import{j as ko}from"./vendors-ByJE77st.js";import{e as re,a as Io}from"./react-DLFRmypc.js";import{U as Eo,V as Po,W as Lo,X as Uo,Y as xo,Z as No,_ as Go}from"./index-gK1XrERn.js";import"./analytics-BTyBkOov.js";import"./utils-BahCaamx.js";import"./dateTime-CKMAqgx1.js";import"./ui-C6uz6_Il.js";import"./media-bEfh4hpP.js";import"./icons-g-Wx_wqN.js";var Qe={exports:{}};/*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com)

Ably JavaScript Library v2.6.0
https://github.com/ably/ably-js

Released under the Apache Licence v2.0*/var qo=Qe.exports,Ss;function Bo(){return Ss||(Ss=1,function(oe,Ft){(function(ee,z){oe.exports=z()})(qo,()=>{var ee={},z={exports:ee},ae=Object.defineProperty,Xe=Object.defineProperties,Ce=Object.getOwnPropertyDescriptor,Ye=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertyNames,te=Object.getOwnPropertySymbols,Ze=Object.prototype.hasOwnProperty,Vt=Object.prototype.propertyIsEnumerable,zt=(e,t,n)=>t in e?ae(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,E=(e,t)=>{for(var n in t||(t={}))Ze.call(t,n)&&zt(e,n,t[n]);if(te)for(var n of te(t))Vt.call(t,n)&&zt(e,n,t[n]);return e},J=(e,t)=>Xe(e,Ye(t)),Ps=(e,t)=>{var n={};for(var s in e)Ze.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&te)for(var s of te(e))t.indexOf(s)<0&&Vt.call(e,s)&&(n[s]=e[s]);return n},Kt=(e,t)=>{for(var n in t)ae(e,n,{get:t[n],enumerable:!0})},Ls=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of K(t))!Ze.call(e,i)&&i!==n&&ae(e,i,{get:()=>t[i],enumerable:!(s=Ce(t,i))||s.enumerable});return e},Us=e=>Ls(ae({},"__esModule",{value:!0}),e),Jt={};Kt(Jt,{ErrorInfo:()=>f,Realtime:()=>kt,Rest:()=>yt,default:()=>To,msgpack:()=>qt,protocolMessageFromDeserialized:()=>ar}),z.exports=Us(Jt);var d=class{},Qt=typeof re<"u"?re:typeof window<"u"?window:self;function Ne(e,t){return`${e}`.padStart(t?3:2,"0")}function xs(e){return d.Config.logTimestamps?function(t){const n=new Date;e(Ne(n.getHours())+":"+Ne(n.getMinutes())+":"+Ne(n.getSeconds())+"."+Ne(n.getMilliseconds(),1)+" "+t)}:function(t){e(t)}}var Ns=()=>{var e;let t,n;return typeof((e=Qt?.console)==null?void 0:e.log)=="function"?(t=function(...s){console.log.apply(console,s)},n=console.warn?function(...s){console.warn.apply(console,s)}:t):t=n=function(){},[t,n].map(xs)},Q=class Ue{constructor(){this.deprecated=(t,n)=>{this.deprecationWarning(`${t} is deprecated and will be removed in a future version. ${n}`)},this.shouldLog=t=>t<=this.logLevel,this.setLog=(t,n)=>{t!==void 0&&(this.logLevel=t),n!==void 0&&(this.logHandler=this.logErrorHandler=n)},this.logLevel=Ue.defaultLogLevel,this.logHandler=Ue.defaultLogHandler,this.logErrorHandler=Ue.defaultLogErrorHandler}static initLogHandlers(){const[t,n]=Ns();this.defaultLogHandler=t,this.defaultLogErrorHandler=n,this.defaultLogger=new Ue}static logActionNoStrip(t,n,s,i){t.logAction(n,s,i)}logAction(t,n,s){this.shouldLog(t)&&(t===1?this.logErrorHandler:this.logHandler)("Ably: "+n+": "+s,t)}renamedClientOption(t,n){this.deprecationWarning(`The \`${t}\` client option has been renamed to \`${n}\`. Please update your code to use \`${n}\` instead. \`${t}\` will be removed in a future version.`)}renamedMethod(t,n,s){this.deprecationWarning(`\`${t}\`’s \`${n}\` method has been renamed to \`${s}\`. Please update your code to use \`${s}\` instead. \`${n}\` will be removed in a future version.`)}deprecationWarning(t){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${t}`,1)}};Q.defaultLogLevel=1,Q.LOG_NONE=0,Q.LOG_ERROR=1,Q.LOG_MAJOR=2,Q.LOG_MINOR=3,Q.LOG_MICRO=4,Q.logAction=(e,t,n,s)=>{Q.logActionNoStrip(e,t,n,s)};var Gs=Q,o=Gs,et={};Kt(et,{Format:()=>an,allSame:()=>on,allToLowerCase:()=>st,allToUpperCase:()=>dn,arrChooseN:()=>un,arrDeleteValue:()=>nn,arrEquals:()=>yn,arrIntersect:()=>en,arrIntersectOb:()=>tn,arrPopRandomElement:()=>tt,arrSubtract:()=>js,arrWithoutValue:()=>Fs,cheapRandStr:()=>qe,containsValue:()=>Ws,copy:()=>ce,createMissingPluginError:()=>De,dataSizeBytes:()=>ln,decodeBody:()=>D,encodeBody:()=>W,ensureArray:()=>Xt,forInOwnNonNullProperties:()=>rn,getBackoffCoefficient:()=>fn,getGlobalObject:()=>rt,getJitterCoefficient:()=>gn,getRetryTime:()=>it,inherits:()=>Hs,inspectBody:()=>cn,inspectError:()=>T,intersect:()=>Zt,isEmpty:()=>Bs,isErrorInfoOrPartialErrorInfo:()=>nt,isNil:()=>H,isObject:()=>le,keysArray:()=>Re,matchDerivedChannel:()=>mn,mixin:()=>w,parseQueryString:()=>Ge,prototypicalClone:()=>Yt,randomString:()=>hn,shallowClone:()=>Ds,shallowEquals:()=>pn,throwMissingPluginError:()=>q,toBase64:()=>Be,toQueryString:()=>we,valuesArray:()=>sn,whenPromiseSettles:()=>N,withTimeoutAsync:()=>vn});function $t(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="+T(e.cause)),e.href&&!(e.message&&e.message.indexOf("help.ably.io")>-1)&&(t+="; see "+e.href+" "),t+="]",t}var f=class Dt extends Error{constructor(t,n,s,i){super(t),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,Dt.prototype),this.code=n,this.statusCode=s,this.cause=i}toString(){return $t(this)}static fromValues(t){const{message:n,code:s,statusCode:i}=t;if(typeof n!="string"||typeof s!="number"||typeof i!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+d.Config.inspect(t));const r=Object.assign(new Dt(n,s,i),t);return r.code&&!r.href&&(r.href="https://help.ably.io/error/"+r.code),r}},P=class Ht extends Error{constructor(t,n,s,i){super(t),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,Ht.prototype),this.code=n,this.statusCode=s,this.cause=i}toString(){return $t(this)}static fromValues(t){const{message:n,code:s,statusCode:i}=t;if(typeof n!="string"||!H(s)&&typeof s!="number"||!H(i)&&typeof i!="number")throw new Error("PartialErrorInfo.fromValues(): invalid values: "+d.Config.inspect(t));const r=Object.assign(new Ht(n,s,i),t);return r.code&&!r.href&&(r.href="https://help.ably.io/error/"+r.code),r}};function qs(e){return Math.floor(Math.random()*e.length)}function w(e,...t){for(let n=0;n<t.length;n++){const s=t[n];if(!s)break;for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e}function ce(e){return w({},e)}function Xt(e){return H(e)?[]:Array.isArray(e)?e:[e]}function le(e){return Object.prototype.toString.call(e)=="[object Object]"}function Bs(e){for(const t in e)return!1;return!0}function H(e){return e==null}function Ds(e){const t=new Object;for(const n in e)t[n]=e[n];return t}function Yt(e,t){class n{}n.prototype=e;const s=new n;return t&&w(s,t),s}var Hs=function(e,t){if(d.Config.inherits){d.Config.inherits(e,t);return}e.super_=t,e.prototype=Yt(t.prototype,{constructor:e})};function Ws(e,t){for(const n in e)if(e[n]==t)return!0;return!1}function Zt(e,t){return Array.isArray(t)?en(e,t):tn(e,t)}function en(e,t){const n=[];for(let s=0;s<e.length;s++){const i=e[s];t.indexOf(i)!=-1&&n.push(i)}return n}function tn(e,t){const n=[];for(let s=0;s<e.length;s++){const i=e[s];i in t&&n.push(i)}return n}function js(e,t){const n=[];for(let s=0;s<e.length;s++){const i=e[s];t.indexOf(i)==-1&&n.push(i)}return n}function nn(e,t){const n=e.indexOf(t),s=n!=-1;return s&&e.splice(n,1),s}function Fs(e,t){const n=e.slice();return nn(n,t),n}function Re(e,t){const n=[];for(const s in e)t&&!Object.prototype.hasOwnProperty.call(e,s)||n.push(s);return n}function sn(e,t){const n=[];for(const s in e)t&&!Object.prototype.hasOwnProperty.call(e,s)||n.push(e[s]);return n}function rn(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function on(e,t){if(e.length===0)return!0;const n=e[0][t];return e.every(function(s){return s[t]===n})}var an=(e=>(e.msgpack="msgpack",e.json="json",e))(an||{});function tt(e){return e.splice(qs(e),1)[0]}function we(e){const t=[];if(e)for(const n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function Ge(e){let t;const n=/([^?&=]+)=?([^&]*)/g,s={};for(;t=n.exec(e);)s[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return s}function nt(e){return typeof e=="object"&&e!==null&&(e instanceof f||e instanceof P)}function T(e){var t,n;return e instanceof Error||((t=e?.constructor)==null?void 0:t.name)==="ErrorInfo"||((n=e?.constructor)==null?void 0:n.name)==="PartialErrorInfo"?e.toString():d.Config.inspect(e)}function cn(e){return d.BufferUtils.isBuffer(e)?e.toString():typeof e=="string"?e:d.Config.inspect(e)}function ln(e){if(d.BufferUtils.isBuffer(e))return d.BufferUtils.byteLength(e);if(typeof e=="string")return d.Config.stringByteSize(e);throw new Error("Expected input of Utils.dataSizeBytes to be a buffer or string, but was: "+typeof e)}function qe(){return String(Math.random()).substr(2)}var hn=async e=>{const t=await d.Config.getRandomArrayBuffer(e);return d.BufferUtils.base64Encode(t)};function un(e,t){const n=Math.min(t,e.length),s=e.slice(),i=[];for(let r=0;r<n;r++)i.push(tt(s));return i}function N(e,t){e.then(n=>{t?.(null,n)}).catch(n=>{t?.(n)})}function D(e,t,n){return n=="msgpack"?(t||q("MsgPack"),t.decode(e)):JSON.parse(String(e))}function W(e,t,n){return n=="msgpack"?(t||q("MsgPack"),t.encode(e,!0)):JSON.stringify(e)}function st(e){return e.map(function(t){return t&&t.toLowerCase()})}function dn(e){return e.map(function(t){return t&&t.toUpperCase()})}function fn(e){return Math.min((e+2)/3,2)}function gn(){return 1-Math.random()*.2}function it(e,t){return e*fn(t)*gn()}function rt(){return typeof re<"u"?re:typeof window<"u"?window:self}function pn(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function mn(e){const t=/^(\[([^?]*)(?:(.*))\])?(.+)$/,n=e.match(t);if(!n||!n.length||n.length<5)throw new f("regex match failed",400,40010);if(n[2])throw new f(`cannot use a derived option with a ${n[2]} channel`,400,40010);return{qualifierParam:n[3]||"",channelName:n[4]}}function Be(e){const t=d.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function yn(e,t){return e.length===t.length&&e.every(function(n,s){return n===t[s]})}function De(e){return new f(`${e} plugin not provided`,40019,400)}function q(e){throw De(e)}async function vn(e,t=5e3,n="Timeout expired"){const s=new f(n,5e4,500);return Promise.race([e,new Promise((i,r)=>setTimeout(()=>r(s),t))])}var bn="2.6.0",Vs="ably-js/"+bn,L={ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:bn,protocolVersion:3,agent:Vs,getHost:Cn,getPort:zs,getHttpScheme:Ks,environmentFallbackHosts:Rn,getFallbackHosts:wn,getHosts:Js,checkHost:On,objectifyOptions:Xs,normaliseOptions:Ys,defaultGetHeaders:Zs,defaultPostHeaders:ei};function Cn(e,t,n){return n?t=t==e.restHost&&e.realtimeHost||t||e.realtimeHost:t=t||e.restHost,t}function zs(e,t){return t||e.tls?e.tlsPort:e.port}function Ks(e){return e.tls?"https://":"http://"}function Rn(e){return[e+"-a-fallback.ably-realtime.com",e+"-b-fallback.ably-realtime.com",e+"-c-fallback.ably-realtime.com",e+"-d-fallback.ably-realtime.com",e+"-e-fallback.ably-realtime.com"]}function wn(e){const t=e.fallbackHosts,n=typeof e.httpMaxRetryCount<"u"?e.httpMaxRetryCount:L.httpMaxRetryCount;return t?un(t,n):[]}function Js(e,t){const n=[e.restHost].concat(wn(e));return t?n.map(s=>Cn(e,s,!0)):n}function On(e){if(typeof e!="string")throw new f("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new f("host must not be zero-length",4e4,400)}function Qs(e,t,n,s){return e.realtimeHost?e.realtimeHost:e.restHost?(o.logAction(s,o.LOG_MINOR,"Defaults.normaliseOptions",'restHost is set to "'+e.restHost+'" but realtimeHost is not set, so setting realtimeHost to "'+e.restHost+'" too. If this is not what you want, please set realtimeHost explicitly.'),e.restHost):t?L.REALTIME_HOST:n+"-"+L.REALTIME_HOST}function $s(e){const t={};for(const n in L.TIMEOUTS)t[n]=e[n]||L.TIMEOUTS[n];return t}function ot(e){let t=L.agent;if(e.agents)for(var n in e.agents)t+=" "+n+"/"+e.agents[n];return t}function Xs(e,t,n,s,i){if(e===void 0){const a=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 o.logAction(s,o.LOG_ERROR,`${n}()`,a),new Error(a)}let r;if(typeof e=="string")if(e.indexOf(":")==-1){if(!t){const a=`${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’s \`token\` property.)`;throw o.logAction(s,o.LOG_ERROR,`${n}()`,a),new Error(a)}r={token:e}}else{if(!t){const a=`${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’s \`key\` property.)`;throw o.logAction(s,o.LOG_ERROR,`${n}()`,a),new Error(a)}r={key:e}}else r=e;return i&&(r=J(E({},r),{plugins:E(E({},i),r.plugins)})),r}function Ys(e,t,n){const s=n??o.defaultLogger;typeof e.recover=="function"&&e.closeOnUnload===!0&&(o.logAction(s,o.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);const i=e.environment&&String(e.environment).toLowerCase()||L.ENVIRONMENT,r=!i||i==="production";!e.fallbackHosts&&!e.restHost&&!e.realtimeHost&&!e.port&&!e.tlsPort&&(e.fallbackHosts=r?L.FALLBACK_HOSTS:Rn(i));const a=e.restHost||(r?L.REST_HOST:i+"-"+L.REST_HOST),c=Qs(e,r,i,s);(e.fallbackHosts||[]).concat(a,c).forEach(On),e.port=e.port||L.PORT,e.tlsPort=e.tlsPort||L.TLS_PORT,"tls"in e||(e.tls=!0);const h=$s(e);t?"useBinaryProtocol"in e?e.useBinaryProtocol=d.Config.supportsBinary&&e.useBinaryProtocol:e.useBinaryProtocol=d.Config.preferBinary:e.useBinaryProtocol=!1;const l={};e.clientId&&(l["X-Ably-ClientId"]=d.BufferUtils.base64Encode(d.BufferUtils.utf8Encode(e.clientId))),"idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0);let u=null,g=e.connectivityCheckUrl;if(e.connectivityCheckUrl){let[p,v]=e.connectivityCheckUrl.split("?");u=v?Ge(v):{},p.indexOf("://")===-1&&(p="https://"+p),g=p}let m=e.wsConnectivityCheckUrl;return m&&m.indexOf("://")===-1&&(m="wss://"+m),J(E({},e),{realtimeHost:c,restHost:a,maxMessageSize:e.maxMessageSize||L.maxMessageSize,timeouts:h,connectivityCheckParams:u,connectivityCheckUrl:g,wsConnectivityCheckUrl:m,headers:l})}function He(e,t,n){const s=n||{};if(s.cipher){e||q("Crypto");const i=e.getCipher(s.cipher,t);s.cipher=i.cipherParams,s.channelCipher=i.cipher}else"cipher"in s&&(s.cipher=void 0,s.channelCipher=null);return s}var An={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},We={format:"json",protocolVersion:L.protocolVersion};function Zs(e,{format:t=We.format,protocolVersion:n=We.protocolVersion}={}){return{accept:An[t],"X-Ably-Version":n.toString(),"Ably-Agent":ot(e)}}function ei(e,{format:t=We.format,protocolVersion:n=We.protocolVersion}={}){let s;return{accept:s=An[t],"content-type":s,"X-Ably-Version":n.toString(),"Ably-Agent":ot(e)}}var C=L;function ti(e){return Object.assign(L,e)}var ni=class _s{constructor(t,n){this.logger=t,this.members=n||[]}call(t,n){for(const s of this.members)if(s)try{s(t,n)}catch(i){o.logAction(this.logger,o.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+i+"; stack = "+i.stack)}}push(...t){this.members.push(...t)}createPromise(){return new Promise((t,n)=>{this.push((s,i)=>{s?n(s):t(i)})})}resolveAll(t){this.call(null,t)}rejectAll(t){this.call(t)}static create(t,n){const s=new _s(t,n);return Object.assign((i,r)=>s.call(i,r),{push:i=>s.push(i),createPromise:()=>s.createPromise(),resolveAll:i=>s.resolveAll(i),rejectAll:i=>s.rejectAll(i)})}},at=ni,Sn=(e=>(e.Get="get",e.Delete="delete",e.Post="post",e.Put="put",e.Patch="patch",e))(Sn||{}),M=Sn,_n=(e=>(e[e.Success=200]="Success",e[e.NoContent=204]="NoContent",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.Forbidden=403]="Forbidden",e[e.RequestTimeout=408]="RequestTimeout",e[e.InternalServerError=500]="InternalServerError",e))(_n||{});function si(e){return e>=200&&e<400}var je=_n,ct=Math.pow(2,17);function ii(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function ri(e){return!!e.connection}function Tn(e){return nt(e)?(e.code||(e.statusCode===403?e.code=40300:(e.code=40170,e.statusCode=401)),e):new f(T(e),e.code||40170,e.statusCode||401)}var oi=(e,t)=>{const n=d.BufferUtils,s=n.utf8Encode(e),i=n.utf8Encode(t),r=n.hmacSha256(s,i);return n.base64Encode(r)};function Mn(e){if(!e)return"";typeof e=="string"&&(e=JSON.parse(e));const t=Object.create(null),n=Re(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 kn(e,t){if(e.authCallback)o.logAction(t,o.LOG_MINOR,"Auth()","using token auth with authCallback");else if(e.authUrl)o.logAction(t,o.LOG_MINOR,"Auth()","using token auth with authUrl");else if(e.key)o.logAction(t,o.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(e.tokenDetails)o.logAction(t,o.LOG_MINOR,"Auth()","using token auth with supplied token only");else{const n="authOptions must include valid authentication parameters";throw o.logAction(t,o.LOG_ERROR,"Auth()",n),new Error(n)}}function ai(e){return"useTokenAuth"in e&&!e.useTokenAuth}function In(e){return e.useTokenAuth||!ai(e)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}function ci(e){return!e.key&&!e.authCallback&&!e.authUrl}var li=0;function hi(){return li++}var ui=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,In(t))ci(t)&&o.logAction(this.logger,o.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),kn(this.authOptions,this.logger);else{if(!t.key){const n="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw o.logAction(this.logger,o.LOG_ERROR,"Auth()",n),new f(n,40160,401)}o.logAction(this.logger,o.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(t)}}get logger(){return this.client.logger}async authorize(e,t){if(t&&t.key&&this.authOptions.key!==t.key)throw new f("Unable to update auth options with incompatible key",40102,401);try{let n=await this._forceNewToken(e??null,t??null);return ri(this.client)?new Promise((s,i)=>{this.client.connection.connectionManager.onAuthUpdated(n,(r,a)=>r?i(r):s(a))}):n}catch(n){throw this.client.connection&&n.statusCode===je.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(n),n}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),kn(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(e,t){const n=t||this.authOptions,s=e||ce(this.tokenParams);let i,r=this.client;if(n.authCallback)o.logAction(this.logger,o.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),i=n.authCallback;else if(n.authUrl)o.logAction(this.logger,o.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),i=(c,h)=>{const l=w({accept:"application/json, text/plain"},n.authHeaders),u=n.authMethod&&n.authMethod.toLowerCase()==="post";let g;const m=n.authUrl.indexOf("?");m>-1&&(g=Ge(n.authUrl.slice(m)),n.authUrl=n.authUrl.slice(0,m),u||(n.authParams=w(g,n.authParams)));const p=w({},n.authParams||{},c),v=y=>{var b,A;let S=(b=y.body)!=null?b:null,_=null;if(y.error)o.logAction(this.logger,o.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+T(y.error));else{const x=(A=y.headers["content-type"])!=null?A:null;Array.isArray(x)?_=x.join(", "):_=x,o.logAction(this.logger,o.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+_+"; body: "+cn(S))}if(y.error){h(y.error,null);return}if(y.unpacked){h(null,S);return}if(d.BufferUtils.isBuffer(S)&&(S=S.toString()),!_){h(new f("authUrl response is missing a content-type header",40170,401),null);return}const R=_.indexOf("application/json")>-1,B=_.indexOf("text/plain")>-1||_.indexOf("application/jwt")>-1;if(!R&&!B){h(new f("authUrl responded with unacceptable content-type "+_+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(R){if(S.length>ct){h(new f("authUrl response exceeded max permitted length",40170,401),null);return}try{S=JSON.parse(S)}catch(x){h(new f("Unexpected error processing authURL response; err = "+x.message,40170,401),null);return}}h(null,S,_)};if(o.logAction(this.logger,o.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+n.authUrl+"; Params: "+JSON.stringify(p)+"; method: "+(u?"POST":"GET")),u){const y=l||{};y["content-type"]="application/x-www-form-urlencoded";const b=we(p).slice(1);N(this.client.http.doUri(M.Post,n.authUrl,y,b,g),(A,S)=>v(A||S))}else N(this.client.http.doUri(M.Get,n.authUrl,l||{},null,p),(y,b)=>v(y||b))};else if(n.key)o.logAction(this.logger,o.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),i=(c,h)=>{N(this.createTokenRequest(c,n),(l,u)=>h(l,u??null))};else{const c="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw o.logAction(this.logger,o.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 f(c,40171,403)}"capability"in s&&(s.capability=Mn(s.capability));const a=(c,h)=>{const l=c.keyName,u="/keys/"+l+"/requestToken",g=function(p){return r.baseUri(p)+u},m=C.defaultPostHeaders(this.client.options);n.requestHeaders&&w(m,n.requestHeaders),o.logAction(this.logger,o.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+u+"; Token params: "+JSON.stringify(c)),N(this.client.http.do(M.Post,g,m,JSON.stringify(c),null),(p,v)=>p?h(p):h(v.error,v.body,v.unpacked))};return new Promise((c,h)=>{let l=!1,u=this.client.options.timeouts.realtimeRequestTimeout,g=setTimeout(()=>{l=!0;const m="Token request callback timed out after "+u/1e3+" seconds";o.logAction(this.logger,o.LOG_ERROR,"Auth.requestToken()",m),h(new f(m,40170,401))},u);i(s,(m,p,v)=>{if(l)return;if(clearTimeout(g),m){o.logAction(this.logger,o.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+T(m)),h(Tn(m));return}if(typeof p=="string"){p.length===0?h(new f("Token string is empty",40170,401)):p.length>ct?h(new f("Token string exceeded max permitted length (was "+p.length+" bytes)",40170,401)):p==="undefined"||p==="null"?h(new f("Token string was literal null/undefined",40170,401)):p[0]==="{"&&!(v&&v.indexOf("application/jwt")>-1)?h(new f("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):c({token:p});return}if(typeof p!="object"||p===null){const b="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof p;o.logAction(this.logger,o.LOG_ERROR,"Auth.requestToken()",b),h(new f(b,40170,401));return}const y=JSON.stringify(p).length;if(y>ct&&!n.suppressMaxLengthCheck){h(new f("Token request/details object exceeded max permitted stringified size (was "+y+" bytes)",40170,401));return}if("issued"in p){c(p);return}if(!("keyName"in p)){const b="Expected token request callback to call back with a token string, token request object, or token details object";o.logAction(this.logger,o.LOG_ERROR,"Auth.requestToken()",b),h(new f(b,40170,401));return}a(p,(b,A,S)=>{if(b){o.logAction(this.logger,o.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+T(b)),h(Tn(b));return}S||(A=JSON.parse(A)),o.logAction(this.logger,o.LOG_MINOR,"Auth.getToken()","token received"),c(A)})})})}async createTokenRequest(e,t){t=t||this.authOptions,e=e||ce(this.tokenParams);const n=t.key;if(!n)throw new f("No key specified",40101,403);const s=n.split(":"),i=s[0],r=s[1];if(!r)throw new f("Invalid key specified",40101,403);if(e.clientId==="")throw new f("clientId can’t be an empty string",40012,400);"capability"in e&&(e.capability=Mn(e.capability));const a=w({keyName:i},e),c=e.clientId||"",h=e.ttl||"",l=e.capability||"";a.timestamp||(a.timestamp=await this.getTimestamp(t&&t.queryTime));const u=a.nonce||(a.nonce=ii()),g=a.timestamp,m=a.keyName+`
`+h+`
`+l+`
`+c+`
`+g+`
`+u+`
`;return a.mac=a.mac||oi(m,r),o.logAction(this.logger,o.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),a}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{const e=await this._ensureValidAuthCredentials(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Be(e.token)}}}async getTimestamp(e){return!this.isTimeOffsetSet()&&(e||this.authOptions.queryTime)?this.client.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.client.serverTimeOffset||0)}isTimeOffsetSet(){return this.client.serverTimeOffset!==null}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=Be(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=typeof t.token=="string"?{token:t.token}:t.token),t.tokenDetails&&(this.tokenDetails=t.tokenDetails),"clientId"in t&&this._userSetClientId(t.clientId),this.authOptions=t)}async _ensureValidAuthCredentials(e){const t=this.tokenDetails;if(t){if(this._tokenClientIdMismatch(t.clientId))throw new f("Mismatch between clientId in token ("+t.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.isTimeOffsetSet()||!t.expires||t.expires>=this.getTimestampUsingOffset())return o.logAction(this.logger,o.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+t.expires),t;o.logAction(this.logger,o.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}const n=(this.waitingForTokenRequest||(this.waitingForTokenRequest=at.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!e)return n;const s=this.currentTokenRequestId=hi();let i,r=null;try{i=await this.requestToken(this.tokenParams,this.authOptions)}catch(c){r=c}if(this.currentTokenRequestId>s)return o.logAction(this.logger,o.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),n;this.currentTokenRequestId=null;const a=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,r?(a?.rejectAll(r),n):(a?.resolveAll(this.tokenDetails=i),n)}_userSetClientId(e){if(typeof e=="string"||e===null){if(e==="*")throw new f('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{const t=this._uncheckedSetClientId(e);if(t)throw t}}else throw new f("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(e){if(this._tokenClientIdMismatch(e)){const t="Unexpected clientId mismatch: client has "+this.clientId+", requested "+e,n=new f(t,40102,401);return o.logAction(this.logger,o.LOG_ERROR,"Auth._uncheckedSetClientId()",t),n}else return this.clientId=this.tokenParams.clientId=e,null}_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)}},$=ui;function lt(e){const t=[];if(e)for(const n in e)t.push(n+"="+e[n]);return t.join("&")}function he(e,t){return e+(t?"?":"")+lt(t)}function di(e,t,n,s,i){e.error?o.logActionNoStrip(i,o.LOG_MICRO,"Http."+t+"()","Received Error; "+he(n,s)+"; Error: "+T(e.error)):o.logActionNoStrip(i,o.LOG_MICRO,"Http."+t+"()","Received; "+he(n,s)+"; Headers: "+lt(e.headers)+"; StatusCode: "+e.statusCode+"; Body"+(d.BufferUtils.isBuffer(e.body)?" (Base64): "+d.BufferUtils.base64Encode(e.body):": "+e.body))}function fi(e,t,n,s,i){i.shouldLog(o.LOG_MICRO)&&o.logActionNoStrip(i,o.LOG_MICRO,"Http."+e+"()","Sending; "+he(t,s)+"; Body"+(d.BufferUtils.isBuffer(n)?" (Base64): "+d.BufferUtils.base64Encode(n):": "+n))}var ht=class{constructor(e){this.client=e,this.platformHttp=new d.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var e,t;return(t=(e=this.client)==null?void 0:e.logger)!=null?t:o.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(e){const t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(C.getFallbackHosts(e.options)):C.getHosts(e.options)}async do(e,t,n,s,i){try{const r=this.client;if(!r)return{error:new f("http.do called without client",5e4,500)};const a=typeof t=="function"?t:function(g){return r.baseUri(g)+t},c=r._currentFallback;if(c)if(c.validUntil>Date.now()){const g=await this.doUri(e,a(c.host),n,s,i);return g.error&&this.platformHttp.shouldFallback(g.error)?(r._currentFallback=null,this.do(e,t,n,s,i)):g}else r._currentFallback=null;const h=this._getHosts(r);if(h.length===1)return this.doUri(e,a(h[0]),n,s,i);let l=null;const u=async(g,m)=>{const p=g.shift();l=l??new Date;const v=await this.doUri(e,a(p),n,s,i);return v.error&&this.platformHttp.shouldFallback(v.error)&&g.length?Date.now()-l.getTime()>r.options.timeouts.httpMaxRetryDuration?{error:new f(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${r.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:u(g,!0):(m&&(r._currentFallback={host:p,validUntil:Date.now()+r.options.timeouts.fallbackRetryTimeout}),v)};return u(h)}catch(r){return{error:new f(`Unexpected error in Http.do: ${T(r)}`,500,5e4)}}}async doUri(e,t,n,s,i){try{fi(e,t,s,i,this.logger);const r=await this.platformHttp.doUri(e,t,n,s,i);return this.logger.shouldLog(o.LOG_MICRO)&&di(r,e,t,i,this.logger),r}catch(r){return{error:new f(`Unexpected error in Http.doUri: ${T(r)}`,500,5e4)}}}},En=class{constructor(e){this.Platform=d,this.ErrorInfo=f,this.Logger=o,this.Defaults=C,this.Utils=et;var t,n,s,i,r,a,c,h;this._additionalHTTPRequestImplementations=(t=e.plugins)!=null?t:null,this.logger=new o,this.logger.setLog(e.logLevel,e.logHandler),o.logAction(this.logger,o.LOG_MICRO,"BaseClient()","initialized with clientOptions "+d.Config.inspect(e)),this._MsgPack=(s=(n=e.plugins)==null?void 0:n.MsgPack)!=null?s:null;const l=this.options=C.normaliseOptions(e,this._MsgPack,this.logger);if(l.key){const u=l.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!u){const g="invalid key parameter";throw o.logAction(this.logger,o.LOG_ERROR,"BaseClient()",g),new f(g,40400,404)}l.keyName=u[1],l.keySecret=u[2]}if("clientId"in l)if(typeof l.clientId=="string"||l.clientId===null){if(l.clientId==="*")throw new f('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new f("clientId must be either a string or null",40012,400);o.logAction(this.logger,o.LOG_MINOR,"BaseClient()","started; version = "+C.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new ht(this),this.auth=new $(this,l),this._rest=(i=e.plugins)!=null&&i.Rest?new e.plugins.Rest(this):null,this._Crypto=(a=(r=e.plugins)==null?void 0:r.Crypto)!=null?a:null,this.__FilteredSubscriptions=(h=(c=e.plugins)==null?void 0:c.MessageInteractions)!=null?h:null}get rest(){return this._rest||q("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||q("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}get device(){var e;return(!((e=this.options.plugins)!=null&&e.Push)||!this.push.LocalDevice)&&q("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(e){return C.getHttpScheme(this.options)+e+":"+C.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)}};En.Platform=d;var Pn=En,gi=class ve{toJSON(){var t,n,s;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(t=this.push)==null?void 0:t.recipient,state:(n=this.push)==null?void 0:n.state,error:(s=this.push)==null?void 0:s.error}}}toString(){var t,n,s,i;let r="[DeviceDetails";return this.id&&(r+="; id="+this.id),this.platform&&(r+="; platform="+this.platform),this.formFactor&&(r+="; formFactor="+this.formFactor),this.clientId&&(r+="; clientId="+this.clientId),this.metadata&&(r+="; metadata="+this.metadata),this.deviceIdentityToken&&(r+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(t=this.push)!=null&&t.recipient&&(r+="; push.recipient="+JSON.stringify(this.push.recipient)),(n=this.push)!=null&&n.state&&(r+="; push.state="+this.push.state),(s=this.push)!=null&&s.error&&(r+="; push.error="+JSON.stringify(this.push.error)),(i=this.push)!=null&&i.metadata&&(r+="; push.metadata="+this.push.metadata),r+="]",r}static toRequestBody(t,n,s){return W(t,n,s)}static fromResponseBody(t,n,s){return s&&(t=D(t,n,s)),Array.isArray(t)?ve.fromValuesArray(t):ve.fromValues(t)}static fromValues(t){return t.error=t.error&&f.fromValues(t.error),Object.assign(new ve,t)}static fromLocalDevice(t){return Object.assign(new ve,t)}static fromValuesArray(t){const n=t.length,s=new Array(n);for(let i=0;i<n;i++)s[i]=ve.fromValues(t[i]);return s}},ue=gi;async function Ln(e,t,n,s){if(e.http.supportsAuthHeaders){const i=await e.auth.getAuthHeaders();return s(w(i,t),n)}else{const i=await e.auth.getAuthParams();return s(t,w(i,n))}}function pi(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===je.NoContent)return J(E({},e),{body:[],unpacked:!0});let s=e.body;if(!e.unpacked)try{s=D(s,t,n)}catch(c){return nt(c)?{err:c}:{err:new P(T(c),null)}}if(!s)return{err:new P("unenvelope(): Response body is missing",null)};const{statusCode:i,response:r,headers:a}=s;if(i===void 0)return J(E({},e),{body:s,unpacked:!0});if(i<200||i>=300){let c=r&&r.error||e.err;return c||(c=new Error("Error in unenveloping "+s),c.statusCode=i),{err:c,body:r,headers:a,unpacked:!0,statusCode:i}}return{err:e.err,body:r,headers:a,unpacked:!0,statusCode:i}}function mi(e,t,n,s,i){e.err?o.logAction(i,o.LOG_MICRO,"Resource."+t+"()","Received Error; "+he(n,s)+"; Error: "+T(e.err)):o.logAction(i,o.LOG_MICRO,"Resource."+t+"()","Received; "+he(n,s)+"; Headers: "+lt(e.headers)+"; StatusCode: "+e.statusCode+"; Body: "+(d.BufferUtils.isBuffer(e.body)?" (Base64): "+d.BufferUtils.base64Encode(e.body):": "+d.Config.inspect(e.body)))}var yi=class be{static async get(t,n,s,i,r,a){return be.do(M.Get,t,n,null,s,i,r,a??!1)}static async delete(t,n,s,i,r,a){return be.do(M.Delete,t,n,null,s,i,r,a)}static async post(t,n,s,i,r,a,c){return be.do(M.Post,t,n,s,i,r,a,c)}static async patch(t,n,s,i,r,a,c){return be.do(M.Patch,t,n,s,i,r,a,c)}static async put(t,n,s,i,r,a,c){return be.do(M.Put,t,n,s,i,r,a,c)}static async do(t,n,s,i,r,a,c,h){c&&((a=a||{}).envelope=c);const l=n.logger;async function u(m,p){var v;if(l.shouldLog(o.LOG_MICRO)){let b=i;if(((v=m["content-type"])==null?void 0:v.indexOf("msgpack"))>0)try{n._MsgPack||q("MsgPack"),b=n._MsgPack.decode(i)}catch(A){o.logAction(l,o.LOG_MICRO,"Resource."+t+"()","Sending MsgPack Decoding Error: "+T(A))}o.logAction(l,o.LOG_MICRO,"Resource."+t+"()","Sending; "+he(s,p)+"; Body: "+b)}const y=await n.http.do(t,s,m,i,p);return y.error&&$.isTokenErr(y.error)?(await n.auth.authorize(null,null),Ln(n,m,p,u)):{err:y.error,body:y.body,headers:y.headers,unpacked:y.unpacked,statusCode:y.statusCode}}let g=await Ln(n,r,a,u);if(c&&(g=pi(g,n._MsgPack,c)),l.shouldLog(o.LOG_MICRO)&&mi(g,t,s,a,l),h){if(g.err)throw g.err;{const m=E({},g);return delete m.err,m}}return g}},I=yi;function vi(e){const t=e.match(/^\.\/(\w+)\?(.*)$/);return t&&t[2]&&Ge(t[2])}function bi(e){typeof e=="string"&&(e=e.split(","));const t={};for(let n=0;n<e.length;n++){const s=e[n].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(s){const i=vi(s[1]);i&&(t[s[2]]=i)}}return t}function Ci(e,t,n){return!(n&&(t||typeof e.code=="number"))}var Ri=class{constructor(e,t,n,s,i,r){this.client=e,this.path=t,this.headers=n,this.envelope=s??null,this.bodyHandler=i,this.useHttpPaginatedResponse=r||!1}get logger(){return this.client.logger}async get(e){const t=await I.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){const t=await I.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){const n=await I.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){const n=await I.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){const n=await I.patch(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async handlePage(e){if(e.err&&Ci(e.err,e.body,this.useHttpPaginatedResponse))throw o.logAction(this.logger,o.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+T(e.err)),e.err;let t,n,s;try{t=e.statusCode==je.NoContent?[]:await this.bodyHandler(e.body,e.headers||{},e.unpacked)}catch(i){throw e.err||i}return e.headers&&(n=e.headers.Link||e.headers.link)&&(s=bi(n)),this.useHttpPaginatedResponse?new wi(this,t,e.headers||{},e.statusCode,s,e.err):new Un(this,t,s)}},Un=class{constructor(e,t,n){this.resource=e,this.items=t;const s=this;n&&("first"in n&&(this.first=async function(){return s.get(n.first)}),"current"in n&&(this.current=async function(){return s.get(n.current)}),this.next=async function(){return"next"in n?s.get(n.next):null},this.hasNext=function(){return"next"in n},this.isLast=()=>{var i;return!((i=this.hasNext)!=null&&i.call(this))})}async get(e){const t=this.resource,n=await I.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}},wi=class extends Un{constructor(e,t,n,s,i,r){super(e,t,i),this.statusCode=s,this.success=s<300&&s>=200,this.headers=n,this.errorCode=r&&r.code,this.errorMessage=r&&r.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},ne=Ri,xn=class xe{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let t="[PushChannelSubscription";return this.channel&&(t+="; channel="+this.channel),this.deviceId&&(t+="; deviceId="+this.deviceId),this.clientId&&(t+="; clientId="+this.clientId),t+="]",t}static fromResponseBody(t,n,s){return s&&(t=D(t,n,s)),Array.isArray(t)?xe.fromValuesArray(t):xe.fromValues(t)}static fromValues(t){return Object.assign(new xe,t)}static fromValuesArray(t){const n=t.length,s=new Array(n);for(let i=0;i<n;i++)s[i]=xe.fromValues(t[i]);return s}};xn.toRequestBody=W;var Oi=xn,ut=Oi,Ai=class{constructor(e){var t;this.client=e,this.admin=new Si(e),d.Config.push&&((t=e.options.plugins)!=null&&t.Push)&&(this.stateMachine=new e.options.plugins.Push.ActivationStateMachine(e),this.LocalDevice=e.options.plugins.Push.localDeviceFactory(ue))}async activate(e,t){await new Promise((n,s)=>{var i;if(!((i=this.client.options.plugins)!=null&&i.Push)){s(De("Push"));return}if(!this.stateMachine){s(new f("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){s(new f("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=r=>{if(r){s(r);return}n()},this.stateMachine.updateFailedCallback=t,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,e))})}async deactivate(e){await new Promise((t,n)=>{var s;if(!((s=this.client.options.plugins)!=null&&s.Push)){n(De("Push"));return}if(!this.stateMachine){n(new f("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){n(new f("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=i=>{if(i){n(i);return}t()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,e))})}},Si=class{constructor(e){this.client=e,this.deviceRegistrations=new _i(e),this.channelSubscriptions=new Ti(e)}async publish(e,t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=C.defaultPostHeaders(n.options,{format:s}),r={},a=w({recipient:e},t);w(i,n.options.headers),n.options.pushFullWait&&w(r,{fullWait:"true"});const c=W(a,n._MsgPack,s);await I.post(n,"/push/publish",c,i,r,null,!0)}},_i=class{constructor(e){this.client=e}async save(e){const t=this.client,n=ue.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=C.defaultPostHeaders(t.options,{format:s}),r={};w(i,t.options.headers),t.options.pushFullWait&&w(r,{fullWait:"true"});const a=W(n,t._MsgPack,s),c=await I.put(t,"/push/deviceRegistrations/"+encodeURIComponent(e.id),a,i,r,null,!0);return ue.fromResponseBody(c.body,t._MsgPack,c.unpacked?void 0:s)}async get(e){const t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=C.defaultGetHeaders(t.options,{format:n}),i=e.id||e;if(typeof i!="string"||!i.length)throw new f("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);w(s,t.options.headers);const r=await I.get(t,"/push/deviceRegistrations/"+encodeURIComponent(i),s,{},null,!0);return ue.fromResponseBody(r.body,t._MsgPack,r.unpacked?void 0:n)}async list(e){const t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,i=C.defaultGetHeaders(t.options,{format:n});return w(i,t.options.headers),new ne(t,"/push/deviceRegistrations",i,s,async function(r,a,c){return ue.fromResponseBody(r,t._MsgPack,c?void 0:n)}).get(e)}async remove(e){const t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=C.defaultGetHeaders(t.options,{format:n}),i={},r=e.id||e;if(typeof r!="string"||!r.length)throw new f("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);w(s,t.options.headers),t.options.pushFullWait&&w(i,{fullWait:"true"}),await I.delete(t,"/push/deviceRegistrations/"+encodeURIComponent(r),s,i,null,!0)}async removeWhere(e){const t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=C.defaultGetHeaders(t.options,{format:n});w(s,t.options.headers),t.options.pushFullWait&&w(e,{fullWait:"true"}),await I.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},Ti=class Ts{constructor(t){this.remove=Ts.prototype.removeWhere,this.client=t}async save(t){const n=this.client,s=ut.fromValues(t),i=n.options.useBinaryProtocol?"msgpack":"json",r=C.defaultPostHeaders(n.options,{format:i}),a={};w(r,n.options.headers),n.options.pushFullWait&&w(a,{fullWait:"true"});const c=W(s,n._MsgPack,i),h=await I.post(n,"/push/channelSubscriptions",c,r,a,null,!0);return ut.fromResponseBody(h.body,n._MsgPack,h.unpacked?void 0:i)}async list(t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=this.client.http.supportsLinkHeaders?void 0:s,r=C.defaultGetHeaders(n.options,{format:s});return w(r,n.options.headers),new ne(n,"/push/channelSubscriptions",r,i,async function(a,c,h){return ut.fromResponseBody(a,n._MsgPack,h?void 0:s)}).get(t)}async removeWhere(t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=C.defaultGetHeaders(n.options,{format:s});w(i,n.options.headers),n.options.pushFullWait&&w(t,{fullWait:"true"}),await I.delete(n,"/push/channelSubscriptions",i,t,null,!0)}async listChannels(t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=this.client.http.supportsLinkHeaders?void 0:s,r=C.defaultGetHeaders(n.options,{format:s});return w(r,n.options.headers),n.options.pushFullWait&&w(t,{fullWait:"true"}),new ne(n,"/push/channels",r,i,async function(a,c,h){const l=!h&&s?D(a,n._MsgPack,s):a;for(let u=0;u<l.length;u++)l[u]=String(l[u]);return l}).get(t)}},Mi=Ai,Nn=["message.unset","message.create","message.update","message.delete","annotation.create","annotation.delete","meta.occupancy"],ki=new Map(Nn.map((e,t)=>[e,t])),Ii=new Map(Nn.map((e,t)=>[t,e]));function Ei(e){return Ii.get(e)}function Pi(e){return e?ki.get(e):void 0}function Li(e){return!e||!e.channelOptions?{channelOptions:e,plugins:{},baseEncodedPreviousPayload:void 0}:e}function Gn(e,t,n){if(n&&n.cipher){e||q("Crypto");const s=e.getCipher(n.cipher,t);return{cipher:s.cipherParams,channelCipher:s.cipher}}return n??{}}function Ui(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+=ln(e.data)),t}async function qn(e,t,n,s){const i=Fe(n),r=Gn(t,e,s??null);try{await Oe(i,r)}catch(a){o.logAction(e,o.LOG_ERROR,"Message.fromEncoded()",a.toString())}return i}async function xi(e,t,n,s){return Promise.all(n.map(function(i){return qn(e,t,i,s)}))}async function Ni(e,t){const n=Fe(e);try{await Oe(n,t.channelOptions)}catch(s){o.logAction(t.logger,o.LOG_ERROR,"Message._fromEncoded()",s.toString())}return n}async function Gi(e,t){return Promise.all(e.map(function(n){return Ni(n,t)}))}async function qi(e,t){let n=e.data,s=e.encoding,i=t.channelCipher;s=s?s+"/":"",d.BufferUtils.isBuffer(n)||(n=d.BufferUtils.utf8Encode(String(n)),s=s+"utf-8/");const r=await i.encrypt(n);return e.data=r,e.encoding=s+"cipher+"+i.algorithm,e}async function dt(e,t){const n=e.data;if(!(typeof n=="string"||d.BufferUtils.isBuffer(n)||n===null||n===void 0))if(le(n)||Array.isArray(n))e.data=JSON.stringify(n),e.encoding=e.encoding?e.encoding+"/json":"json";else throw new f("Data type is unsupported",40013,400);return t!=null&&t.cipher?qi(e,t):e}async function Bn(e,t){return Promise.all(e.map(n=>dt(n,t)))}var Bi=W;async function Oe(e,t){const n=Li(t);let s=e.data;const i=e.encoding;if(i){const r=i.split("/");let a,c=r.length,h=e.data,l="";try{for(;(a=c)>0;){const u=r[--c].match(/([-\w]+)(\+([\w-]+))?/);if(!u)break;switch(l=u[1],l){case"base64":h=d.BufferUtils.base64Decode(String(h)),a==r.length&&(s=h);continue;case"utf-8":h=d.BufferUtils.utf8Decode(h);continue;case"json":h=JSON.parse(h);continue;case"cipher":if(n.channelOptions!=null&&n.channelOptions.cipher&&n.channelOptions.channelCipher){const g=u[3],m=n.channelOptions.channelCipher;if(g!=m.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");h=await m.decrypt(h);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!n.plugins||!n.plugins.vcdiff)throw new f("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new f("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let g=n.baseEncodedPreviousPayload;typeof g=="string"&&(g=d.BufferUtils.utf8Encode(g));const m=d.BufferUtils.toBuffer(g);h=d.BufferUtils.toBuffer(h),h=d.BufferUtils.arrayBufferViewToBuffer(n.plugins.vcdiff.decode(h,m)),s=h}catch(g){throw new f("Vcdiff delta decode failed with "+g,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(u){const g=u;throw new f("Error processing the "+l+" encoding, decoder returned ‘"+g.message+"’",g.code||40013,400)}finally{e.encoding=a<=0?null:r.slice(0,a).join("/"),e.data=h}}n.baseEncodedPreviousPayload=s}function de(e){return Object.assign(new pt,e)}function Fe(e){const t=Ei(e.action)||e.action,n=Object.assign(new pt,J(E({},e),{action:t}));return n.expandFields(),n}function ft(e){return e.map(de)}function gt(e){let t,n=0;for(let s=0;s<e.length;s++)t=e[s],n+=t.size||(t.size=Ui(t));return n}var pt=class{toJSON(){let e=this.encoding,t=this.data;return t&&d.BufferUtils.isBuffer(t)&&(arguments.length>0?(e=e?e+"/base64":"base64",t=d.BufferUtils.base64Encode(t)):t=d.BufferUtils.toBuffer(t)),{name:this.name,id:this.id,clientId:this.clientId,connectionId:this.connectionId,connectionKey:this.connectionKey,extras:this.extras,serial:this.serial,action:Pi(this.action)||this.action,refSerial:this.refSerial,refType:this.refType,createdAt:this.createdAt,version:this.version,operation:this.operation,encoding:e,data:t}}expandFields(){this.action==="message.create"&&(this.version&&!this.serial&&(this.serial=this.version),this.timestamp&&!this.createdAt&&(this.createdAt=this.timestamp))}toString(){let e="[Message";return this.name&&(e+="; name="+this.name),this.id&&(e+="; id="+this.id),this.timestamp&&(e+="; timestamp="+this.timestamp),this.clientId&&(e+="; clientId="+this.clientId),this.connectionId&&(e+="; connectionId="+this.connectionId),this.encoding&&(e+="; encoding="+this.encoding),this.extras&&(e+="; extras ="+JSON.stringify(this.extras)),this.data&&(typeof this.data=="string"?e+="; data="+this.data:d.BufferUtils.isBuffer(this.data)?e+="; data (buffer)="+d.BufferUtils.base64Encode(this.data):e+="; data (json)="+JSON.stringify(this.data)),this.extras&&(e+="; extras="+JSON.stringify(this.extras)),this.action&&(e+="; action="+this.action),this.serial&&(e+="; serial="+this.serial),this.version&&(e+="; version="+this.version),this.refSerial&&(e+="; refSerial="+this.refSerial),this.refType&&(e+="; refType="+this.refType),this.createdAt&&(e+="; createdAt="+this.createdAt),this.operation&&(e+="; operation="+JSON.stringify(this.operation)),e+="]",e}},Di=pt,Dn=["absent","present","enter","leave","update"];function Hi(e){return Dn.indexOf(e)}async function Hn(e,t,n,s){const i=Ve(n),r=Gn(t,e,s??null);try{await mt(i,r??{})}catch(a){o.logAction(e,o.LOG_ERROR,"PresenceMessage.fromEncoded()",a.toString())}return i}async function Wi(e,t,n,s){return Promise.all(n.map(function(i){return Hn(e,t,i,s)}))}async function ji(e,t){const n=Ve(e);try{await mt(n,t.channelOptions)}catch(s){o.logAction(t.logger,o.LOG_ERROR,"PresenceMessage._fromEncoded()",s.toString())}return n}async function Wn(e,t){return Promise.all(e.map(function(n){return ji(n,t)}))}function X(e){return Object.assign(new ze,e)}function Ve(e){const t=Dn[e.action];return Object.assign(new ze,J(E({},e),{action:t}))}var mt=Oe;function jn(e){return e.map(X)}function Fn(e){return e instanceof ze?e:X({data:e})}var ze=class{isSynthesized(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");const e=this.id.split(":");return{connectionId:e[0],msgSerial:parseInt(e[1],10),index:parseInt(e[2],10)}}toJSON(){let e=this.data,t=this.encoding;return e&&d.BufferUtils.isBuffer(e)&&(arguments.length>0?(t=t?t+"/base64":"base64",e=d.BufferUtils.base64Encode(e)):e=d.BufferUtils.toBuffer(e)),{id:this.id,clientId:this.clientId,action:Hi(this.action),data:e,encoding:t,extras:this.extras}}toString(){let e="[PresenceMessage";return e+="; action="+this.action,this.id&&(e+="; id="+this.id),this.timestamp&&(e+="; timestamp="+this.timestamp),this.clientId&&(e+="; clientId="+this.clientId),this.connectionId&&(e+="; connectionId="+this.connectionId),this.encoding&&(e+="; encoding="+this.encoding),this.data&&(typeof this.data=="string"?e+="; data="+this.data:d.BufferUtils.isBuffer(this.data)?e+="; data (buffer)="+d.BufferUtils.base64Encode(this.data):e+="; data (json)="+JSON.stringify(this.data)),this.extras&&(e+="; extras="+JSON.stringify(this.extras)),e+="]",e}},Fi=ze,Vi=class{constructor(e){this.channel=e}get logger(){return this.channel.logger}async get(e){o.logAction(this.logger,o.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);const t=this.channel.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.channel.client.http.supportsLinkHeaders?void 0:n,i=C.defaultGetHeaders(t.options,{format:n});return w(i,t.options.headers),new ne(t,this.channel.client.rest.presenceMixin.basePath(this),i,s,async(r,a,c)=>{const h=c?r:D(r,t._MsgPack,n);return Wn(h,this.channel)}).get(e)}async history(e){return o.logAction(this.logger,o.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},zi=Vi,Ki=9;function Ji(e){return e.every(function(t){return!t.id})}var Qi=class{constructor(e,t,n){var s,i;o.logAction(e.logger,o.LOG_MINOR,"RestChannel()","started; name = "+t),this.name=t,this.client=e,this.presence=new zi(this),this.channelOptions=He((s=e._Crypto)!=null?s:null,this.logger,n),(i=e.options.plugins)!=null&&i.Push&&(this._push=new e.options.plugins.Push.PushChannel(this))}get push(){return this._push||q("Push"),this._push}get logger(){return this.client.logger}setOptions(e){var t;this.channelOptions=He((t=this.client._Crypto)!=null?t:null,this.logger,e)}async history(e){return o.logAction(this.logger,o.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,e)}async publish(...e){const t=e[0],n=e[1];let s,i;if(typeof t=="string"||t===null)s=[de({name:t,data:n})],i=e[2];else if(le(t))s=[de(t)],i=e[1];else if(Array.isArray(t))s=ft(t),i=e[1];else throw new f("The single-argument form of publish() expects a message object or an array of message objects",40013,400);i||(i={});const r=this.client,a=r.options,c=a.useBinaryProtocol?"msgpack":"json",h=r.options.idempotentRestPublishing,l=C.defaultPostHeaders(r.options,{format:c});if(w(l,a.headers),h&&Ji(s)){const m=await hn(Ki);s.forEach(function(p,v){p.id=m+":"+v.toString()})}await Bn(s,this.channelOptions);const u=gt(s),g=a.maxMessageSize;if(u>g)throw new f("Maximum size of messages that can be published at once exceeded ( was "+u+" bytes; limit is "+g+" bytes)",40009,400);await this._publish(Bi(s,r._MsgPack,c),l,i)}async _publish(e,t,n){await I.post(this.client,this.client.rest.channelMixin.basePath(this)+"/messages",e,t,n,null,!0)}async status(){return this.client.rest.channelMixin.status(this)}},$i=Qi,Xi=class Ms{constructor(t){this.entries=t&&t.entries||void 0,this.schema=t&&t.schema||void 0,this.appId=t&&t.appId||void 0,this.inProgress=t&&t.inProgress||void 0,this.unit=t&&t.unit||void 0,this.intervalId=t&&t.intervalId||void 0}static fromValues(t){return new Ms(t)}},Yi=Xi,Vn=class{static basePath(e){return"/channels/"+encodeURIComponent(e.name)}static history(e,t){const n=e.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.client.http.supportsLinkHeaders?void 0:s,r=C.defaultGetHeaders(n.options,{format:s});return w(r,n.options.headers),new ne(n,this.basePath(e)+"/messages",r,i,async function(a,c,h){const l=h?a:D(a,n._MsgPack,s);return Gi(l,e)}).get(t)}static async status(e){const t=e.client.options.useBinaryProtocol?"msgpack":"json",n=C.defaultPostHeaders(e.client.options,{format:t});return(await I.get(e.client,this.basePath(e),n,{},t,!0)).body}},Zi=class{static basePath(e){return Vn.basePath(e.channel)+"/presence"}static async history(e,t){const n=e.channel.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.channel.client.http.supportsLinkHeaders?void 0:s,r=C.defaultGetHeaders(n.options,{format:s});return w(r,n.options.headers),new ne(n,this.basePath(e)+"/history",r,i,async(a,c,h)=>{const l=h?a:D(a,n._MsgPack,s);return Wn(l,e.channel)}).get(t)}},zn=class{constructor(e){this.channelMixin=Vn,this.presenceMixin=Zi,this.Resource=I,this.DeviceDetails=ue,this.client=e,this.channels=new er(this.client),this.push=new Mi(this.client)}async stats(e){const t=C.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return w(t,this.client.options.headers),new ne(this.client,"/stats",t,s,function(i,r,a){const c=a?i:JSON.parse(i);for(let h=0;h<c.length;h++)c[h]=Yi.fromValues(c[h]);return c}).get(e)}async time(e){const t=C.defaultGetHeaders(this.client.options);this.client.options.headers&&w(t,this.client.options.headers);const n=c=>this.client.baseUri(c)+"/time";let{error:s,body:i,unpacked:r}=await this.client.http.do(M.Get,n,t,null,e);if(s)throw s;r||(i=JSON.parse(i));const a=i[0];if(!a)throw new f("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=a-Date.now(),a}async request(e,t,n,s,i,r){var a;const[c,h,l]=this.client.options.useBinaryProtocol?(this.client._MsgPack||q("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],u=this.client.http.supportsLinkHeaders?void 0:l;s=s||{};const g=e.toLowerCase(),m=g=="get"?C.defaultGetHeaders(this.client.options,{format:l,protocolVersion:n}):C.defaultPostHeaders(this.client.options,{format:l,protocolVersion:n});typeof i!="string"&&(i=(a=c(i))!=null?a:null),w(m,this.client.options.headers),r&&w(m,r);const p=new ne(this.client,t,m,u,async function(v,y,b){return Xt(b?v:h(v))},!0);if(!d.Http.methods.includes(g))throw new f("Unsupported method "+g,40500,405);return d.Http.methodsWithBody.includes(g)?p[g](s,i):p[g](s)}async batchPublish(e){let t,n;Array.isArray(e)?(t=e,n=!1):(t=[e],n=!0);const s=this.client.options.useBinaryProtocol?"msgpack":"json",i=C.defaultPostHeaders(this.client.options,{format:s});this.client.options.headers&&w(i,this.client.options.headers);const r=W(t,this.client._MsgPack,s),a=await I.post(this.client,"/messages",r,i,{},null,!0),c=a.unpacked?a.body:D(a.body,this.client._MsgPack,s);return n?c[0]:c}async batchPresence(e){const t=this.client.options.useBinaryProtocol?"msgpack":"json",n=C.defaultPostHeaders(this.client.options,{format:t});this.client.options.headers&&w(n,this.client.options.headers);const s=e.join(","),i=await I.get(this.client,"/presence",n,{channels:s},null,!0);return i.unpacked?i.body:D(i.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(In(this.client.options))throw new f("Cannot revoke tokens when using token auth",40162,401);const n=this.client.options.keyName;let s=t??{};const i=E({targets:e.map(l=>`${l.type}:${l.value}`)},s),r=this.client.options.useBinaryProtocol?"msgpack":"json",a=C.defaultPostHeaders(this.client.options,{format:r});this.client.options.headers&&w(a,this.client.options.headers);const c=W(i,this.client._MsgPack,r),h=await I.post(this.client,`/keys/${n}/revokeTokens`,c,a,{},null,!0);return h.unpacked?h.body:D(h.body,this.client._MsgPack,r)}},er=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 $i(this.client,e,t),n}release(e){delete this.all[String(e)]}},tr=class extends Pn{constructor(e){super(C.objectifyOptions(e,!1,"BaseRest",o.defaultLogger,{Rest:zn}))}},Kn={Rest:zn},Jn=class extends Di{static async fromEncoded(e,t){return qn(o.defaultLogger,d.Crypto,e,t)}static async fromEncodedArray(e,t){return xi(o.defaultLogger,d.Crypto,e,t)}static fromValues(e){return de(e)}static fromWireProtocol(e){return Fe(e)}static async encode(e,t){return dt(e,t)}static async decode(e,t){return Oe(e,t)}},Qn=class extends Fi{static async fromEncoded(e,t){return Hn(o.defaultLogger,d.Crypto,e,t)}static async fromEncodedArray(e,t){return Wi(o.defaultLogger,d.Crypto,e,t)}static fromValues(e){return X(e)}},fe=class $e extends tr{constructor(t){var n,s;if(!$e._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(C.objectifyOptions(t,!0,"Rest",o.defaultLogger,J(E({},Kn),{Crypto:(n=$e.Crypto)!=null?n:void 0,MsgPack:(s=$e._MsgPack)!=null?s:void 0})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(t){this._Crypto=t}};fe._Crypto=null,fe.Message=Jn,fe.PresenceMessage=Qn,fe._MsgPack=null,fe._Http=ht;var yt=fe;function nr(e,t,n,s){try{n.apply(t,s)}catch(i){o.logAction(e,o.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+i+"; stack = "+(i&&i.stack))}}function vt(e,t,n){let s,i,r;for(let a=0;a<e.length;a++)if(s=e[a],n&&(s=s[n]),Array.isArray(s)){for(;(i=s.indexOf(t))!==-1;)s.splice(i,1);n&&s.length===0&&delete e[a][n]}else if(le(s))for(r in s)Object.prototype.hasOwnProperty.call(s,r)&&Array.isArray(s[r])&&vt([s],t,r)}var sr=class{constructor(e){this.logger=e,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...e){if(e.length===1){const t=e[0];if(typeof t=="function")this.any.push(t);else throw new Error("EventListener.on(): Invalid arguments: "+d.Config.inspect(e))}if(e.length===2){const[t,n]=e;if(typeof n!="function")throw new Error("EventListener.on(): Invalid arguments: "+d.Config.inspect(e));if(H(t))this.any.push(n);else if(Array.isArray(t))t.forEach(s=>{this.on(s,n)});else{if(typeof t!="string")throw new Error("EventListener.on(): Invalid arguments: "+d.Config.inspect(e));(this.events[t]||(this.events[t]=[])).push(n)}}}off(...e){if(e.length==0||H(e[0])&&H(e[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}const[t,n]=e;let s=null,i=null;if(e.length===1||!n)typeof t=="function"?s=t:i=t;else{if(typeof n!="function")throw new Error("EventEmitter.off(): invalid arguments:"+d.Config.inspect(e));[i,s]=[t,n]}if(s&&H(i)){vt([this.any,this.events,this.anyOnce,this.eventsOnce],s);return}if(Array.isArray(i)){i.forEach(r=>{this.off(r,s)});return}if(typeof i!="string")throw new Error("EventEmitter.off(): invalid arguments:"+d.Config.inspect(e));s?vt([this.events,this.eventsOnce],s,i):(delete this.events[i],delete this.eventsOnce[i])}listeners(e){if(e){const 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){const 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);const i=this.eventsOnce[e];i&&(Array.prototype.push.apply(s,i),delete this.eventsOnce[e]);const r=this.events[e];r&&Array.prototype.push.apply(s,r),s.forEach(a=>{nr(this.logger,n,a,t)})}once(...e){const t=e.length;if(t===0||t===1&&typeof e[0]!="function"){const i=e[0];return new Promise(r=>{this.once(i,r)})}const[n,s]=e;if(e.length===1&&typeof n=="function")this.anyOnce.push(n);else if(H(n)){if(typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+d.Config.inspect(e));this.anyOnce.push(s)}else if(Array.isArray(n)){const i=this,r=function(){const a=Array.prototype.slice.call(arguments);if(n.forEach(function(c){i.off(c,r)}),typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+d.Config.inspect(e));s.apply(this,a)};n.forEach(function(a){i.on(a,r)})}else{if(typeof n!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+d.Config.inspect(e));const i=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(s){if(typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+d.Config.inspect(e));i.push(s)}}}async whenState(e,t){if(typeof e!="string"||typeof t!="string")throw new Error("whenState requires a valid state String argument");return e===t?null:this.once(e)}},U=sr,O={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},$n=[];Object.keys(O).forEach(function(e){$n[O[e]]=e});var Y={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19},ir=Object.keys(Y);Y.MODE_ALL=Y.PRESENCE|Y.PUBLISH|Y.SUBSCRIBE|Y.PRESENCE_SUBSCRIBE;function Xn(e){const t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}var Yn=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE"],rr=W;function or(e,t,n,s){const i=D(e,t,s);return bt(i,n)}function bt(e,t){const n=e.error;n&&(e.error=f.fromValues(n));let s;e.messages&&(s=e.messages.map(a=>Fe(a)));let i;return t&&e.presence&&(i=e.presence.map(a=>t.presenceMessageFromWireProtocol(a))),Object.assign(new Rt,J(E({},e),{presence:i,messages:s}))}function ar(e){return bt(e,{presenceMessageFromValues:X,presenceMessagesFromValuesArray:jn,presenceMessageFromWireProtocol:Ve})}function j(e){return Object.assign(new Rt,e)}function Ct(e,t){let n="[ProtocolMessage";e.action!==void 0&&(n+="; action="+$n[e.action]||e.action);const s=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"];let i;for(let r=0;r<s.length;r++)i=s[r],e[i]!==void 0&&(n+="; "+i+"="+e[i]);if(e.messages&&(n+="; messages="+Xn(ft(e.messages))),e.presence&&t&&(n+="; presence="+Xn(t.presenceMessagesFromValuesArray(e.presence))),e.error&&(n+="; error="+f.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(n+="; token="+e.auth.accessToken),e.flags&&(n+="; flags="+ir.filter(e.hasFlag).join(",")),e.params){let r="";rn(e.params,function(a){r.length>0&&(r+="; "),r+=a+"="+e.params[a]}),r.length>0&&(n+="; params=["+r+"]")}return n+="]",n}var Rt=class{constructor(){this.hasFlag=e=>(this.flags&Y[e])>0}setFlag(e){return this.flags=this.flags|Y[e]}getMode(){return this.flags&&this.flags&Y.MODE_ALL}encodeModesToFlags(e){e.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){const e=[];return Yn.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},Zn=Rt,cr=class extends U{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){o.logAction(this.logger,o.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+e+"; count = "+t),n=n||null;const s=this.messages;if(s.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");const i=s[0];if(i){const r=i.message.msgSerial,a=e+t;if(a>r){const c=s.splice(0,a-r);for(const h of c)h.callback(n)}s.length==0&&this.emit("idle")}}completeAllMessages(e){this.completeMessages(0,Number.MAX_SAFE_INTEGER||Number.MAX_VALUE,e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){o.logAction(this.logger,o.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},es=cr,ts=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;const n=e.action;this.sendAttempted=!1,this.ackRequired=n==O.MESSAGE||n==O.PRESENCE}},lr=class extends U{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new es(this.logger),e.on("ack",(t,n)=>{this.onAck(t,n)}),e.on("nack",(t,n,s)=>{this.onNack(t,n,s)})}onAck(e,t){o.logAction(this.logger,o.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages(e,t)}onNack(e,t,n){o.logAction(this.logger,o.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+T(n)),n||(n=new f("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages(e,t,n)}onceIdle(e){const t=this.messageQueue;if(t.count()===0){e();return}t.once("idle",e)}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(o.LOG_MICRO)&&o.logActionNoStrip(this.logger,o.LOG_MICRO,"Protocol.send()","sending msg; "+Ct(e.message,this.transport.connectionManager.realtime._RealtimePresence)),e.sendAttempted=!0,this.transport.send(e.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){const e=this.transport;this.onceIdle(function(){e.disconnect()})}},hr=lr,ur=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},Ke=ur,se={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},dr={disconnected:()=>f.fromValues({statusCode:400,code:se.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>f.fromValues({statusCode:400,code:se.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>f.fromValues({statusCode:400,code:se.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>f.fromValues({statusCode:400,code:se.CLOSING,message:"Connection closing"}),closed:()=>f.fromValues({statusCode:400,code:se.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>f.fromValues({statusCode:500,code:se.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>f.fromValues({statusCode:500,code:se.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function fr(e){return!e.statusCode||!e.code||e.statusCode>=500?!0:Object.values(se).includes(e.code)}var ie=dr,gr=j({action:O.CLOSE}),pr=j({action:O.DISCONNECT}),mr=class extends U{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",ie.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||ie.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||ie.failed())}finish(e,t){var n;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((n=this.idleTimer)!=null?n:void 0),this.idleTimer=null,this.emit(e,t),this.dispose())}onProtocolMessage(e){switch(this.logger.shouldLog(o.LOG_MICRO)&&o.logActionNoStrip(this.logger,o.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+Ct(e,this.connectionManager.realtime._RealtimePresence)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case O.HEARTBEAT:o.logActionNoStrip(this.logger,o.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case O.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case O.CLOSED:this.onClose(e);break;case O.DISCONNECTED:this.onDisconnect(e);break;case O.ACK:this.emit("ack",e.msgSerial,e.count);break;case O.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case O.SYNC:this.connectionManager.onChannelMessage(e,this);break;case O.ACTIVATE:break;case O.AUTH:N(this.auth.authorize(),t=>{t&&o.logAction(this.logger,o.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+T(t))});break;case O.ERROR:if(o.logAction(this.logger,o.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+d.Config.inspect(e.error)+(e.channel?", channel: "+e.channel:"")),e.channel===void 0){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 new Error("Transport.onConnect(): Connect message recieved without connectionDetails");const t=e.connectionDetails.maxIdleInterval;t&&(this.maxIdleInterval=t+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(e){const t=e&&e.error;o.logAction(this.logger,o.LOG_MINOR,"Transport.onDisconnect()","err = "+T(t)),this.finish("disconnected",t)}onFatalError(e){const t=e&&e.error;o.logAction(this.logger,o.LOG_MINOR,"Transport.onFatalError()","err = "+T(t)),this.finish("failed",t)}onClose(e){const t=e&&e.error;o.logAction(this.logger,o.LOG_MINOR,"Transport.onClose()","err = "+T(t)),this.finish("closed",t)}requestClose(){o.logAction(this.logger,o.LOG_MINOR,"Transport.requestClose()",""),this.send(gr)}requestDisconnect(){o.logAction(this.logger,o.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(pr)}ping(e){const t={action:O.HEARTBEAT};e&&(t.id=e),this.send(j(t))}dispose(){o.logAction(this.logger,o.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 new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;const e=Date.now()-this.lastActivity,t=this.maxIdleInterval-e;if(t<=0){const n="No activity seen from realtime in "+e+"ms; assuming connection has dropped";o.logAction(this.logger,o.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new f(n,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,s,i){const r=new e(t,n,s);let a;const c=function(l){clearTimeout(a),i({event:this.event,error:l})},h=t.options.timeouts.realtimeRequestTimeout;return a=setTimeout(()=>{r.off(["preconnect","disconnected","failed"]),r.dispose(),c.call({event:"disconnected"},new f("Timeout waiting for transport to indicate itself viable",5e4,500))},h),r.on(["failed","disconnected"],c),r.on("preconnect",function(){o.logAction(t.logger,o.LOG_MINOR,"Transport.tryConnect()","viable transport "+r),clearTimeout(a),r.off(["failed","disconnected"],c),i(null,r)}),r.connect(),r}static isAvailable(){throw new f("isAvailable not implemented for transport",5e4,500)}},ge=mr,G;(e=>{e.WebSocket="web_socket",e.Comet="comet",e.XhrPolling="xhr_polling"})(G||(G={}));var yr=typeof re<"u"?re:typeof window<"u"?window:self,wt=()=>{var e;return typeof d.WebStorage<"u"&&((e=d.WebStorage)==null?void 0:e.localSupported)},Ae=()=>{var e;return typeof d.WebStorage<"u"&&((e=d.WebStorage)==null?void 0:e.sessionSupported)},ns=function(){},Ot="ably-transport-preference";function vr(e,t,n){let s;if(e.channel!==t.channel||(s=e.action)!==O.PRESENCE&&s!==O.MESSAGE||s!==t.action)return!1;const i=s===O.PRESENCE?"presence":"messages",r=e[i].concat(t[i]);return gt(r)>n||!on(r,"clientId")||!r.every(function(c){return!c.id})?!1:(e[i]=r,!0)}function At(e){try{return JSON.parse(e)}catch{return null}}var br=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){const t=e?ce(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":{const s=At(n.recover);s&&(t.recover=s.connectionKey);break}}return n.clientId!==void 0&&(t.clientId=n.clientId),n.echoMessages===!1&&(t.echo="false"),this.format!==void 0&&(t.format=this.format),this.stream!==void 0&&(t.stream=this.stream),this.heartbeats!==void 0&&(t.heartbeats=this.heartbeats),t.v=C.protocolVersion,t.agent=ot(this.options),n.transportParams!==void 0&&w(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+="]",e}},Cr=class ks extends U{constructor(t,n){super(t.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=t,this.initTransports(),this.options=n;const s=n.timeouts,i=s.webSocketConnectTimeout+s.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:i,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:s.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:s.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:s.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 es(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=s.connectionStateTtl,this.maxIdleInterval=null,this.transports=Zt(n.transports||C.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(G.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(G.XhrPolling)?this.baseTransport=G.XhrPolling:this.transports.includes(G.Comet)&&(this.baseTransport=G.Comet),this.httpHosts=C.getHosts(n),this.wsHosts=C.getHosts(n,!0),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,o.logAction(this.logger,o.LOG_MINOR,"Realtime.ConnectionManager()","started"),o.logAction(this.logger,o.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(n.transports||C.defaultTransports)+"]"),o.logAction(this.logger,o.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),o.logAction(this.logger,o.LOG_MICRO,"Realtime.ConnectionManager()","http hosts = ["+this.httpHosts+"]"),!this.transports.length){const a="no requested transports available";throw o.logAction(this.logger,o.LOG_ERROR,"realtime.ConnectionManager()",a),new Error(a)}const r=d.Config.addEventListener;r&&(Ae()&&typeof n.recover=="function"&&r("beforeunload",this.persistConnection.bind(this)),n.closeOnUnload===!0&&r("beforeunload",()=>{o.logAction(this.logger,o.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),r("online",()=>{var a;this.state==this.states.disconnected||this.state==this.states.suspended?(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager caught browser ‘online’ event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((a=this.pendingTransport)==null||a.off(),this.disconnectAllTransports(),this.startConnect())}),r("offline",()=>{this.state==this.states.connected&&(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager caught browser ‘offline’ event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(t){const n={supportedTransports:{}};return this.initTransports(t,n),n.supportedTransports}static initTransports(t,n){const s=E(E({},d.Transports.bundledImplementations),t);[G.WebSocket,...d.Transports.order].forEach(i=>{const r=s[i];r&&r.isAvailable()&&(n.supportedTransports[i]=r)})}initTransports(){ks.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(t,n){return new br(this.options,t,n,this.connectionKey)}getTransportParams(t){(s=>{if(this.connectionKey){s("resume");return}if(typeof this.options.recover=="string"){s("recover");return}const i=this.options.recover,r=this.getSessionRecoverData(),a=this.sessionRecoveryName();if(r&&typeof i=="function"){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+a+")"),i(r,c=>{c?(this.options.recover=r.recoveryKey,s("recover")):s("clean")});return}s("clean")})(s=>{const i=this.createTransportParams(null,s);if(s==="recover"){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);const r=At(this.options.recover);r&&(this.msgSerial=r.msgSerial)}else o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+i.toString());t(i)})}tryATransport(t,n,s){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+n),this.proposedTransport=ge.tryConnect(this.supportedTransports[n],this,this.realtime.auth,t,(i,r)=>{const a=this.state;if(a==this.states.closing||a==this.states.closed||a==this.states.failed){r&&(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+a.state+" while we were attempting the transport; closing "+r),r.close()),s(!0);return}if(i){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+n+" "+i.event+", err: "+i.error.toString()),$.isTokenErr(i.error)&&!(this.errorReason&&$.isTokenErr(this.errorReason))?(this.errorReason=i.error,N(this.realtime.auth._forceNewToken(null,null),c=>{if(c){this.actOnErrorFromAuthorize(c);return}this.tryATransport(t,n,s)})):i.event==="failed"?(this.notifyState({state:"failed",error:i.error}),s(!0)):i.event==="disconnected"&&(fr(i.error)?s(!1):(this.notifyState({state:this.states.connecting.failState,error:i.error}),s(!0)));return}o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+n+"; setting pending"),this.setTransportPending(r,t),s(null,r)})}setTransportPending(t,n){const s=n.mode;o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+t+"; mode = "+s),this.pendingTransport=t,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),t.once("connected",(r,a,c)=>{this.activateTransport(r,t,a,c),s==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});const i=this;t.on(["disconnected","closed","failed"],function(r){i.deactivateTransport(t,this.event,r)}),this.emit("transport.pending",t)}activateTransport(t,n,s,i){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+n),t&&o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+t),s&&o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId =  "+s),i&&o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails =  "+JSON.stringify(i)),this.persistTransportPreference(n);const r=this.state,a=this.states.connected.state;if(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+r.state),r.state==this.states.closing.state||r.state==this.states.closed.state||r.state==this.states.failed.state)return o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),n.disconnect(),!1;if(delete this.pendingTransport,!n.isConnected)return o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+n+" since it appears to no longer be connected"),!1;const c=this.activeProtocol;this.activeProtocol=new hr(n),this.host=n.params.host;const h=i.connectionKey;if(h&&this.connectionKey!=h&&this.setConnection(s,i,!!t),this.onConnectionDetailsUpdate(i,n),d.Config.nextTick(()=>{n.on("connected",(l,u,g)=>{this.onConnectionDetailsUpdate(g,n),this.emit("update",new Ke(a,a,null,l))})}),r.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new Ke(a,a,null,t))):(this.notifyState({state:"connected",error:t}),this.errorReason=this.realtime.connection.errorReason=t||null),this.emit("transport.active",n),c)if(c.messageQueue.count()>0&&o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+c.transport.shortName+", new one is "+n.shortName+") finishing with "+c.messageQueue.count()+" messages still pending"),c.transport===n){const l="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+n.shortName+"; stack = "+new Error().stack;o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.activateTransport()",l)}else c.finish();return!0}deactivateTransport(t,n,s){const i=this.activeProtocol,r=i&&i.getTransport()===t,a=t===this.pendingTransport,c=this.noTransportsScheduledForActivation();if(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+t),o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+n+(r?"; was active":a?"; was pending":"")+(c?"":"; another transport is scheduled for activation")),s&&s.message&&o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason =  "+s.message),r&&(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(i.getPendingMessages()),i.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",t),r&&c||r&&n==="failed"||n==="closed"||i===null&&a){if(n==="disconnected"&&s&&s.statusCode>500&&this.httpHosts.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:n,error:s,retryImmediately:!0});return}const h=n==="failed"&&$.isTokenErr(s)?"disconnected":n;this.notifyState({state:h,error:s});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(t,n,s){const i=this.connectionId;(i&&i!==t||!i&&s)&&(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==t&&o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=t,this.realtime.connection.key=this.connectionKey=n.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;const t=Date.now()-this.lastActivity;t>this.connectionStateTtl+this.maxIdleInterval&&(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+t+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(Ae()){const t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:yr.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getError(){if(this.errorReason){const t=P.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,n;return(n=(t=ie)[this.state.state])==null?void 0:n.call(t)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(t){const n="Connection state",s=t.current+(t.reason?"; reason: "+t.reason:"");t.current==="failed"?o.logAction(this.logger,o.LOG_ERROR,n,s):o.logAction(this.logger,o.LOG_MAJOR,n,s),o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+t.current+"; reason = "+(t.reason&&t.reason.message));const i=this.state=this.states[t.current];t.reason&&(this.errorReason=t.reason,this.realtime.connection.errorReason=t.reason),(i.terminal||i.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",t)}startTransitionTimer(t){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+t.state),this.transitionTimer&&(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager "+t.state+" timer expired","requesting new state: "+t.failState),this.notifyState({state:t.failState}))},t.retryDelay)}cancelTransitionTimer(){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(t){t!=="disconnected"&&t!=="suspended"&&t!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(t){this.retryTimer=setTimeout(()=>{o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{o.logAction(this.logger,o.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&N(this.realtime.http.checkConnectivity(),(t,n)=>{t||!n?(o.logAction(this.logger,o.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new f("Unable to connect (network unreachable)",80003,404)})):o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(t){this.webSocketGiveUpTimer=setTimeout(()=>{var n,s;this.wsCheckResult||(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(n=this.proposedTransport)==null||n.dispose(),(s=this.pendingTransport)==null||s.dispose(),this.connectBase(t,++this.connectCounter)):o.logAction(this.logger,o.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(t){var n,s;const i=t.state,r=i==="disconnected"&&(this.state===this.states.connected||t.retryImmediately||this.state===this.states.connecting&&t.error&&$.isTokenErr(t.error)&&!(this.errorReason&&$.isTokenErr(this.errorReason)));if(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+i+(r?"; will retry connection immediately":"")),i==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(t.state),(i==="suspended"||i==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;const a=this.states[t.state];let c=a.retryDelay;a.state==="disconnected"&&(this.disconnectedRetryCount++,c=it(a.retryDelay,this.disconnectedRetryCount));const h=new Ke(this.state.state,a.state,c,t.error||((s=(n=ie)[a.state])==null?void 0:s.call(n)));if(r){const l=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},u=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;u&&u<1e3?(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+u+"ms ago, waiting another "+(1e3-u)+"ms before trying again"),setTimeout(l,1e3-u)):d.Config.nextTick(l)}else(i==="disconnected"||i==="suspended")&&this.startRetryTimer(c);(i==="disconnected"&&!r||i==="suspended"||a.terminal)&&d.Config.nextTick(()=>{this.disconnectAllTransports()}),i=="connected"&&!this.activeProtocol&&o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(h),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(i,h.reason),this.failQueuedMessages(h.reason))}requestState(t){var n,s;const i=t.state;if(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+i+"; current state: "+this.state.state),i==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(i),i=="connecting"&&this.state.state=="connected")||i=="closing"&&this.state.state=="closed")return;const r=this.states[i],a=new Ke(this.state.state,r.state,null,t.error||((s=(n=ie)[r.state])==null?void 0:s.call(n)));this.enactStateChange(a),i=="connecting"&&d.Config.nextTick(()=>{this.startConnect()}),i=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}const t=this.realtime.auth,n=++this.connectCounter,s=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(i=>{if(i.mode==="recover"&&i.options.recover){const r=At(i.options.recover);r&&this.realtime.channels.recoverChannels(r.channelSerials)}n===this.connectCounter&&this.connectImpl(i,n)})};if(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),t.method==="basic")s();else{const i=r=>{n===this.connectCounter&&(r?this.actOnErrorFromAuthorize(r):s())};this.errorReason&&$.isTokenErr(this.errorReason)?N(t._forceNewToken(null,null),i):N(t._ensureValidAuthCredentials(!1),i)}}connectImpl(t,n){const s=this.state.state;if(s!==this.states.connecting.state){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+s);return}const i=this.getTransportPreference();i&&i===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(t,++this.connectCounter))}).catch(ns),i&&i===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(t,n):this.connectWs(t,n)}connectWs(t,n){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(t),this.tryTransportWithFallbacks("web_socket",t,!0,n,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(t,n){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,t,!1,n,()=>!0):this.notifyState({state:"disconnected",error:new f("No transports left to try",8e4,404)})}tryTransportWithFallbacks(t,n,s,i,r){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",t);const a=g=>{this.notifyState({state:this.states.connecting.failState,error:g})},c=s?this.wsHosts.slice():this.httpHosts.slice(),h=(g,m)=>{if(i===this.connectCounter){if(!r()){m&&m.dispose();return}!m&&!g&&u()}},l=c.shift();if(!l){a(new f("Unable to connect (no available host)",80003,404));return}n.host=l;const u=()=>{if(!c.length){a(new f("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){a(new P("Internal error: Http.checkConnectivity not set",null,500));return}N(this.realtime.http.checkConnectivity(),(g,m)=>{if(i===this.connectCounter&&r()){if(g){a(g);return}if(!m){a(new f("Unable to connect (network unreachable)",80003,404));return}n.host=tt(c),this.tryATransport(n,t,h)}})};if(this.forceFallbackHost&&c.length){this.forceFallbackHost=!1,u();return}this.tryATransport(n,t,h)}closeImpl(){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(t,n){var s;switch(this.state.state){case"connected":{o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");const i=(s=this.activeProtocol)==null?void 0:s.getTransport();i&&i.onAuthUpdated&&i.onAuthUpdated(t);const r=j({action:O.AUTH,auth:{accessToken:t.token}});this.send(r);const a=()=>{this.off(c),n(null,t)},c=h=>{h.current==="failed"&&(this.off(a),this.off(c),n(h.reason||this.getStateError()))};this.once("connectiondetails",a),this.on("connectionstate",c);break}case"connecting":o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");const i=r=>{switch(r.current){case"connected":this.off(i),n(null,t);break;case"failed":case"closed":case"suspended":this.off(i),n(r.reason||this.getStateError());break}};this.on("connectionstate",i),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(t,n,s){s=s||ns;const i=this.state;if(i.sendEvents){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new ts(t,s));return}if(!(n&&i.queueEvents)){const a="rejecting event, queueEvent was "+n+", state was "+i.state;o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.send()",a),s(this.errorReason||new f(a,9e4,400));return}this.logger.shouldLog(o.LOG_MICRO)&&o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+Ct(t,this.realtime._RealtimePresence)),this.queue(t,s)}sendImpl(t){const n=t.message;t.ackRequired&&!t.sendAttempted&&(n.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(s){o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+s.stack)}}queue(t,n){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.queue()","queueing event");const s=this.queuedMessages.last(),i=this.options.maxMessageSize;s&&!s.sendAttempted&&vr(s.message,t,i)?(s.merged||(s.callback=at.create(this.logger,[s.callback]),s.merged=!0),s.callback.push(n)):this.queuedMessages.push(new ts(t,n))}sendQueuedMessages(){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let t;for(;t=this.queuedMessages.shift();)this.sendImpl(t)}queuePendingMessages(t){t&&t.length&&(o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+t.length+" pending messages"),this.queuedMessages.prepend(t))}failQueuedMessages(t){const n=this.queuedMessages.count();n>0&&(o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+n+" queued messages, err = "+T(t)),this.queuedMessages.completeAllMessages(t))}onChannelMessage(t,n){this.pendingChannelMessagesState.queue.push({message:t,transport:n}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;const t=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(t.message).catch(n=>{o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",n)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(t){await this.realtime.channels.processChannelMessage(t)}async ping(){var t;if(this.state.state!=="connected")throw new f("Unable to ping service; not connected",4e4,400);const n=(t=this.activeProtocol)==null?void 0:t.getTransport();if(!n)throw this.getStateError();o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.ping()","transport = "+n);const s=Date.now(),i=qe();return vn(new Promise(r=>{const a=c=>{c===i&&(n.off("heartbeat",a),r(Date.now()-s))};n.on("heartbeat",a),n.ping(i)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(t){this.activeProtocol.getTransport().fail(t)}getTransportPreference(){var t,n;return this.transportPreference||wt()&&((n=(t=d.WebStorage)==null?void 0:t.get)==null?void 0:n.call(t,Ot))}persistTransportPreference(t){var n,s;this.transportPreference=t.shortName,wt()&&((s=(n=d.WebStorage)==null?void 0:n.set)==null||s.call(n,Ot,t.shortName))}unpersistTransportPreference(){var t,n;this.transportPreference=null,wt()&&((n=(t=d.WebStorage)==null?void 0:t.remove)==null||n.call(t,Ot))}actOnErrorFromAuthorize(t){if(t.code===40171)this.notifyState({state:"failed",error:t});else if(t.code===40102)this.notifyState({state:"failed",error:t});else if(t.statusCode===je.Forbidden){const n="Client configured authentication provider returned 403; failing the connection";o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",n),this.notifyState({state:"failed",error:new f(n,80019,403,t)})}else{const n="Client configured authentication provider request failed";o.logAction(this.logger,o.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",n),this.notifyState({state:this.state.failState,error:new f(n,80019,401,t)})}}onConnectionDetailsUpdate(t,n){if(!t)return;this.connectionDetails=t,t.maxMessageSize&&(this.options.maxMessageSize=t.maxMessageSize);const s=t.clientId;if(s){const r=this.realtime.auth._uncheckedSetClientId(s);if(r){o.logAction(this.logger,o.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",r.message),n.fail(r);return}}const i=t.connectionStateTtl;i&&(this.connectionStateTtl=i),this.maxIdleInterval=t.maxIdleInterval,this.emit("connectiondetails",t)}checkWsConnectivity(){const t=this.options.wsConnectivityCheckUrl||C.wsConnectivityCheckUrl,n=new d.Config.WebSocket(t);return new Promise((s,i)=>{let r=!1;n.onopen=()=>{r||(r=!0,s(),n.close())},n.onclose=n.onerror=()=>{r||(r=!0,i())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var t,n;return Ae()&&((n=(t=d.WebStorage)==null?void 0:t.getSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var n,s;return Ae()&&((s=(n=d.WebStorage)==null?void 0:n.setSession)==null?void 0:s.call(n,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,n;return Ae()&&((n=(t=d.WebStorage)==null?void 0:t.removeSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}},ss=Cr,Rr=class extends U{constructor(e,t){super(e.logger),this.whenState=n=>U.prototype.whenState.call(this,n,this.state),this.ably=e,this.connectionManager=new ss(e,t),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",n=>{const s=this.state=n.current;d.Config.nextTick(()=>{this.emit(s,n)})}),this.connectionManager.on("update",n=>{d.Config.nextTick(()=>{this.emit("update",n)})})}connect(){o.logAction(this.logger,o.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return o.logAction(this.logger,o.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){o.logAction(this.logger,o.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()}},wr=Rr,Or=class{constructor(e,t,n,s,i){this.previous=e,this.current=t,t==="attached"&&(this.resumed=n,this.hasBacklog=s),i&&(this.reason=i)}},St=Or,is=function(){};function Ar(e){if(e&&"params"in e&&!le(e.params))return new f("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new f("options.modes must be an array",4e4,400);for(let t=0;t<e.modes.length;t++){const n=e.modes[t];if(!n||typeof n!="string"||!Yn.includes(String.prototype.toUpperCase.call(n)))return new f("Invalid channel mode: "+n,4e4,400)}}}var Sr=class Wt extends U{constructor(t,n,s){var i,r;super(t.logger),this.retryCount=0,this.history=async function(a){o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);const c=this.client.rest.channelMixin;if(a&&a.untilAttach){if(this.state!=="attached")throw new f("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new f("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete a.untilAttach,a.from_serial=this.properties.attachSerial}return c.history(this,a)},this.whenState=a=>U.prototype.whenState.call(this,a,this.state),o.logAction(this.logger,o.LOG_MINOR,"RealtimeChannel()","started; name = "+n),this.name=n,this.channelOptions=He((i=t._Crypto)!=null?i:null,this.logger,s),this.client=t,this._presence=t._RealtimePresence?new t._RealtimePresence.RealtimePresence(this):null,this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new U(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(s),this.errorReason=null,this._requestedFlags=null,this._mode=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new U(this.logger),(r=t.options.plugins)!=null&&r.Push&&(this._push=new t.options.plugins.Push.PushChannel(this))}get presence(){return this._presence||q("RealtimePresence"),this._presence}get push(){return this._push||q("Push"),this._push}invalidStateError(){return new f("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(t){return t=Array.prototype.slice.call(t),typeof t[0]=="function"&&t.unshift(null),t}async setOptions(t){var n;const s=this.channelOptions,i=Ar(t);if(i)throw i;if(this.channelOptions=He((n=this.client._Crypto)!=null?n:null,this.logger,t),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(t,s))return this.attachImpl(),new Promise((r,a)=>{this._allChannelChanges.once(["attached","update","detached","failed"],function(c){switch(this.event){case"update":case"attached":r();break;default:a(c.reason)}})})}_shouldReattachToSetOptions(t,n){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(t?.params){const s=rs(t.params),i=rs(n.params);if(Object.keys(s).length!==Object.keys(i).length||!pn(i,s))return!0}return!!(t?.modes&&(!n.modes||!yn(t.modes,n.modes)))}async publish(...t){let n=t[0],s=t.length;if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(s==1)if(le(n))n=[de(n)];else if(Array.isArray(n))n=ft(n);else throw new f("The single-argument form of publish() expects a message object or an array of message objects",40013,400);else n=[de({name:t[0],data:t[1]})];const i=this.client.options.maxMessageSize;await Bn(n,this.channelOptions);const r=gt(n);if(r>i)throw new f("Maximum size of messages that can be published at once exceeded ( was "+r+" bytes; limit is "+i+" bytes)",40009,400);return new Promise((a,c)=>{this._publish(n,h=>h?c(h):a())})}_publish(t,n){o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.publish()","message count = "+t.length);const s=this.state;switch(s){case"failed":case"suspended":n(f.fromValues(this.invalidStateError()));break;default:{o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+s);const i=new Zn;i.action=O.MESSAGE,i.channel=this.name,i.messages=t,this.sendMessage(i,n);break}}}onEvent(t){o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.onEvent()","received message");const n=this.subscriptions;for(let s=0;s<t.length;s++){const i=t[s];n.emit(i.name,i)}}async attach(){return this.state==="attached"?null:new Promise((t,n)=>{this._attach(!1,null,(s,i)=>s?n(s):t(i))})}_attach(t,n,s){s||(s=r=>{r&&o.logAction(this.logger,o.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+r.toString())});const i=this.connectionManager;if(!i.activeState()){s(i.getError());return}(this.state!=="attaching"||t)&&this.requestState("attaching",n),this.once(function(r){switch(this.event){case"attached":s?.(null,r);break;case"detached":case"suspended":case"failed":s?.(r.reason||i.getError()||new f("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":s?.(new f("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");const t=j({action:O.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this._requestedFlags?t.encodeModesToFlags(this._requestedFlags):this.channelOptions.modes&&t.encodeModesToFlags(dn(this.channelOptions.modes)),this._attachResume&&t.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(t.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(t,is)}async detach(){const t=this.connectionManager;if(!t.activeState())throw t.getError();switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new f("Unable to detach; channel state = failed",90001,400);default:this.requestState("detaching");case"detaching":return new Promise((n,s)=>{this.once(function(i){switch(this.event){case"detached":n();break;case"attached":case"suspended":case"failed":s(i.reason||t.getError()||new f("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":s(new f("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(t){o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");const n=j({action:O.DETACH,channel:this.name});this.sendMessage(n,t||is)}async subscribe(...t){const[n,s]=Wt.processListenerArgs(t);if(this.state==="failed")throw f.fromValues(this.invalidStateError());return n&&typeof n=="object"&&!Array.isArray(n)?this.client._FilteredSubscriptions.subscribeFilter(this,n,s):this.subscriptions.on(n,s),this.attach()}unsubscribe(...t){var n;const[s,i]=Wt.processListenerArgs(t);if(typeof s=="object"&&!i||(n=this.filteredSubscriptions)!=null&&n.has(i)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,s,i).forEach(r=>this.subscriptions.off(r));return}this.subscriptions.off(s,i)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new P("Unable to sync to channel; not attached",4e4)}const t=this.connectionManager;if(!t.activeState())throw t.getError();const n=j({action:O.SYNC,channel:this.name});this.syncChannelSerial&&(n.channelSerial=this.syncChannelSerial),t.send(n)}sendMessage(t,n){this.connectionManager.send(t,this.client.options.queueMessages,n)}sendPresence(t,n){const s=j({action:O.PRESENCE,channel:this.name,presence:Array.isArray(t)?this.client._RealtimePresence.presenceMessagesFromValuesArray(t):[this.client._RealtimePresence.presenceMessageFromValues(t)]});this.sendMessage(s,n)}async processMessage(t){(t.action===O.ATTACHED||t.action===O.MESSAGE||t.action===O.PRESENCE)&&this.setChannelSerial(t.channelSerial);let n,s=!1;switch(t.action){case O.ATTACHED:{this.properties.attachSerial=t.channelSerial,this._mode=t.getMode(),this.params=t.params||{};const i=t.decodeModesFromFlags();this.modes=i&&st(i)||void 0;const r=t.hasFlag("RESUMED"),a=t.hasFlag("HAS_PRESENCE"),c=t.hasFlag("HAS_BACKLOG");if(this.state==="attached"){r||this._presence&&this._presence.onAttached(a);const h=new St(this.state,this.state,r,c,t.error);this._allChannelChanges.emit("update",h),(!r||this.channelOptions.updateOnAttached)&&this.emit("update",h)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",t.error,r,a,c);break}case O.DETACHED:{const i=t.error?f.fromValues(t.error):new f("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",i):this.state==="attaching"?this.notifyState("suspended",i):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",i);break}case O.SYNC:if(s=!0,n=this.syncChannelSerial=t.channelSerial,!t.presence)break;case O.PRESENCE:{const i=t.presence;if(!i)break;const r=this.channelOptions;await this._decodeAndPrepareMessages(t,i,a=>mt(a,r)),this._presence&&this._presence.setPresence(i,s,n);break}case O.MESSAGE:{if(this.state!=="attached"){o.logAction(this.logger,o.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+t.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}const i=t.messages,r=i[0],a=i[i.length-1],c=t.channelSerial;if(r.extras&&r.extras.delta&&r.extras.delta.from!==this._lastPayload.messageId){const l='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+this.name+'".';o.logAction(this.logger,o.LOG_ERROR,"RealtimeChannel.processMessage()",l),this._startDecodeFailureRecovery(new f(l,40018,400));break}const{unrecoverableError:h}=await this._decodeAndPrepareMessages(t,i,l=>Oe(l,this._decodingContext),l=>{const u=l;switch(u.code){case 40018:return this._startDecodeFailureRecovery(u),{unrecoverableError:!0};case 40019:case 40021:return this.notifyState("failed",u),{unrecoverableError:!0};default:return{unrecoverableError:!1}}});if(h)return;for(let l=0;l<i.length;l++){const u=i[l];c&&!u.version&&(u.version=c+":"+l.toString().padStart(3,"0"),u.expandFields())}this._lastPayload.messageId=a.id,this._lastPayload.protocolMessageChannelSerial=t.channelSerial,this.onEvent(i);break}case O.ERROR:{const i=t.error;i&&i.code==80016?this.checkPendingState():this.notifyState("failed",f.fromValues(i));break}default:o.logAction(this.logger,o.LOG_ERROR,"RealtimeChannel.processMessage()","Fatal protocol error: unrecognised action ("+t.action+")"),this.connectionManager.abort(ie.unknownChannelErr())}}async _decodeAndPrepareMessages(t,n,s,i){const{id:r,connectionId:a,timestamp:c}=t;for(let h=0;h<n.length;h++){const l=n[h];try{await s(l)}catch(u){if(o.logAction(this.logger,o.LOG_ERROR,"RealtimeChannel.decodeAndPrepareMessages()",u.toString()),i){const{unrecoverableError:g}=i(u);if(g)return{unrecoverableError:!0}}}l.connectionId||(l.connectionId=a),l.timestamp||(l.timestamp=c),r&&!l.id&&(l.id=r+":"+h)}return{unrecoverableError:!1}}_startDecodeFailureRecovery(t){this._lastPayload.decodeFailureRecoveryInProgress||(o.logAction(this.logger,o.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,t,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){o.logAction(this.logger,o.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(t,n,s,i,r){if(o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+t),this.clearStateTimer(),["detached","suspended","failed"].includes(t)&&(this.properties.channelSerial=null),t===this.state)return;this._presence&&this._presence.actOnChannelState(t,i,n),t==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),n&&(this.errorReason=n);const a=new St(this.state,t,s,r,n),c='Channel state for channel "'+this.name+'"',h=t+(n?"; reason: "+n:"");t==="failed"?o.logAction(this.logger,o.LOG_ERROR,c,h):o.logAction(this.logger,o.LOG_MAJOR,c,h),t!=="attaching"&&t!=="suspended"&&(this.retryCount=0),t==="attached"&&this.onAttached(),t==="attached"?this._attachResume=!0:(t==="detaching"||t==="failed")&&(this._attachResume=!1),this.state=t,this._allChannelChanges.emit(t,a),this.emit(t,a)}requestState(t,n){o.logAction(this.logger,o.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+t),this.notifyState(t,n),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){o.logAction(this.logger,o.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(o.logAction(this.logger,o.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();break}}timeoutPendingState(){switch(this.state){case"attaching":{const t=new f("Channel attach timed out",90007,408);this.notifyState("suspended",t);break}case"detaching":{const t=new f("Channel detach timed out",90007,408);this.notifyState("attached",t);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{o.logAction(this.logger,o.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){const t=this.stateTimer;t&&(clearTimeout(t),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;const t=it(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,o.logAction(this.logger,o.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){const t=this.state;return t==="initialized"||t==="detached"||t==="failed"?null:new f("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 "+t,90001,400)}setChannelSerial(t){o.logAction(this.logger,o.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+t+"; previous = "+this.properties.channelSerial),t&&(this.properties.channelSerial=t)}async status(){return this.client.rest.channelMixin.status(this)}};function rs(e){const t=e||{},{agent:n}=t;return Ps(t,["agent"])}var _t=Sr,os=class Is extends Pn{constructor(t){var n,s;if(super(C.objectifyOptions(t,!1,"BaseRealtime",o.defaultLogger)),o.logAction(this.logger,o.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new f(`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=Is.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(s=(n=this.options.plugins)==null?void 0:n.RealtimePresence)!=null?s:null,this.connection=new wr(this,this.options),this._channels=new Tr(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(t){const n={};return t?.WebSocketTransport&&(n[G.WebSocket]=t.WebSocketTransport),t?.XHRPolling&&(n[G.XhrPolling]=t.XHRPolling),n}get channels(){return this._channels}connect(){o.logAction(this.logger,o.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){o.logAction(this.logger,o.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};os.EventEmitter=U;var _r=os,Tr=class extends U{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(const t of Re(this.all,!0)){const n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(const t of Re(e,!0)){const n=this.get(t);n.properties.channelSerial=e[t]}}async processChannelMessage(e){const t=e.channel;if(t===void 0){o.logAction(this.logger,o.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action);return}const n=this.all[t];if(!n){o.logAction(this.logger,o.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+t);return}await n.processMessage(e)}onTransportActive(){for(const e in this.all){const t=this.all[e];t.state==="attaching"||t.state==="detaching"?t.checkPendingState():t.state==="suspended"?t._attach(!1,null):t.state==="attached"&&t.requestState("attaching")}}propogateConnectionInterruption(e,t){const n={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},s=["attaching","attached","detaching","suspended"],i=n[e];for(const r in this.all){const a=this.all[r];s.includes(a.state)&&a.notifyState(i,t)}}get(e,t){e=String(e);let n=this.all[e];if(!n)n=this.all[e]=new _t(this.realtime,e,t);else if(t){if(n._shouldReattachToSetOptions(t,n.channelOptions))throw new f("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)}return n}getDerived(e,t,n){if(t.filter){const s=Be(t.filter),i=mn(e);e=`[filter=${s}${i.qualifierParam}]${i.channelName}`}return this.get(e,n)}release(e){e=String(e);const t=this.all[e];if(!t)return;const n=t.getReleaseErr();if(n)throw n;delete this.all[e]}},Mr=_r;function kr(e,t){if(e.isSynthesized()||t.isSynthesized())return e.timestamp>=t.timestamp;const n=e.parseId(),s=t.parseId();return n.msgSerial===s.msgSerial?n.index>s.index:n.msgSerial>s.msgSerial}var Tt=class extends U{constructor(e,t,n=kr){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){const t=this.map,n=[];for(const s in t){const i=t[s];i.clientId==e&&i.action!="absent"&&n.push(i)}return n}list(e){const t=this.map,n=e&&e.clientId,s=e&&e.connectionId,i=[];for(const r in t){const a=t[r];a.action!=="absent"&&(n&&n!=a.clientId||s&&s!=a.connectionId||i.push(a))}return i}put(e){(e.action==="enter"||e.action==="update")&&(e=X(e),e.action="present");const t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];const s=t[n];return s&&!this.newerThan(e,s)?!1:(t[n]=e,!0)}values(){const e=this.map,t=[];for(const n in e){const s=e[n];s.action!="absent"&&t.push(s)}return t}remove(e){const t=this.map,n=this.memberKey(e),s=t[n];return s&&!this.newerThan(e,s)?!1:(this.syncInProgress?(e=X(e),e.action="absent",t[n]=e):delete t[n],!!s)}startSync(){const e=this.map,t=this.syncInProgress;o.logAction(this.logger,o.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),this.syncInProgress||(this.residualMembers=ce(e),this.setInProgress(!0))}endSync(){const e=this.map,t=this.syncInProgress;if(o.logAction(this.logger,o.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),t){for(const n in e)e[n].action==="absent"&&delete e[n];this.presence._synthesizeLeaves(sn(this.residualMembers));for(const n in this.residualMembers)delete e[n];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}waitSync(e){const t=this.syncInProgress;if(o.logAction(this.logger,o.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),!t){e();return}this.once("sync",e)}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){o.logAction(this.logger,o.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+e),this.syncInProgress=e,this.presence.syncComplete=!e}};function Ir(e){return e.channel.client.auth.clientId}function Mt(e){const t=e.channel.client,n=t.auth.clientId;return(!n||n==="*")&&t.connection.state==="connected"}function Er(e,t,n){switch(e.state){case"attached":case"suspended":n();break;case"initialized":case"detached":case"detaching":case"attaching":N(e.attach(),function(s){s?t(s):n()});break;default:t(f.fromValues(e.invalidStateError()))}}var Pr=class extends U{constructor(e){super(e.logger),this.channel=e,this.syncComplete=!1,this.members=new Tt(this,t=>t.clientId+":"+t.connectionId),this._myMembers=new Tt(this,t=>t.clientId),this.subscriptions=new U(this.logger),this.pendingPresence=[]}async enter(e){if(Mt(this))throw new f("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"enter")}async update(e){if(Mt(this))throw new f("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){const i=this.channel;if(!i.connectionManager.activeState())throw i.connectionManager.getError();o.logAction(this.logger,o.LOG_MICRO,"RealtimePresence."+s+"Client()","channel = "+i.name+", id = "+e+", client = "+(t||"(implicit) "+Ir(this)));const r=Fn(n);switch(r.action=s,e&&(r.id=e),t&&(r.clientId=t),await dt(r,i.channelOptions),i.state){case"attached":return new Promise((a,c)=>{i.sendPresence(r,h=>h?c(h):a())});case"initialized":case"detached":i.attach();case"attaching":return new Promise((a,c)=>{this.pendingPresence.push({presence:r,callback:h=>h?c(h):a()})});default:{const a=new P("Unable to "+s+" presence channel while in "+i.state+" state",90001);throw a.code=90001,a}}}async leave(e){if(Mt(this))throw new f("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,e)}async leaveClient(e,t){const n=this.channel;if(!n.connectionManager.activeState())throw n.connectionManager.getError();o.logAction(this.logger,o.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+e);const s=Fn(t);return s.action="leave",e&&(s.clientId=e),new Promise((i,r)=>{switch(n.state){case"attached":n.sendPresence(s,a=>a?r(a):i());break;case"attaching":this.pendingPresence.push({presence:s,callback:a=>a?r(a):i()});break;case"initialized":case"failed":{const a=new P("Unable to leave presence channel (incompatible state)",90001);r(a);break}default:r(n.invalidStateError())}})}async get(e){const t=!e||("waitForSync"in e?e.waitForSync:!0);return new Promise((n,s)=>{function i(r){n(e?r.list(e):r.values())}if(this.channel.state==="suspended"){t?s(f.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):i(this.members);return}Er(this.channel,r=>s(r),()=>{const r=this.members;t?r.waitSync(function(){i(r)}):i(r)})})}async history(e){o.logAction(this.logger,o.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);const t=this.channel.client.rest.presenceMixin;if(e&&e.untilAttach)if(this.channel.state==="attached")delete e.untilAttach,e.from_serial=this.channel.properties.attachSerial;else throw new f("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return t.history(this,e)}setPresence(e,t,n){o.logAction(this.logger,o.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);let s,i;const r=this.members,a=this._myMembers,c=[],h=this.channel.connectionManager.connectionId;t&&(this.members.startSync(),n&&(i=n.match(/^[\w-]+:(.*)$/))&&(s=i[1]));for(let l=0;l<e.length;l++){const u=X(e[l]);switch(u.action){case"leave":r.remove(u)&&c.push(u),u.connectionId===h&&!u.isSynthesized()&&a.remove(u);break;case"enter":case"present":case"update":r.put(u)&&c.push(u),u.connectionId===h&&a.put(u);break}}t&&!s&&(r.endSync(),this.channel.syncChannelSerial=null);for(let l=0;l<c.length;l++){const u=c[l];this.subscriptions.emit(u.action,u)}}onAttached(e){o.logAction(this.logger,o.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+e),e?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();const t=this.pendingPresence,n=t.length;if(n){this.pendingPresence=[];const s=[],i=at.create(this.logger);o.logAction(this.logger,o.LOG_MICRO,"RealtimePresence.onAttached","sending "+n+" queued presence messages");for(let r=0;r<n;r++){const a=t[r];s.push(a.presence),i.push(a.callback)}this.channel.sendPresence(s,i)}}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);break}}failPendingPresence(e){if(this.pendingPresence.length){o.logAction(this.logger,o.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+T(e));for(let t=0;t<this.pendingPresence.length;t++)try{this.pendingPresence[t].callback(e)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){const e=this._myMembers,t=this.channel.connectionManager.connectionId;for(const n in e.map){const s=e.map[n];o.logAction(this.logger,o.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+s.clientId+'" into the presence set');const i=s.connectionId===t?s.id:void 0;this._enterOrUpdateClient(i,s.clientId,s.data,"enter").catch(r=>{const a=new f("Presence auto re-enter failed",91004,400,r);o.logAction(this.logger,o.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+T(r));const c=new St(this.channel.state,this.channel.state,!0,!1,a);this.channel.emit("update",c)})}}_synthesizeLeaves(e){const t=this.subscriptions;e.forEach(function(n){const s=X({action:"leave",connectionId:n.connectionId,clientId:n.clientId,data:n.data,encoding:n.encoding,timestamp:Date.now()});t.emit("leave",s)})}async subscribe(...e){const t=_t.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if(i.state==="failed")throw f.fromValues(i.invalidStateError());this.subscriptions.on(n,s),await i.attach()}unsubscribe(...e){const t=_t.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}},Lr=Pr,Ur=G.WebSocket;function xr(e){return!!e.on}var Nr=class extends ge{constructor(e,t,n){super(e,t,n),this.shortName=Ur,n.heartbeats=d.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!d.Config.WebSocket}createWebSocket(e,t){return this.uri=e+we(t),new d.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){o.logAction(this.logger,o.LOG_MINOR,"WebSocketTransport.connect()","starting"),ge.prototype.connect.call(this);const e=this,t=this.params,n=t.options,i=(n.tls?"wss://":"ws://")+this.wsHost+":"+C.getPort(n)+"/";o.logAction(this.logger,o.LOG_MINOR,"WebSocketTransport.connect()","uri: "+i),N(this.auth.getAuthParams(),function(r,a){if(e.isDisposed)return;let c="";for(const l in a)c+=" "+l+": "+a[l]+";";if(o.logAction(e.logger,o.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+c+" err: "+r),r){e.disconnect(r);return}const h=t.getConnectParams(a);try{const l=e.wsConnection=e.createWebSocket(i,h);l.binaryType=d.Config.binaryType,l.onopen=function(){e.onWsOpen()},l.onclose=function(u){e.onWsClose(u)},l.onmessage=function(u){e.onWsData(u.data)},l.onerror=function(u){e.onWsError(u)},xr(l)&&l.on("ping",function(){e.onActivity()})}catch(l){o.logAction(e.logger,o.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(l.stack||l.message)),e.disconnect(l)}})}send(e){const t=this.wsConnection;if(!t){o.logAction(this.logger,o.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{t.send(rr(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(n){const s="Exception from ws connection when trying to send: "+T(n);o.logAction(this.logger,o.LOG_ERROR,"WebSocketTransport.send()",s),this.finish("disconnected",new f(s,5e4,500))}}onWsData(e){o.logAction(this.logger,o.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+e.length+"; type = "+typeof e);try{this.onProtocolMessage(or(e,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.format))}catch(t){o.logAction(this.logger,o.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+t.stack)}}onWsOpen(){o.logAction(this.logger,o.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(e){let t,n;if(typeof e=="object"?(n=e.code,t=e.wasClean||n===1e3):(n=e,t=n==1e3),delete this.wsConnection,t){o.logAction(this.logger,o.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");const s=new f("Websocket closed",80003,400);this.finish("disconnected",s)}else{const s="Unclean disconnection of WebSocket ; code = "+n,i=new f(s,80003,400);o.logAction(this.logger,o.LOG_MINOR,"WebSocketTransport.onWsClose()",s),this.finish("disconnected",i)}this.emit("disposed")}onWsError(e){o.logAction(this.logger,o.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+e.message),d.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){o.logAction(this.logger,o.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;const e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,d.Config.nextTick(()=>{if(o.logAction(this.logger,o.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!e)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},as=Nr,Gr=class{static subscribeFilter(e,t,n){const s=i=>{var r,a,c,h,l,u;const g={name:i.name,refTimeserial:(a=(r=i.extras)==null?void 0:r.ref)==null?void 0:a.timeserial,refType:(h=(c=i.extras)==null?void 0:c.ref)==null?void 0:h.type,isRef:!!((u=(l=i.extras)==null?void 0:l.ref)!=null&&u.timeserial),clientId:i.clientId};Object.entries(t).find(([m,p])=>p!==void 0?g[m]!==p:!1)||n(i)};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)){const r=e.filteredSubscriptions.get(n);r.set(t,((i=r?.get(t))==null?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(([r,a])=>{var c;let h=a.get(t);return a.delete(t),a.size===0&&((c=e.filteredSubscriptions)==null||c.delete(r)),h}).reduce((r,a)=>a?r.concat(...a):r,[]);if(!n||!e.filteredSubscriptions.has(n))return[];const s=e.filteredSubscriptions.get(n);if(!t){const r=Array.from(s.values()).reduce((a,c)=>a.concat(...c),[]);return e.filteredSubscriptions.delete(n),r}let i=s.get(t);return s.delete(t),i||[]}},F=class jt extends Mr{constructor(t){var n;const s=jt._MsgPack;if(!s)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(C.objectifyOptions(t,!0,"Realtime",o.defaultLogger,J(E({},Kn),{Crypto:(n=jt.Crypto)!=null?n:void 0,MsgPack:s,RealtimePresence:{RealtimePresence:Lr,presenceMessageFromValues:X,presenceMessagesFromValuesArray:jn,presenceMessageFromWireProtocol:Ve},WebSocketTransport:as,MessageInteractions:Gr})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(t){this._Crypto=t}};F.Utils=et,F.ConnectionManager=ss,F.ProtocolMessage=Zn,F._Crypto=null,F.Message=Jn,F.PresenceMessage=Qn,F._MsgPack=null,F._Http=ht,F._PresenceMap=Tt;var kt=F,It=Uint8Array,Se=Uint32Array,Et=Math.pow,cs=new Se(8),ls=[],_e=new Se(64);function hs(e){return(e-(e|0))*Et(2,32)|0}for(var Te=2,Me=0;Me<64;){for(Pt=!0,Je=2;Je<=Te/2;Je++)Te%Je===0&&(Pt=!1);Pt&&(Me<8&&(cs[Me]=hs(Et(Te,1/2))),ls[Me]=hs(Et(Te,1/3)),Me++),Te++}var Pt,Je,qr=!!new It(new Se([1]).buffer)[0];function Lt(e){return qr?e>>>24|(e>>>16&255)<<8|(e&65280)<<8|e<<24:e}function V(e,t){return e>>>t|e<<32-t}function Ut(e){var t=cs.slice(),n=e.length,s=n*8,i=512-(s+64)%512-1+s+65,r=new It(i/8),a=new Se(r.buffer);r.set(e,0),r[n]=128,a[a.length-1]=Lt(s);for(var c,h=0;h<i/32;h+=16){var l=t.slice();for(c=0;c<64;c++){var u;if(c<16)u=Lt(a[h+c]);else{var g=_e[c-15],m=_e[c-2];u=_e[c-7]+_e[c-16]+(V(g,7)^V(g,18)^g>>>3)+(V(m,17)^V(m,19)^m>>>10)}_e[c]=u|=0;for(var p=(V(l[4],6)^V(l[4],11)^V(l[4],25))+(l[4]&l[5]^~l[4]&l[6])+l[7]+u+ls[c],v=(V(l[0],2)^V(l[0],13)^V(l[0],22))+(l[0]&l[1]^l[2]&(l[0]^l[1])),y=7;y>0;y--)l[y]=l[y-1];l[0]=p+v|0,l[4]=l[4]+p|0}for(c=0;c<8;c++)t[c]=t[c]+l[c]|0}return new It(new Se(t.map(function(b){return Lt(b)})).buffer)}function Br(e,t){if(e.length>64&&(e=Ut(e)),e.length<64){const c=new Uint8Array(64);c.set(e,0),e=c}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 a=new Uint8Array(96);return a.set(s,0),a.set(Ut(r),64),Ut(a)}var Dr=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){let t="";const n=this.base64CharSet,s=e.byteLength,i=s%3,r=s-i;let a,c,h,l,u;for(let g=0;g<r;g=g+3)u=e[g]<<16|e[g+1]<<8|e[g+2],a=(u&16515072)>>18,c=(u&258048)>>12,h=(u&4032)>>6,l=u&63,t+=n[a]+n[c]+n[h]+n[l];return i==1?(u=e[r],a=(u&252)>>2,c=(u&3)<<4,t+=n[a]+n[c]+"=="):i==2&&(u=e[r]<<8|e[r+1],a=(u&64512)>>10,c=(u&1008)>>4,h=(u&15)<<2,t+=n[a]+n[c]+n[h]+"="),t}base64ToArrayBuffer(e){const t=atob?.(e),n=t.length,s=new Uint8Array(n);for(let i=0;i<n;i++){const r=t.charCodeAt(i);s[i]=r}return this.toArrayBuffer(s)}isBuffer(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}toBuffer(e){if(!ArrayBuffer)throw new 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 new Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(e){if(!ArrayBuffer)throw new 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 new Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(e){return this.uint8ViewToBase64(this.toBuffer(e))}base64Decode(e){if(ArrayBuffer&&d.Config.atob)return this.base64ToArrayBuffer(e);throw new Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(e){return this.toBuffer(e).reduce((n,s)=>n+s.toString(16).padStart(2,"0"),"")}hexDecode(e){if(e.length%2!==0)throw new Error("Can't create a byte array from a hex string of odd length");const 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(d.Config.TextEncoder){const t=new d.Config.TextEncoder().encode(e);return this.toArrayBuffer(t)}else throw new Error("Expected TextEncoder to be configured")}utf8Decode(e){if(!this.isBuffer(e))throw new Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return new TextDecoder().decode(e);throw new Error("Expected TextDecoder to be configured")}areBuffersEqual(e,t){if(!e||!t)return!1;const n=this.toArrayBuffer(e),s=this.toArrayBuffer(t);if(n.byteLength!=s.byteLength)return!1;const i=new Uint8Array(n),r=new Uint8Array(s);for(var a=0;a<i.length;a++)if(i[a]!=r[a])return!1;return!0}byteLength(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}arrayBufferViewToBuffer(e){return this.toArrayBuffer(e)}hmacSha256(e,t){const n=Br(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},us=new Dr,Hr=function(e,t){var n="aes",s=256,i="cbc",r=16;function a(m){if(m.algorithm==="aes"&&m.mode==="cbc"){if(m.keyLength===128||m.keyLength===256)return;throw new Error("Unsupported key length "+m.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function c(m){return m.replace("_","/").replace("-","+")}function h(m){return m instanceof l}class l{constructor(p,v,y,b){this.algorithm=p,this.keyLength=v,this.mode=y,this.key=b}}class u{static getDefaultParams(p){var v;if(!p.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof p.key=="string"?v=t.toArrayBuffer(t.base64Decode(c(p.key))):p.key instanceof ArrayBuffer?v=p.key:v=t.toArrayBuffer(p.key);var y=p.algorithm||n,b=v.byteLength*8,A=p.mode||i,S=new l(y,b,A,v);if(p.keyLength&&p.keyLength!==S.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+p.keyLength+" was specified, but the key actually has length "+S.keyLength);return a(S),S}static async generateRandomKey(p){try{return e.getRandomArrayBuffer((p||s)/8)}catch(v){throw new f("Failed to generate random key: "+v.message,400,5e4,v)}}static getCipher(p,v){var y,b=h(p)?p:this.getDefaultParams(p);return{cipherParams:b,cipher:new g(b,(y=p.iv)!=null?y:null,v)}}}u.CipherParams=l;class g{constructor(p,v,y){if(this.logger=y,!crypto.subtle)throw isSecureContext?new Error("Crypto operations are not possible since the browser’s SubtleCrypto class is unavailable (reason unknown)."):new 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=p.algorithm+"-"+String(p.keyLength)+"-"+p.mode,this.webCryptoAlgorithm=p.algorithm+"-"+p.mode,this.key=t.toArrayBuffer(p.key),this.iv=v?t.toArrayBuffer(v):null}concat(p,v){const y=new ArrayBuffer(p.byteLength+v.byteLength),b=new DataView(y),A=new DataView(t.toArrayBuffer(p));for(let _=0;_<A.byteLength;_++)b.setInt8(_,A.getInt8(_));const S=new DataView(t.toArrayBuffer(v));for(let _=0;_<S.byteLength;_++)b.setInt8(A.byteLength+_,S.getInt8(_));return y}async encrypt(p){o.logAction(this.logger,o.LOG_MICRO,"CBCCipher.encrypt()","");const v=await this.getIv(),y=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),b=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:v},y,p);return this.concat(v,b)}async decrypt(p){o.logAction(this.logger,o.LOG_MICRO,"CBCCipher.decrypt()","");const v=t.toArrayBuffer(p),y=v.slice(0,r),b=v.slice(r),A=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:y},A,b)}async getIv(){if(this.iv){var p=this.iv;return this.iv=null,p}const v=await e.getRandomArrayBuffer(r);return t.toArrayBuffer(v)}}return u},ds=(e=>(e[e.REQ_SEND=0]="REQ_SEND",e[e.REQ_RECV=1]="REQ_RECV",e[e.REQ_RECV_POLL=2]="REQ_RECV_POLL",e[e.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",e))(ds||{}),Z=ds;function fs(){return new f("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var ke,gs=(ke=class{constructor(e){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1;var t;this.client=e??null;const n=e?.options.connectivityCheckUrl||C.connectivityCheckUrl,s=(t=e?.options.connectivityCheckParams)!=null?t:null,i=!e?.options.connectivityCheckUrl,r=E(E({},gs.bundledRequestImplementations),e?._additionalHTTPRequestImplementations),a=r.XHRRequest,c=r.FetchRequest,h=!!(a||c);if(!h)throw fs();d.Config.xhrSupported&&a?(this.supportsAuthHeaders=!0,this.Request=async function(l,u,g,m,p){return new Promise(v=>{var y;const b=a.createRequest(u,g,m,p,Z.REQ_SEND,(y=e&&e.options.timeouts)!=null?y:null,this.logger,l);b.once("complete",(A,S,_,R,B)=>v({error:A,body:S,headers:_,unpacked:R,statusCode:B})),b.exec()})},e?.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var l;o.logAction(this.logger,o.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);const u=await this.doUri(M.Get,n,null,null,s);let g=!1;return i?g=!u.error&&((l=u.body)==null?void 0:l.replace(/\n/,""))=="yes":g=!u.error&&si(u.statusCode),o.logAction(this.logger,o.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+g),g}):d.Config.fetchSupported&&c?(this.supportsAuthHeaders=!0,this.Request=async(l,u,g,m,p)=>c(l,e??null,u,g,m,p),this.checkConnectivity=async function(){var l;o.logAction(this.logger,o.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);const u=await this.doUri(M.Get,n,null,null,null),g=!u.error&&((l=u.body)==null?void 0:l.replace(/\n/,""))=="yes";return o.logAction(this.logger,o.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+g),g}):this.Request=async()=>({error:h?new P("no supported HTTP transports available",null,400):fs()})}get logger(){var e,t;return(t=(e=this.client)==null?void 0:e.logger)!=null?t:o.defaultLogger}async doUri(e,t,n,s,i){return this.Request?this.Request(e,t,n,i,s):{error:new P("Request invoked before assigned to",null,500)}}shouldFallback(e){const t=e.statusCode;return t===408&&!e.code||t===400&&!e.code||t>=500&&t<=504}},ke.methods=[M.Get,M.Delete,M.Post,M.Put,M.Patch],ke.methodsWithoutBody=[M.Get,M.Delete],ke.methodsWithBody=[M.Post,M.Put,M.Patch],ke),ps=gs,pe="ablyjs-storage-test",me=typeof re<"u"?re:typeof window<"u"?window:self,Wr=class{constructor(){try{me.sessionStorage.setItem(pe,pe),me.sessionStorage.removeItem(pe),this.sessionSupported=!0}catch{this.sessionSupported=!1}try{me.localStorage.setItem(pe,pe),me.localStorage.removeItem(pe),this.localSupported=!0}catch{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){const 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 new Error("Session Storage not supported");if(!t&&!this.localSupported)throw new Error("Local Storage not supported");const n=this.storageInterface(t).getItem(e);if(!n)return null;const 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?me.sessionStorage:me.localStorage}},ms=new Wr,k=rt(),jr=typeof EdgeRuntime=="string";typeof Window>"u"&&typeof WorkerGlobalScope>"u"&&!jr&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function Fr(){const e=k.location;return!k.WebSocket||!e||!e.origin||e.origin.indexOf("http")>-1}function Vr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}var zr=k.navigator&&k.navigator.userAgent.toString(),Kr=k.location&&k.location.href,Jr={agent:"browser",logTimestamps:!0,userAgent:zr,currentUrl:Kr,binaryType:"arraybuffer",WebSocket:k.WebSocket,fetchSupported:!!k.fetch,xhrSupported:k.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:Fr(),useProtocolHeartbeats:!0,supportsBinary:!!k.TextDecoder,preferBinary:!1,ArrayBuffer:k.ArrayBuffer,atob:k.atob,nextTick:typeof k.setImmediate<"u"?k.setImmediate.bind(k):function(e){setTimeout(e,0)},addEventListener:k.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return k.TextDecoder&&new k.TextEncoder().encode(e).length||e.length},TextEncoder:k.TextEncoder,TextDecoder:k.TextDecoder,getRandomArrayBuffer:async function(e){const t=new Uint8Array(e);return k.crypto.getRandomValues(t),t.buffer},isWebworker:Vr(),push:{platform:"browser",formFactor:"desktop",storage:ms}},ys=Jr;function Qr(e){const t=[80015,80017,80030];return e.code?$.isTokenErr(e)?!1:t.includes(e.code)?!0:e.code>=4e4&&e.code<5e4:!1}function xt(e){return Qr(e)?[j({action:O.ERROR,error:e})]:[j({action:O.DISCONNECTED,error:e})]}var $r=class extends ge{constructor(e,t,n){super(e,t,n,!0),this.onAuthUpdated=s=>{this.authParams={access_token:s.token}},this.stream="stream"in n?n.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){o.logAction(this.logger,o.LOG_MINOR,"CometTransport.connect()","starting"),ge.prototype.connect.call(this);const e=this.params,t=e.options,n=C.getHost(t,e.host),s=C.getPort(t),i=t.tls?"https://":"http://";this.baseUri=i+n+":"+s+"/comet/";const r=this.baseUri+"connect";o.logAction(this.logger,o.LOG_MINOR,"CometTransport.connect()","uri: "+r),N(this.auth.getAuthParams(),(a,c)=>{if(a){this.disconnect(a);return}if(this.isDisposed)return;this.authParams=c;const h=this.params.getConnectParams(c);"stream"in h&&(this.stream=h.stream),o.logAction(this.logger,o.LOG_MINOR,"CometTransport.connect()","connectParams:"+we(h));let l=!1;const u=this.recvRequest=this.createRequest(r,null,h,null,this.stream?Z.REQ_RECV_STREAM:Z.REQ_RECV);u.on("data",g=>{this.recvRequest&&(l||(l=!0,this.emit("preconnect")),this.onData(g))}),u.on("complete",g=>{if(this.recvRequest||(g=g||new f("Request cancelled",80003,400)),this.recvRequest=null,!l&&!g&&(l=!0,this.emit("preconnect")),this.onActivity(),g){g.code?this.onData(xt(g)):this.disconnect(g);return}d.Config.nextTick(()=>{this.recv()})}),u.exec()})}requestClose(){o.logAction(this.logger,o.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){o.logAction(this.logger,o.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(e){const t=e?this.closeUri:this.disconnectUri;if(t){const n=this.createRequest(t,null,this.authParams,null,Z.REQ_SEND);n.on("complete",s=>{s&&(o.logAction(this.logger,o.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+T(s)),this.finish("disconnected",s))}),n.exec()}}dispose(){o.logAction(this.logger,o.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(o.logAction(this.logger,o.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",ie.disconnected()),d.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(e){var t;if(this.isDisposed)return;const n=(t=e.connectionDetails)==null?void 0:t.connectionKey;ge.prototype.onConnect.call(this,e);const s=this.baseUri+n;o.logAction(this.logger,o.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}const t=this.pendingItems||[];t.push(e),this.pendingItems=null,this.sendItems(t)}sendAnyPending(){const e=this.pendingItems;e&&(this.pendingItems=null,this.sendItems(e))}sendItems(e){const t=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(e),Z.REQ_SEND);t.on("complete",(n,s)=>{if(n&&o.logAction(this.logger,o.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+T(n)),this.sendRequest=null,n){n.code?this.onData(xt(n)):this.disconnect(n);return}s&&this.onData(s),this.pendingItems&&d.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),t.exec()}recv(){if(this.recvRequest||!this.isConnected)return;const e=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?Z.REQ_RECV_STREAM:Z.REQ_RECV_POLL);e.on("data",t=>{this.onData(t)}),e.on("complete",t=>{if(this.recvRequest=null,this.onActivity(),t){t.code?this.onData(xt(t)):this.disconnect(t);return}d.Config.nextTick(()=>{this.recv()})}),e.exec()}onData(e){try{const t=this.decodeResponse(e);if(t&&t.length)for(let n=0;n<t.length;n++)this.onProtocolMessage(bt(t[n],this.connectionManager.realtime._RealtimePresence))}catch(t){o.logAction(this.logger,o.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+t.stack)}}encodeRequest(e){return JSON.stringify(e)}decodeResponse(e){return typeof e=="string"?JSON.parse(e):e}},Xr=$r;function Yr(e,t){return st(Re(t)).includes("x-ably-errorcode")}function Zr(e,t){if(Yr(e,t))return e.error&&f.fromValues(e.error)}var eo=function(){},to=0,vs={};function no(e,t){return e.getResponseHeader&&e.getResponseHeader(t)}function so(e){return e.getResponseHeader&&(e.getResponseHeader("transfer-encoding")||!e.getResponseHeader("content-length"))}function io(e){const t=e.getAllResponseHeaders().trim().split(`\r
`),n={};for(let s=0;s<t.length;s++){const i=t[s].split(":").map(r=>r.trim());n[i[0].toLowerCase()]=i[1]}return n}var ro=class Es extends U{constructor(t,n,s,i,r,a,c,h){super(c),s=s||{},s.rnd=qe(),this.uri=t+we(s),this.headers=n||{},this.body=i,this.method=h?h.toUpperCase():H(i)?"GET":"POST",this.requestMode=r,this.timeouts=a,this.timedOut=!1,this.requestComplete=!1,this.id=String(++to),vs[this.id]=this}static createRequest(t,n,s,i,r,a,c,h){const l=a||C.TIMEOUTS;return new Es(t,n,ce(s),i,r,l,c,h)}complete(t,n,s,i,r){this.requestComplete||(this.requestComplete=!0,!t&&n&&this.emit("data",n),this.emit("complete",t,n,s,i,r),this.dispose())}abort(){this.dispose()}exec(){let t=this.headers;const n=this.requestMode==Z.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,s=this.timer=setTimeout(()=>{this.timedOut=!0,r.abort()},n),i=this.method,r=this.xhr=new XMLHttpRequest,a=t.accept;let c=this.body,h="text";a?a.indexOf("application/x-msgpack")===0&&(h="arraybuffer"):t.accept="application/json",c&&(t["content-type"]||(t["content-type"]="application/json")).indexOf("application/json")>-1&&typeof c!="string"&&(c=JSON.stringify(c)),r.open(i,this.uri,!0),r.responseType=h,"authorization"in t&&(r.withCredentials=!0);for(const R in t)r.setRequestHeader(R,t[R]);const l=(R,B,x,Le)=>{var ye;let Bt=B+" (event type: "+R.type+")";(ye=this==null?void 0:this.xhr)!=null&&ye.statusText&&(Bt+=", current statusText is "+this.xhr.statusText),o.logAction(this.logger,o.LOG_ERROR,"Request.on"+R.type+"()",Bt),this.complete(new P(Bt,x,Le))};r.onerror=function(R){l(R,"XHR error occurred",null,400)},r.onabort=R=>{this.timedOut?l(R,"Request aborted due to request timeout expiring",null,408):l(R,"Request cancelled",null,400)},r.ontimeout=function(R){l(R,"Request timed out",null,408)};let u,g,m,p=0,v=!1;const y=()=>{if(clearTimeout(s),m=g<400,g==204){this.complete(null,null,null,null,g);return}u=this.requestMode==Z.REQ_RECV_STREAM&&m&&so(r)},b=()=>{let R;try{const x=no(r,"content-type");if(x?x.indexOf("application/json")>=0:r.responseType=="text"){const ye=r.responseType==="arraybuffer"?d.BufferUtils.utf8Decode(r.response):String(r.responseText);ye.length?R=JSON.parse(ye):R=ye,v=!0}else R=r.response;R.response!==void 0?(g=R.statusCode,m=g<400,t=R.headers,R=R.response):t=io(r)}catch(x){this.complete(new P("Malformed response body from server: "+x.message,null,400));return}if(m||Array.isArray(R)){this.complete(null,R,t,v,g);return}let B=Zr(R,t);B||(B=new P("Error response received from server: "+g+" body was: "+d.Config.inspect(R),null,g)),this.complete(B,R,t,v,g)};function A(){const R=r.responseText,B=R.length-1;let x,Le;for(;p<B&&(x=R.indexOf(`
`,p))>-1;)Le=R.slice(p,x),p=x+1,S(Le)}const S=R=>{try{R=JSON.parse(R)}catch(B){this.complete(new P("Malformed response body from server: "+B.message,null,400));return}this.emit("data",R)},_=()=>{A(),this.streamComplete=!0,d.Config.nextTick(()=>{this.complete()})};r.onreadystatechange=function(){const R=r.readyState;R<3||r.status!==0&&(g===void 0&&(g=r.status,y()),R==3&&u?A():R==4&&(u?_():b()))},r.send(c)}dispose(){const t=this.xhr;if(t){t.onreadystatechange=t.onerror=t.onabort=t.ontimeout=eo,this.xhr=null;const n=this.timer;n&&(clearTimeout(n),this.timer=null),this.requestComplete||t.abort()}delete vs[this.id]}},bs=ro,Cs=G.XhrPolling,oo=class extends Xr{constructor(e,t,n){super(e,t,n),this.shortName=Cs,n.stream=!1,this.shortName=Cs}static isAvailable(){return!!(d.Config.xhrSupported&&d.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,i){return bs.createRequest(e,t,n,s,i,this.timeouts,this.logger)}},ao=oo,co=["xhr_polling"],lo={order:co,bundledImplementations:{web_socket:as,xhr_polling:ao}},ho=lo,uo={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[G.XhrPolling,G.WebSocket]},fo=uo;function go(e){if(e===void 0)return"undefined";let t,n;if(e instanceof ArrayBuffer?(n="ArrayBuffer",t=new DataView(e)):e instanceof DataView&&(n="DataView",t=e),!t)return JSON.stringify(e);const s=[];for(let i=0;i<e.byteLength;i++){if(i>20){s.push("...");break}let r=t.getUint8(i).toString(16);r.length===1&&(r="0"+r),s.push(r)}return"<"+n+" "+s.join(" ")+">"}function Ie(e,t,n){for(let s=0,i=n.length;s<i;s++){const r=n.charCodeAt(s);if(r<128){e.setUint8(t++,r>>>0&127|0);continue}if(r<2048){e.setUint8(t++,r>>>6&31|192),e.setUint8(t++,r>>>0&63|128);continue}if(r<65536){e.setUint8(t++,r>>>12&15|224),e.setUint8(t++,r>>>6&63|128),e.setUint8(t++,r>>>0&63|128);continue}if(r<1114112){e.setUint8(t++,r>>>18&7|240),e.setUint8(t++,r>>>12&63|128),e.setUint8(t++,r>>>6&63|128),e.setUint8(t++,r>>>0&63|128);continue}throw new Error("bad codepoint "+r)}}function Rs(e,t,n){let s="";for(let i=t,r=t+n;i<r;i++){const a=e.getUint8(i);if((a&128)===0){s+=String.fromCharCode(a);continue}if((a&224)===192){s+=String.fromCharCode((a&15)<<6|e.getUint8(++i)&63);continue}if((a&240)===224){s+=String.fromCharCode((a&15)<<12|(e.getUint8(++i)&63)<<6|(e.getUint8(++i)&63)<<0);continue}if((a&248)===240){s+=String.fromCharCode((a&7)<<18|(e.getUint8(++i)&63)<<12|(e.getUint8(++i)&63)<<6|(e.getUint8(++i)&63)<<0);continue}throw new Error("Invalid byte "+a.toString(16))}return s}function Nt(e){let t=0;for(let n=0,s=e.length;n<s;n++){const i=e.charCodeAt(n);if(i<128){t+=1;continue}if(i<2048){t+=2;continue}if(i<65536){t+=3;continue}if(i<1114112){t+=4;continue}throw new Error("bad codepoint "+i)}return t}function po(e,t){const n=Pe(e,t);if(n===0)return;const s=new ArrayBuffer(n),i=new DataView(s);return Ee(e,i,0,t),s}var Gt=65536*65536,ws=1/Gt;function mo(e,t){return t=t||0,e.getInt32(t)*Gt+e.getUint32(t+4)}function yo(e,t){return t=t||0,e.getUint32(t)*Gt+e.getUint32(t+4)}function vo(e,t,n){n<9223372036854776e3?(e.setInt32(t,Math.floor(n*ws)),e.setInt32(t+4,n&-1)):(e.setUint32(t,2147483647),e.setUint32(t+4,2147483647))}function bo(e,t,n){n<18446744073709552e3?(e.setUint32(t,Math.floor(n*ws)),e.setInt32(t+4,n&-1)):(e.setUint32(t,4294967295),e.setUint32(t+4,4294967295))}var Co=class{constructor(e,t){this.map=n=>{const s={};for(let i=0;i<n;i++){const r=this.parse();s[r]=this.parse()}return s},this.bin=n=>{const s=new ArrayBuffer(n);return new Uint8Array(s).set(new Uint8Array(this.view.buffer,this.offset,n),0),this.offset+=n,s},this.buf=this.bin,this.str=n=>{const s=Rs(this.view,this.offset,n);return this.offset+=n,s},this.array=n=>{const s=new Array(n);for(let i=0;i<n;i++)s[i]=this.parse();return s},this.ext=n=>(this.offset+=n,{type:this.view.getInt8(this.offset),data:this.buf(n)}),this.parse=()=>{const n=this.view.getUint8(this.offset);let s,i;if((n&128)===0)return this.offset++,n;if((n&240)===128)return i=n&15,this.offset++,this.map(i);if((n&240)===144)return i=n&15,this.offset++,this.array(i);if((n&224)===160)return i=n&31,this.offset++,this.str(i);if((n&224)===224)return s=this.view.getInt8(this.offset),this.offset++,s;switch(n){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 i=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(i);case 197:return i=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(i);case 198:return i=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(i);case 199:return i=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(i);case 200:return i=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(i);case 201:return i=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(i);case 202:return s=this.view.getFloat32(this.offset+1),this.offset+=5,s;case 203:return s=this.view.getFloat64(this.offset+1),this.offset+=9,s;case 204:return s=this.view.getUint8(this.offset+1),this.offset+=2,s;case 205:return s=this.view.getUint16(this.offset+1),this.offset+=3,s;case 206:return s=this.view.getUint32(this.offset+1),this.offset+=5,s;case 207:return s=yo(this.view,this.offset+1),this.offset+=9,s;case 208:return s=this.view.getInt8(this.offset+1),this.offset+=2,s;case 209:return s=this.view.getInt16(this.offset+1),this.offset+=3,s;case 210:return s=this.view.getInt32(this.offset+1),this.offset+=5,s;case 211:return s=mo(this.view,this.offset+1),this.offset+=9,s;case 212:return i=1,this.offset++,this.ext(i);case 213:return i=2,this.offset++,this.ext(i);case 214:return i=4,this.offset++,this.ext(i);case 215:return i=8,this.offset++,this.ext(i);case 216:return i=16,this.offset++,this.ext(i);case 217:return i=this.view.getUint8(this.offset+1),this.offset+=2,this.str(i);case 218:return i=this.view.getUint16(this.offset+1),this.offset+=3,this.str(i);case 219:return i=this.view.getUint32(this.offset+1),this.offset+=5,this.str(i);case 220:return i=this.view.getUint16(this.offset+1),this.offset+=3,this.array(i);case 221:return i=this.view.getUint32(this.offset+1),this.offset+=5,this.array(i);case 222:return i=this.view.getUint16(this.offset+1),this.offset+=3,this.map(i);case 223:return i=this.view.getUint32(this.offset+1),this.offset+=5,this.map(i)}throw new Error("Unknown type 0x"+n.toString(16))},this.offset=t||0,this.view=e}};function Ro(e){const t=new DataView(e),n=new Co(t),s=n.parse();if(n.offset!==e.byteLength)throw new Error(e.byteLength-n.offset+" trailing bytes");return s}function Os(e,t){return Object.keys(e).filter(function(n){const s=e[n],i=typeof s;return(!t||s!=null)&&(i!=="function"||!!s.toJSON)})}function Ee(e,t,n,s){const i=typeof e;if(typeof e=="string"){const r=Nt(e);if(r<32)return t.setUint8(n,r|160),Ie(t,n+1,e),1+r;if(r<256)return t.setUint8(n,217),t.setUint8(n+1,r),Ie(t,n+2,e),2+r;if(r<65536)return t.setUint8(n,218),t.setUint16(n+1,r),Ie(t,n+3,e),3+r;if(r<4294967296)return t.setUint8(n,219),t.setUint32(n+1,r),Ie(t,n+5,e),5+r}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){const r=e.byteLength;if(r<256)return t.setUint8(n,196),t.setUint8(n+1,r),new Uint8Array(t.buffer).set(new Uint8Array(e),n+2),2+r;if(r<65536)return t.setUint8(n,197),t.setUint16(n+1,r),new Uint8Array(t.buffer).set(new Uint8Array(e),n+3),3+r;if(r<4294967296)return t.setUint8(n,198),t.setUint32(n+1,r),new Uint8Array(t.buffer).set(new Uint8Array(e),n+5),5+r}if(typeof e=="number"){if(Math.floor(e)!==e)return t.setUint8(n,203),t.setFloat64(n+1,e),9;if(e>=0){if(e<128)return t.setUint8(n,e),1;if(e<256)return t.setUint8(n,204),t.setUint8(n+1,e),2;if(e<65536)return t.setUint8(n,205),t.setUint16(n+1,e),3;if(e<4294967296)return t.setUint8(n,206),t.setUint32(n+1,e),5;if(e<18446744073709552e3)return t.setUint8(n,207),bo(t,n+1,e),9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return t.setInt8(n,e),1;if(e>=-128)return t.setUint8(n,208),t.setInt8(n+1,e),2;if(e>=-32768)return t.setUint8(n,209),t.setInt16(n+1,e),3;if(e>=-2147483648)return t.setUint8(n,210),t.setInt32(n+1,e),5;if(e>=-9223372036854776e3)return t.setUint8(n,211),vo(t,n+1,e),9;throw new Error("Number too small -0x"+(-e).toString(16).substr(1))}if(i==="undefined")return s?0:(t.setUint8(n,212),t.setUint8(n+1,0),t.setUint8(n+2,0),3);if(e===null)return s?0:(t.setUint8(n,192),1);if(i==="boolean")return t.setUint8(n,e?195:194),1;if(typeof e.toJSON=="function")return Ee(e.toJSON(),t,n,s);if(i==="object"){let r,a=0,c;const h=Array.isArray(e);if(h?r=e.length:(c=Os(e,s),r=c.length),r<16?(t.setUint8(n,r|(h?144:128)),a=1):r<65536?(t.setUint8(n,h?220:222),t.setUint16(n+1,r),a=3):r<4294967296&&(t.setUint8(n,h?221:223),t.setUint32(n+1,r),a=5),h)for(let l=0;l<r;l++)a+=Ee(e[l],t,n+a,s);else if(c)for(let l=0;l<r;l++){const u=c[l];a+=Ee(u,t,n+a),a+=Ee(e[u],t,n+a,s)}return a}if(i==="function")return 0;throw new Error("Unknown type "+i)}function Pe(e,t){const n=typeof e;if(n==="string"){const s=Nt(e);if(s<32)return 1+s;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){const s=e.byteLength;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(typeof e=="number"){if(Math.floor(e)!==e)return 9;if(e>=0){if(e<128)return 1;if(e<256)return 2;if(e<65536)return 3;if(e<4294967296)return 5;if(e<18446744073709552e3)return 9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return 1;if(e>=-128)return 2;if(e>=-32768)return 3;if(e>=-2147483648)return 5;if(e>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+e.toString(16).substr(1))}if(n==="boolean")return 1;if(e===null)return t?0:1;if(e===void 0)return t?0:3;if(typeof e.toJSON=="function")return Pe(e.toJSON(),t);if(n==="object"){let s,i=0;if(Array.isArray(e)){s=e.length;for(let r=0;r<s;r++)i+=Pe(e[r],t)}else{const r=Os(e,t);s=r.length;for(let a=0;a<s;a++){const c=r[a];i+=Pe(c)+Pe(e[c],t)}}if(s<16)return 1+i;if(s<65536)return 3+i;if(s<4294967296)return 5+i;throw new Error("Array or object too long 0x"+s.toString(16))}if(n==="function")return 0;throw new Error("Unknown type "+n)}var qt={encode:po,decode:Ro,inspect:go,utf8Write:Ie,utf8Read:Rs,utf8ByteCount:Nt};function wo(e,t){return!!t.get("x-ably-errorcode")}function Oo(e,t){if(wo(e,t))return e.error&&f.fromValues(e.error)}function Ao(e){const t={};return e.forEach((n,s)=>{t[s]=n}),t}async function So(e,t,n,s,i,r){const a=new Headers(s||{}),c=e?e.toUpperCase():H(r)?"GET":"POST",h=new AbortController;let l;const u=new Promise(p=>{l=setTimeout(()=>{h.abort(),p({error:new P("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:C.TIMEOUTS.httpRequestTimeout)}),g={method:c,headers:a,body:r,signal:h.signal};d.Config.isWebworker||(g.credentials=a.has("authorization")?"include":"same-origin");const m=(async()=>{try{const p=new URLSearchParams(i||{});p.set("rnd",qe());const v=n+"?"+p,y=await rt().fetch(v,g);if(clearTimeout(l),y.status==204)return{error:null,statusCode:y.status};const b=y.headers.get("Content-Type");let A;b&&b.indexOf("application/x-msgpack")>-1?A=await y.arrayBuffer():b&&b.indexOf("application/json")>-1?A=await y.json():A=await y.text();const S=!!b&&b.indexOf("application/x-msgpack")===-1,_=Ao(y.headers);return y.ok?{error:null,body:A,headers:_,unpacked:S,statusCode:y.status}:{error:Oo(A,y.headers)||new P("Error response received from server: "+y.status+" body was: "+d.Config.inspect(A),null,y.status),body:A,headers:_,unpacked:S,statusCode:y.status}}catch(p){return clearTimeout(l),{error:p}}})();return Promise.race([u,m])}var _o={XHRRequest:bs,FetchRequest:So},As=Hr(ys,us);d.Crypto=As,d.BufferUtils=us,d.Http=ps,d.Config=ys,d.Transports=ho,d.WebStorage=ms;for(const e of[yt,kt])e.Crypto=As,e._MsgPack=qt;ps.bundledRequestImplementations=_o,o.initLogHandlers(),d.Defaults=ti(fo),d.Config.agent&&(d.Defaults.agent+=" "+d.Config.agent);var To={ErrorInfo:f,Rest:yt,Realtime:kt,msgpack:qt};if(typeof z.exports=="object"&&typeof ee=="object"){var Mo=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")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};z.exports=Mo(z.exports,ee)}return z.exports})}(Qe)),Qe.exports}var Do=Bo();function Yo(){const[oe]=Eo("user");return oe?ko.jsx(Ho,{userSignalsChannel:oe.userSignalsChannel},oe.id):null}function Ho({userSignalsChannel:oe}){const[Ft]=Po(Wo),ee=Lo();function z(){ee.refetchQueries({include:[xo]})}const ae=()=>{ee.refetchQueries({include:[No]})},Xe=()=>{ee.refetchQueries({include:[Go]})};return Io.useEffect(()=>{const Ce=new Do.Realtime({authCallback:(Ye,K)=>{Ft().then(({data:te})=>{if(!te?.generateAblyTokenRequest.tokenRequest){K("No data returned",null);return}K(null,JSON.parse(te.generateAblyTokenRequest.tokenRequest))}).catch(te=>{K("Error",null)})},realtimeRequestTimeout:25e3});return Ce.connection.on("connected",()=>{Ce.channels.get(oe).subscribe(K=>{K.name==="refetch_root_data"&&z(),K.name==="refetch_balance_transaction_reports"&&ae(),K.name==="refetch_hris_integration"&&Xe()})}),()=>{Ce.close()}},[]),null}const Wo=Uo`
  mutation GenerateAblyTokenRequest {
    generateAblyTokenRequest {
      tokenRequest
    }
  }
`;export{Yo as default};