import{j as Mo}from"./vendors-G61NC5D4.js";import{d as se,r as ko}from"./react-CRjHcyn1.js";import{U as Io,V as Eo,W as Po,X as Lo,Y as Uo,Z as xo,_ as No}from"./index-BTl5Gysz.js";import"./analytics-e_U0oswF.js";import"./utils-CsLaO2iZ.js";import"./dateTime-BHGoDcSC.js";import"./ui-BcmfUO8P.js";import"./media-CbS6VBpW.js";import"./icons-Cmqfkpn_.js";(function(){try{var D=typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Re=new Error().stack;Re&&(D._sentryDebugIds=D._sentryDebugIds||{},D._sentryDebugIds[Re]="3e43334a-8e0d-412f-b802-f74c9a6d79ba",D._sentryDebugIdIdentifier="sentry-dbid-3e43334a-8e0d-412f-b802-f74c9a6d79ba")}catch{}})();var As={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*/(function(D,Re){(function(J,Q){D.exports=Q()})(se,()=>{var J={},Q={exports:J},ae=Object.defineProperty,Xe=Object.defineProperties,we=Object.getOwnPropertyDescriptor,Ye=Object.getOwnPropertyDescriptors,$=Object.getOwnPropertyNames,j=Object.getOwnPropertySymbols,Ze=Object.prototype.hasOwnProperty,Ft=Object.prototype.propertyIsEnumerable,Vt=(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)&&Vt(e,n,t[n]);if(j)for(var n of j(t))Ft.call(t,n)&&Vt(e,n,t[n]);return e},X=(e,t)=>Xe(e,Ye(t)),Es=(e,t)=>{var n={};for(var s in e)Ze.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&j)for(var s of j(e))t.indexOf(s)<0&&Ft.call(e,s)&&(n[s]=e[s]);return n},zt=(e,t)=>{for(var n in t)ae(e,n,{get:t[n],enumerable:!0})},Ps=(e,t,n,s)=>{if(typeof t=="object"||typeof t=="function")for(let i of $(t))!Ze.call(e,i)&&i!==n&&ae(e,i,{get:()=>t[i],enumerable:!(s=we(t,i))||s.enumerable});return e},Ls=e=>Ps(ae({},"__esModule",{value:!0}),e),Kt={};zt(Kt,{ErrorInfo:()=>f,Realtime:()=>kt,Rest:()=>yt,default:()=>_o,msgpack:()=>qt,protocolMessageFromDeserialized:()=>or}),Q.exports=Ls(Kt);var d=class{},Jt=typeof se<"u"?se:typeof window<"u"?window:self;function Ge(e,t){return`${e}`.padStart(t?3:2,"0")}function Us(e){return d.Config.logTimestamps?function(t){const n=new Date;e(Ge(n.getHours())+":"+Ge(n.getMinutes())+":"+Ge(n.getSeconds())+"."+Ge(n.getMilliseconds(),1)+" "+t)}:function(t){e(t)}}var xs=()=>{var e;let t,n;return typeof((e=Jt==null?void 0:Jt.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(Us)},Y=class xe{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=xe.defaultLogLevel,this.logHandler=xe.defaultLogHandler,this.logErrorHandler=xe.defaultLogErrorHandler}static initLogHandlers(){const[t,n]=xs();this.defaultLogHandler=t,this.defaultLogErrorHandler=n,this.defaultLogger=new xe}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)}};Y.defaultLogLevel=1,Y.LOG_NONE=0,Y.LOG_ERROR=1,Y.LOG_MAJOR=2,Y.LOG_MINOR=3,Y.LOG_MICRO=4,Y.logAction=(e,t,n,s)=>{Y.logActionNoStrip(e,t,n,s)};var Ns=Y,o=Ns,et={};zt(et,{Format:()=>on,allSame:()=>rn,allToLowerCase:()=>st,allToUpperCase:()=>un,arrChooseN:()=>hn,arrDeleteValue:()=>tn,arrEquals:()=>mn,arrIntersect:()=>Zt,arrIntersectOb:()=>en,arrPopRandomElement:()=>tt,arrSubtract:()=>Ws,arrWithoutValue:()=>js,cheapRandStr:()=>Be,containsValue:()=>Hs,copy:()=>ce,createMissingPluginError:()=>He,dataSizeBytes:()=>cn,decodeBody:()=>H,encodeBody:()=>F,ensureArray:()=>$t,forInOwnNonNullProperties:()=>sn,getBackoffCoefficient:()=>dn,getGlobalObject:()=>rt,getJitterCoefficient:()=>fn,getRetryTime:()=>it,inherits:()=>Ds,inspectBody:()=>an,inspectError:()=>T,intersect:()=>Yt,isEmpty:()=>qs,isErrorInfoOrPartialErrorInfo:()=>nt,isNil:()=>W,isObject:()=>le,keysArray:()=>Oe,matchDerivedChannel:()=>pn,mixin:()=>O,parseQueryString:()=>qe,prototypicalClone:()=>Xt,randomString:()=>ln,shallowClone:()=>Bs,shallowEquals:()=>gn,throwMissingPluginError:()=>q,toBase64:()=>De,toQueryString:()=>ve,valuesArray:()=>nn,whenPromiseSettles:()=>N,withTimeoutAsync:()=>yn});function Qt(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 Qt(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 Qt(this)}static fromValues(t){const{message:n,code:s,statusCode:i}=t;if(typeof n!="string"||!W(s)&&typeof s!="number"||!W(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 Gs(e){return Math.floor(Math.random()*e.length)}function O(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 O({},e)}function $t(e){return W(e)?[]:Array.isArray(e)?e:[e]}function le(e){return Object.prototype.toString.call(e)=="[object Object]"}function qs(e){for(const t in e)return!1;return!0}function W(e){return e==null}function Bs(e){const t=new Object;for(const n in e)t[n]=e[n];return t}function Xt(e,t){class n{}n.prototype=e;const s=new n;return t&&O(s,t),s}var Ds=function(e,t){if(d.Config.inherits){d.Config.inherits(e,t);return}e.super_=t,e.prototype=Xt(t.prototype,{constructor:e})};function Hs(e,t){for(const n in e)if(e[n]==t)return!0;return!1}function Yt(e,t){return Array.isArray(t)?Zt(e,t):en(e,t)}function Zt(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 en(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 Ws(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=e.indexOf(t),s=n!=-1;return s&&e.splice(n,1),s}function js(e,t){const n=e.slice();return tn(n,t),n}function Oe(e,t){const n=[];for(const s in e)t&&!Object.prototype.hasOwnProperty.call(e,s)||n.push(s);return n}function nn(e,t){const n=[];for(const s in e)t&&!Object.prototype.hasOwnProperty.call(e,s)||n.push(e[s]);return n}function sn(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function rn(e,t){if(e.length===0)return!0;const n=e[0][t];return e.every(function(s){return s[t]===n})}var on=(e=>(e.msgpack="msgpack",e.json="json",e))(on||{});function tt(e){return e.splice(Gs(e),1)[0]}function ve(e){const t=[];if(e)for(const n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function qe(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==null?void 0:e.constructor)==null?void 0:t.name)==="ErrorInfo"||((n=e==null?void 0:e.constructor)==null?void 0:n.name)==="PartialErrorInfo"?e.toString():d.Config.inspect(e)}function an(e){return d.BufferUtils.isBuffer(e)?e.toString():typeof e=="string"?e:d.Config.inspect(e)}function cn(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 Be(){return String(Math.random()).substr(2)}var ln=async e=>{const t=await d.Config.getRandomArrayBuffer(e);return d.BufferUtils.base64Encode(t)};function hn(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||t(null,n)}).catch(n=>{t==null||t(n)})}function H(e,t,n){return n=="msgpack"?(t||q("MsgPack"),t.decode(e)):JSON.parse(String(e))}function F(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 un(e){return e.map(function(t){return t&&t.toUpperCase()})}function dn(e){return Math.min((e+2)/3,2)}function fn(){return 1-Math.random()*.2}function it(e,t){return e*dn(t)*fn()}function rt(){return typeof se<"u"?se:typeof window<"u"?window:self}function gn(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function pn(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 De(e){const t=d.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function mn(e,t){return e.length===t.length&&e.every(function(n,s){return n===t[s]})}function He(e){return new f(`${e} plugin not provided`,40019,400)}function q(e){throw He(e)}async function yn(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",Fs="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:Fs,getHost:Cn,getPort:Vs,getHttpScheme:zs,environmentFallbackHosts:Rn,getFallbackHosts:wn,getHosts:Ks,checkHost:On,objectifyOptions:$s,normaliseOptions:Xs,defaultGetHeaders:Ys,defaultPostHeaders:Zs};function Cn(e,t,n){return n?t=t==e.restHost&&e.realtimeHost||t||e.realtimeHost:t=t||e.restHost,t}function Vs(e,t){return t||e.tls?e.tlsPort:e.port}function zs(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?hn(t,n):[]}function Ks(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 Js(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 Qs(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 $s(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=X(E({},r),{plugins:E(E({},i),r.plugins)})),r}function Xs(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=Js(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=Qs(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,b]=e.connectivityCheckUrl.split("?");u=b?qe(b):{},p.indexOf("://")===-1&&(p="https://"+p),g=p}let m=e.wsConnectivityCheckUrl;return m&&m.indexOf("://")===-1&&(m="wss://"+m),X(E({},e),{realtimeHost:c,restHost:a,maxMessageSize:e.maxMessageSize||L.maxMessageSize,timeouts:h,connectivityCheckParams:u,connectivityCheckUrl:g,wsConnectivityCheckUrl:m,headers:l})}function We(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 vn={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},je={format:"json",protocolVersion:L.protocolVersion};function Ys(e,{format:t=je.format,protocolVersion:n=je.protocolVersion}={}){return{accept:vn[t],"X-Ably-Version":n.toString(),"Ably-Agent":ot(e)}}function Zs(e,{format:t=je.format,protocolVersion:n=je.protocolVersion}={}){let s;return{accept:s=vn[t],"content-type":s,"X-Ably-Version":n.toString(),"Ably-Agent":ot(e)}}var R=L;function ei(e){return Object.assign(L,e)}var ti=class Ss{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 Ss(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=ti,An=(e=>(e.Get="get",e.Delete="delete",e.Post="post",e.Put="put",e.Patch="patch",e))(An||{}),M=An,Sn=(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))(Sn||{});function ni(e){return e>=200&&e<400}var Fe=Sn,ct=Math.pow(2,17);function si(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function ii(e){return!!e.connection}function _n(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 ri=(e,t)=>{const n=d.BufferUtils,s=n.utf8Encode(e),i=n.utf8Encode(t),r=n.hmacSha256(s,i);return n.base64Encode(r)};function Tn(e){if(!e)return"";typeof e=="string"&&(e=JSON.parse(e));const t=Object.create(null),n=Oe(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 Mn(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 oi(e){return"useTokenAuth"in e&&!e.useTokenAuth}function kn(e){return e.useTokenAuth||!oi(e)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}function ai(e){return!e.key&&!e.authCallback&&!e.authUrl}var ci=0;function li(){return ci++}var hi=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,kn(t))ai(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),Mn(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 ii(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===Fe.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(n),n}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),Mn(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=O({accept:"application/json, text/plain"},n.authHeaders),u=n.authMethod&&n.authMethod.toLowerCase()==="post";let g;const m=n.authUrl.indexOf("?");m>-1&&(g=qe(n.authUrl.slice(m)),n.authUrl=n.authUrl.slice(0,m),u||(n.authParams=O(g,n.authParams)));const p=O({},n.authParams||{},c),b=y=>{var C,A;let S=(C=y.body)!=null?C: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: "+an(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 w=_.indexOf("application/json")>-1,B=_.indexOf("text/plain")>-1||_.indexOf("application/jwt")>-1;if(!w&&!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(w){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 C=ve(p).slice(1);N(this.client.http.doUri(M.Post,n.authUrl,y,C,g),(A,S)=>b(A||S))}else N(this.client.http.doUri(M.Get,n.authUrl,l||{},null,p),(y,C)=>b(y||C))};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=Tn(s.capability));const a=(c,h)=>{const l=c.keyName,u="/keys/"+l+"/requestToken",g=function(p){return r.baseUri(p)+u},m=R.defaultPostHeaders(this.client.options);n.requestHeaders&&O(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,b)=>p?h(p):h(b.error,b.body,b.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,b)=>{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(_n(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]==="{"&&!(b&&b.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 C="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()",C),h(new f(C,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 C="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()",C),h(new f(C,40170,401));return}a(p,(C,A,S)=>{if(C){o.logAction(this.logger,o.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+T(C)),h(_n(C));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=Tn(e.capability));const a=O({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=si()),g=a.timestamp,m=a.keyName+` `+h+` `+l+` `+c+` `+g+` `+u+` `;return a.mac=a.mac||ri(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 "+De(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=De(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=li();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==null||a.rejectAll(r),n):(a==null||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)}},Z=hi;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 ui(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 di(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(R.getFallbackHosts(e.options)):R.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 b=await this.doUri(e,a(p),n,s,i);return b.error&&this.platformHttp.shouldFallback(b.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}),b)};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{di(e,t,s,i,this.logger);const r=await this.platformHttp.doUri(e,t,n,s,i);return this.logger.shouldLog(o.LOG_MICRO)&&ui(r,e,t,i,this.logger),r}catch(r){return{error:new f(`Unexpected error in Http.doUri: ${T(r)}`,500,5e4)}}}},In=class{constructor(e){this.Platform=d,this.ErrorInfo=f,this.Logger=o,this.Defaults=R,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=R.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 = "+R.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new ht(this),this.auth=new Z(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 R.getHttpScheme(this.options)+e+":"+R.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)}};In.Platform=d;var En=In,fi=class be{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 F(t,n,s)}static fromResponseBody(t,n,s){return s&&(t=H(t,n,s)),Array.isArray(t)?be.fromValuesArray(t):be.fromValues(t)}static fromValues(t){return t.error=t.error&&f.fromValues(t.error),Object.assign(new be,t)}static fromLocalDevice(t){return Object.assign(new be,t)}static fromValuesArray(t){const n=t.length,s=new Array(n);for(let i=0;i<n;i++)s[i]=be.fromValues(t[i]);return s}},ue=fi;async function Pn(e,t,n,s){if(e.http.supportsAuthHeaders){const i=await e.auth.getAuthHeaders();return s(O(i,t),n)}else{const i=await e.auth.getAuthParams();return s(t,O(i,n))}}function gi(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===Fe.NoContent)return X(E({},e),{body:[],unpacked:!0});let s=e.body;if(!e.unpacked)try{s=H(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 X(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 pi(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 mi=class Ce{static async get(t,n,s,i,r,a){return Ce.do(M.Get,t,n,null,s,i,r,a??!1)}static async delete(t,n,s,i,r,a){return Ce.do(M.Delete,t,n,null,s,i,r,a)}static async post(t,n,s,i,r,a,c){return Ce.do(M.Post,t,n,s,i,r,a,c)}static async patch(t,n,s,i,r,a,c){return Ce.do(M.Patch,t,n,s,i,r,a,c)}static async put(t,n,s,i,r,a,c){return Ce.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 b;if(l.shouldLog(o.LOG_MICRO)){let C=i;if(((b=m["content-type"])==null?void 0:b.indexOf("msgpack"))>0)try{n._MsgPack||q("MsgPack"),C=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: "+C)}const y=await n.http.do(t,s,m,i,p);return y.error&&Z.isTokenErr(y.error)?(await n.auth.authorize(null,null),Pn(n,m,p,u)):{err:y.error,body:y.body,headers:y.headers,unpacked:y.unpacked,statusCode:y.statusCode}}let g=await Pn(n,r,a,u);if(c&&(g=gi(g,n._MsgPack,c)),l.shouldLog(o.LOG_MICRO)&&pi(g,t,s,a,l),h){if(g.err)throw g.err;{const m=E({},g);return delete m.err,m}}return g}},I=mi;function yi(e){const t=e.match(/^\.\/(\w+)\?(.*)$/);return t&&t[2]&&qe(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=yi(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==Fe.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 Ln(this,t,s)}},Ln=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 Ln{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}}},ie=Ri,Un=class Ne{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=H(t,n,s)),Array.isArray(t)?Ne.fromValuesArray(t):Ne.fromValues(t)}static fromValues(t){return Object.assign(new Ne,t)}static fromValuesArray(t){const n=t.length,s=new Array(n);for(let i=0;i<n;i++)s[i]=Ne.fromValues(t[i]);return s}};Un.toRequestBody=F;var Oi=Un,ut=Oi,vi=class{constructor(e){var t;this.client=e,this.admin=new Ai(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(He("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(He("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))})}},Ai=class{constructor(e){this.client=e,this.deviceRegistrations=new Si(e),this.channelSubscriptions=new _i(e)}async publish(e,t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=R.defaultPostHeaders(n.options,{format:s}),r={},a=O({recipient:e},t);O(i,n.options.headers),n.options.pushFullWait&&O(r,{fullWait:"true"});const c=F(a,n._MsgPack,s);await I.post(n,"/push/publish",c,i,r,null,!0)}},Si=class{constructor(e){this.client=e}async save(e){const t=this.client,n=ue.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=R.defaultPostHeaders(t.options,{format:s}),r={};O(i,t.options.headers),t.options.pushFullWait&&O(r,{fullWait:"true"});const a=F(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=R.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);O(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=R.defaultGetHeaders(t.options,{format:n});return O(i,t.options.headers),new ie(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=R.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);O(s,t.options.headers),t.options.pushFullWait&&O(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=R.defaultGetHeaders(t.options,{format:n});O(s,t.options.headers),t.options.pushFullWait&&O(e,{fullWait:"true"}),await I.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},_i=class _s{constructor(t){this.remove=_s.prototype.removeWhere,this.client=t}async save(t){const n=this.client,s=ut.fromValues(t),i=n.options.useBinaryProtocol?"msgpack":"json",r=R.defaultPostHeaders(n.options,{format:i}),a={};O(r,n.options.headers),n.options.pushFullWait&&O(a,{fullWait:"true"});const c=F(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=R.defaultGetHeaders(n.options,{format:s});return O(r,n.options.headers),new ie(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=R.defaultGetHeaders(n.options,{format:s});O(i,n.options.headers),n.options.pushFullWait&&O(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=R.defaultGetHeaders(n.options,{format:s});return O(r,n.options.headers),n.options.pushFullWait&&O(t,{fullWait:"true"}),new ie(n,"/push/channels",r,i,async function(a,c,h){const l=!h&&s?H(a,n._MsgPack,s):a;for(let u=0;u<l.length;u++)l[u]=String(l[u]);return l}).get(t)}},Ti=vi,xn=["message.unset","message.create","message.update","message.delete","annotation.create","annotation.delete","meta.occupancy"],Mi=new Map(xn.map((e,t)=>[e,t])),ki=new Map(xn.map((e,t)=>[t,e]));function Ii(e){return ki.get(e)}function Ei(e){return e?Mi.get(e):void 0}function Pi(e){return!e||!e.channelOptions?{channelOptions:e,plugins:{},baseEncodedPreviousPayload:void 0}:e}function Nn(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 Li(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+=cn(e.data)),t}async function Gn(e,t,n,s){const i=Ve(n),r=Nn(t,e,s??null);try{await Ae(i,r)}catch(a){o.logAction(e,o.LOG_ERROR,"Message.fromEncoded()",a.toString())}return i}async function Ui(e,t,n,s){return Promise.all(n.map(function(i){return Gn(e,t,i,s)}))}async function xi(e,t){const n=Ve(e);try{await Ae(n,t.channelOptions)}catch(s){o.logAction(t.logger,o.LOG_ERROR,"Message._fromEncoded()",s.toString())}return n}async function Ni(e,t){return Promise.all(e.map(function(n){return xi(n,t)}))}async function Gi(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?Gi(e,t):e}async function qn(e,t){return Promise.all(e.map(n=>dt(n,t)))}var qi=F;async function Ae(e,t){const n=Pi(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 Ve(e){const t=Ii(e.action)||e.action,n=Object.assign(new pt,X(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=Li(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:Ei(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}},Bi=pt,Bn=["absent","present","enter","leave","update"];function Di(e){return Bn.indexOf(e)}async function Dn(e,t,n,s){const i=ze(n),r=Nn(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 Hi(e,t,n,s){return Promise.all(n.map(function(i){return Dn(e,t,i,s)}))}async function Wi(e,t){const n=ze(e);try{await mt(n,t.channelOptions)}catch(s){o.logAction(t.logger,o.LOG_ERROR,"PresenceMessage._fromEncoded()",s.toString())}return n}async function Hn(e,t){return Promise.all(e.map(function(n){return Wi(n,t)}))}function ee(e){return Object.assign(new Ke,e)}function ze(e){const t=Bn[e.action];return Object.assign(new Ke,X(E({},e),{action:t}))}var mt=Ae;function Wn(e){return e.map(ee)}function jn(e){return e instanceof Ke?e:ee({data:e})}var Ke=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:Di(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}},ji=Ke,Fi=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=R.defaultGetHeaders(t.options,{format:n});return O(i,t.options.headers),new ie(t,this.channel.client.rest.presenceMixin.basePath(this),i,s,async(r,a,c)=>{const h=c?r:H(r,t._MsgPack,n);return Hn(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)}},Vi=Fi,zi=9;function Ki(e){return e.every(function(t){return!t.id})}var Ji=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 Vi(this),this.channelOptions=We((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=We((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=R.defaultPostHeaders(r.options,{format:c});if(O(l,a.headers),h&&Ki(s)){const m=await ln(zi);s.forEach(function(p,b){p.id=m+":"+b.toString()})}await qn(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(qi(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)}},Qi=Ji,$i=class Ts{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 Ts(t)}},Xi=$i,Fn=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=R.defaultGetHeaders(n.options,{format:s});return O(r,n.options.headers),new ie(n,this.basePath(e)+"/messages",r,i,async function(a,c,h){const l=h?a:H(a,n._MsgPack,s);return Ni(l,e)}).get(t)}static async status(e){const t=e.client.options.useBinaryProtocol?"msgpack":"json",n=R.defaultPostHeaders(e.client.options,{format:t});return(await I.get(e.client,this.basePath(e),n,{},t,!0)).body}},Yi=class{static basePath(e){return Fn.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=R.defaultGetHeaders(n.options,{format:s});return O(r,n.options.headers),new ie(n,this.basePath(e)+"/history",r,i,async(a,c,h)=>{const l=h?a:H(a,n._MsgPack,s);return Hn(l,e.channel)}).get(t)}},Vn=class{constructor(e){this.channelMixin=Fn,this.presenceMixin=Yi,this.Resource=I,this.DeviceDetails=ue,this.client=e,this.channels=new Zi(this.client),this.push=new Ti(this.client)}async stats(e){const t=R.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return O(t,this.client.options.headers),new ie(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]=Xi.fromValues(c[h]);return c}).get(e)}async time(e){const t=R.defaultGetHeaders(this.client.options);this.client.options.headers&&O(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"?R.defaultGetHeaders(this.client.options,{format:l,protocolVersion:n}):R.defaultPostHeaders(this.client.options,{format:l,protocolVersion:n});typeof i!="string"&&(i=(a=c(i))!=null?a:null),O(m,this.client.options.headers),r&&O(m,r);const p=new ie(this.client,t,m,u,async function(b,y,C){return $t(C?b:h(b))},!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=R.defaultPostHeaders(this.client.options,{format:s});this.client.options.headers&&O(i,this.client.options.headers);const r=F(t,this.client._MsgPack,s),a=await I.post(this.client,"/messages",r,i,{},null,!0),c=a.unpacked?a.body:H(a.body,this.client._MsgPack,s);return n?c[0]:c}async batchPresence(e){const t=this.client.options.useBinaryProtocol?"msgpack":"json",n=R.defaultPostHeaders(this.client.options,{format:t});this.client.options.headers&&O(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:H(i.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(kn(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=R.defaultPostHeaders(this.client.options,{format:r});this.client.options.headers&&O(a,this.client.options.headers);const c=F(i,this.client._MsgPack,r),h=await I.post(this.client,`/keys/${n}/revokeTokens`,c,a,{},null,!0);return h.unpacked?h.body:H(h.body,this.client._MsgPack,r)}},Zi=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 Qi(this.client,e,t),n}release(e){delete this.all[String(e)]}},er=class extends En{constructor(e){super(R.objectifyOptions(e,!1,"BaseRest",o.defaultLogger,{Rest:Vn}))}},zn={Rest:Vn},Kn=class extends Bi{static async fromEncoded(e,t){return Gn(o.defaultLogger,d.Crypto,e,t)}static async fromEncodedArray(e,t){return Ui(o.defaultLogger,d.Crypto,e,t)}static fromValues(e){return de(e)}static fromWireProtocol(e){return Ve(e)}static async encode(e,t){return dt(e,t)}static async decode(e,t){return Ae(e,t)}},Jn=class extends ji{static async fromEncoded(e,t){return Dn(o.defaultLogger,d.Crypto,e,t)}static async fromEncodedArray(e,t){return Hi(o.defaultLogger,d.Crypto,e,t)}static fromValues(e){return ee(e)}},fe=class $e extends er{constructor(t){var n,s;if(!$e._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(R.objectifyOptions(t,!0,"Rest",o.defaultLogger,X(E({},zn),{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=Kn,fe.PresenceMessage=Jn,fe._MsgPack=null,fe._Http=ht;var yt=fe;function tr(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 bt(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])&&bt([s],t,r)}var nr=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(W(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||W(e[0])&&W(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&&W(i)){bt([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?bt([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=>{tr(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(W(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=nr,v={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},Qn=[];Object.keys(v).forEach(function(e){Qn[v[e]]=e});var te={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},sr=Object.keys(te);te.MODE_ALL=te.PRESENCE|te.PUBLISH|te.SUBSCRIBE|te.PRESENCE_SUBSCRIBE;function $n(e){const t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}var Xn=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE"],ir=F;function rr(e,t,n,s){const i=H(e,t,s);return Ct(i,n)}function Ct(e,t){const n=e.error;n&&(e.error=f.fromValues(n));let s;e.messages&&(s=e.messages.map(a=>Ve(a)));let i;return t&&e.presence&&(i=e.presence.map(a=>t.presenceMessageFromWireProtocol(a))),Object.assign(new wt,X(E({},e),{presence:i,messages:s}))}function or(e){return Ct(e,{presenceMessageFromValues:ee,presenceMessagesFromValuesArray:Wn,presenceMessageFromWireProtocol:ze})}function V(e){return Object.assign(new wt,e)}function Rt(e,t){let n="[ProtocolMessage";e.action!==void 0&&(n+="; action="+Qn[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="+$n(ft(e.messages))),e.presence&&t&&(n+="; presence="+$n(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="+sr.filter(e.hasFlag).join(",")),e.params){let r="";sn(e.params,function(a){r.length>0&&(r+="; "),r+=a+"="+e.params[a]}),r.length>0&&(n+="; params=["+r+"]")}return n+="]",n}var wt=class{constructor(){this.hasFlag=e=>(this.flags&te[e])>0}setFlag(e){return this.flags=this.flags|te[e]}getMode(){return this.flags&&this.flags&te.MODE_ALL}encodeModesToFlags(e){e.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){const e=[];return Xn.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},Yn=wt,ar=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")}},Zn=ar,es=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;const n=e.action;this.sendAttempted=!1,this.ackRequired=n==v.MESSAGE||n==v.PRESENCE}},cr=class extends U{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new Zn(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; "+Rt(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()})}},lr=cr,hr=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},Je=hr,re={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},ur={disconnected:()=>f.fromValues({statusCode:400,code:re.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>f.fromValues({statusCode:400,code:re.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>f.fromValues({statusCode:400,code:re.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>f.fromValues({statusCode:400,code:re.CLOSING,message:"Connection closing"}),closed:()=>f.fromValues({statusCode:400,code:re.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>f.fromValues({statusCode:500,code:re.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>f.fromValues({statusCode:500,code:re.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function dr(e){return!e.statusCode||!e.code||e.statusCode>=500?!0:Object.values(re).includes(e.code)}var oe=ur,fr=V({action:v.CLOSE}),gr=V({action:v.DISCONNECT}),pr=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",oe.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||oe.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||oe.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+": "+Rt(e,this.connectionManager.realtime._RealtimePresence)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case v.HEARTBEAT:o.logActionNoStrip(this.logger,o.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case v.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case v.CLOSED:this.onClose(e);break;case v.DISCONNECTED:this.onDisconnect(e);break;case v.ACK:this.emit("ack",e.msgSerial,e.count);break;case v.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case v.SYNC:this.connectionManager.onChannelMessage(e,this);break;case v.ACTIVATE:break;case v.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 v.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(fr)}requestDisconnect(){o.logAction(this.logger,o.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(gr)}ping(e){const t={action:v.HEARTBEAT};e&&(t.id=e),this.send(V(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=pr,G;(e=>{e.WebSocket="web_socket",e.Comet="comet",e.XhrPolling="xhr_polling"})(G||(G={}));var mr=typeof se<"u"?se:typeof window<"u"?window:self,Ot=()=>{var e;return typeof d.WebStorage<"u"&&((e=d.WebStorage)==null?void 0:e.localSupported)},Se=()=>{var e;return typeof d.WebStorage<"u"&&((e=d.WebStorage)==null?void 0:e.sessionSupported)},ts=function(){},vt="ably-transport-preference";function yr(e,t,n){let s;if(e.channel!==t.channel||(s=e.action)!==v.PRESENCE&&s!==v.MESSAGE||s!==t.action)return!1;const i=s===v.PRESENCE?"presence":"messages",r=e[i].concat(t[i]);return gt(r)>n||!rn(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=R.protocolVersion,t.agent=ot(this.options),n.transportParams!==void 0&&O(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 Ms 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 Zn(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=Yt(n.transports||R.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=R.getHosts(n),this.wsHosts=R.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||R.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&&(Se()&&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(){Ms.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()),Z.isTokenErr(i.error)&&!(this.errorReason&&Z.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"&&(dr(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 lr(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 Je(a,a,null,l))})}),r.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new Je(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"&&Z.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(Se()){const t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:mr.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=oe)[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&&Z.isTokenErr(t.error)&&!(this.errorReason&&Z.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 Je(this.state.state,a.state,c,t.error||((s=(n=oe)[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 Je(this.state.state,r.state,null,t.error||((s=(n=oe)[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&&Z.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(ts),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=V({action:v.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||ts;const i=this.state;if(i.sendEvents){o.logAction(this.logger,o.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new es(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; "+Rt(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&&yr(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 es(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=Be();return yn(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||Ot()&&((n=(t=d.WebStorage)==null?void 0:t.get)==null?void 0:n.call(t,vt))}persistTransportPreference(t){var n,s;this.transportPreference=t.shortName,Ot()&&((s=(n=d.WebStorage)==null?void 0:n.set)==null||s.call(n,vt,t.shortName))}unpersistTransportPreference(){var t,n;this.transportPreference=null,Ot()&&((n=(t=d.WebStorage)==null?void 0:t.remove)==null||n.call(t,vt))}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===Fe.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||R.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 Se()&&((n=(t=d.WebStorage)==null?void 0:t.getSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var n,s;return Se()&&((s=(n=d.WebStorage)==null?void 0:n.setSession)==null?void 0:s.call(n,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,n;return Se()&&((n=(t=d.WebStorage)==null?void 0:t.removeSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}},ns=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 ns(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,ss=function(){};function vr(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"||!Xn.includes(String.prototype.toUpperCase.call(n)))return new f("Invalid channel mode: "+n,4e4,400)}}}var Ar=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=We((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=vr(t);if(i)throw i;if(this.channelOptions=We((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!=null&&t.params){const s=is(t.params),i=is(n.params);if(Object.keys(s).length!==Object.keys(i).length||!gn(i,s))return!0}return!!(t!=null&&t.modes&&(!n.modes||!mn(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 qn(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 Yn;i.action=v.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||s(null,r);break;case"detached":case"suspended":case"failed":s==null||s(r.reason||i.getError()||new f("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":s==null||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=V({action:v.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this._requestedFlags?t.encodeModesToFlags(this._requestedFlags):this.channelOptions.modes&&t.encodeModesToFlags(un(this.channelOptions.modes)),this._attachResume&&t.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(t.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(t,ss)}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=V({action:v.DETACH,channel:this.name});this.sendMessage(n,t||ss)}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=V({action:v.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=V({action:v.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===v.ATTACHED||t.action===v.MESSAGE||t.action===v.PRESENCE)&&this.setChannelSerial(t.channelSerial);let n,s=!1;switch(t.action){case v.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 v.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 v.SYNC:if(s=!0,n=this.syncChannelSerial=t.channelSerial,!t.presence)break;case v.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 v.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=>Ae(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 v.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(oe.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 is(e){return Es(e||{},["agent"])}var _t=Ar,rs=class ks extends En{constructor(t){var n,s;if(super(R.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=ks.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 _r(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(t){const n={};return t!=null&&t.WebSocketTransport&&(n[G.WebSocket]=t.WebSocketTransport),t!=null&&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()}};rs.EventEmitter=U;var Sr=rs,_r=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 Oe(this.all,!0)){const n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(const t of Oe(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=De(t.filter),i=pn(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]}},Tr=Sr;function Mr(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=Mr){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=ee(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=ee(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(nn(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 kr(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 Ir(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 Er=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) "+kr(this)));const r=jn(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=jn(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}Ir(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=ee(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=ee({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)}},Pr=Er,Lr=G.WebSocket;function Ur(e){return!!e.on}var xr=class extends ge{constructor(e,t,n){super(e,t,n),this.shortName=Lr,n.heartbeats=d.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!d.Config.WebSocket}createWebSocket(e,t){return this.uri=e+ve(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+":"+R.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)},Ur(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(ir(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(rr(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()}))}},os=xr,Nr=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==null?void 0: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||[]}},z=class jt extends Tr{constructor(t){var n;const s=jt._MsgPack;if(!s)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(R.objectifyOptions(t,!0,"Realtime",o.defaultLogger,X(E({},zn),{Crypto:(n=jt.Crypto)!=null?n:void 0,MsgPack:s,RealtimePresence:{RealtimePresence:Pr,presenceMessageFromValues:ee,presenceMessagesFromValuesArray:Wn,presenceMessageFromWireProtocol:ze},WebSocketTransport:os,MessageInteractions:Nr})))}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}};z.Utils=et,z.ConnectionManager=ns,z.ProtocolMessage=Yn,z._Crypto=null,z.Message=Kn,z.PresenceMessage=Jn,z._MsgPack=null,z._Http=ht,z._PresenceMap=Tt;var kt=z,It=Uint8Array,_e=Uint32Array,Et=Math.pow,as=new _e(8),cs=[],Te=new _e(64);function ls(e){return(e-(e|0))*Et(2,32)|0}for(var Me=2,ke=0;ke<64;){for(Pt=!0,Qe=2;Qe<=Me/2;Qe++)Me%Qe===0&&(Pt=!1);Pt&&(ke<8&&(as[ke]=ls(Et(Me,1/2))),cs[ke]=ls(Et(Me,1/3)),ke++),Me++}var Pt,Qe,Gr=!!new It(new _e([1]).buffer)[0];function Lt(e){return Gr?e>>>24|(e>>>16&255)<<8|(e&65280)<<8|e<<24:e}function K(e,t){return e>>>t|e<<32-t}function Ut(e){var t=as.slice(),n=e.length,s=n*8,i=512-(s+64)%512-1+s+65,r=new It(i/8),a=new _e(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=Te[c-15],m=Te[c-2];u=Te[c-7]+Te[c-16]+(K(g,7)^K(g,18)^g>>>3)+(K(m,17)^K(m,19)^m>>>10)}Te[c]=u|=0;for(var p=(K(l[4],6)^K(l[4],11)^K(l[4],25))+(l[4]&l[5]^~l[4]&l[6])+l[7]+u+cs[c],b=(K(l[0],2)^K(l[0],13)^K(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+b|0,l[4]=l[4]+p|0}for(c=0;c<8;c++)t[c]=t[c]+l[c]|0}return new It(new _e(t.map(function(C){return Lt(C)})).buffer)}function qr(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 Br=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==null?void 0: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=qr(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},hs=new Br,Dr=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,b,y,C){this.algorithm=p,this.keyLength=b,this.mode=y,this.key=C}}class u{static getDefaultParams(p){var b;if(!p.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof p.key=="string"?b=t.toArrayBuffer(t.base64Decode(c(p.key))):p.key instanceof ArrayBuffer?b=p.key:b=t.toArrayBuffer(p.key);var y=p.algorithm||n,C=b.byteLength*8,A=p.mode||i,S=new l(y,C,A,b);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(b){throw new f("Failed to generate random key: "+b.message,400,5e4,b)}}static getCipher(p,b){var y,C=h(p)?p:this.getDefaultParams(p);return{cipherParams:C,cipher:new g(C,(y=p.iv)!=null?y:null,b)}}}u.CipherParams=l;class g{constructor(p,b,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=b?t.toArrayBuffer(b):null}concat(p,b){const y=new ArrayBuffer(p.byteLength+b.byteLength),C=new DataView(y),A=new DataView(t.toArrayBuffer(p));for(let _=0;_<A.byteLength;_++)C.setInt8(_,A.getInt8(_));const S=new DataView(t.toArrayBuffer(b));for(let _=0;_<S.byteLength;_++)C.setInt8(A.byteLength+_,S.getInt8(_));return y}async encrypt(p){o.logAction(this.logger,o.LOG_MICRO,"CBCCipher.encrypt()","");const b=await this.getIv(),y=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),C=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:b},y,p);return this.concat(b,C)}async decrypt(p){o.logAction(this.logger,o.LOG_MICRO,"CBCCipher.decrypt()","");const b=t.toArrayBuffer(p),y=b.slice(0,r),C=b.slice(r),A=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:y},A,C)}async getIv(){if(this.iv){var p=this.iv;return this.iv=null,p}const b=await e.getRandomArrayBuffer(r);return t.toArrayBuffer(b)}}return u},us=(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))(us||{}),ne=us;function ds(){return new f("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var Ie,fs=(Ie=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==null?void 0:e.options.connectivityCheckUrl)||R.connectivityCheckUrl,s=(t=e==null?void 0:e.options.connectivityCheckParams)!=null?t:null,i=!(e!=null&&e.options.connectivityCheckUrl),r=E(E({},fs.bundledRequestImplementations),e==null?void 0:e._additionalHTTPRequestImplementations),a=r.XHRRequest,c=r.FetchRequest,h=!!(a||c);if(!h)throw ds();d.Config.xhrSupported&&a?(this.supportsAuthHeaders=!0,this.Request=async function(l,u,g,m,p){return new Promise(b=>{var y;const C=a.createRequest(u,g,m,p,ne.REQ_SEND,(y=e&&e.options.timeouts)!=null?y:null,this.logger,l);C.once("complete",(A,S,_,w,B)=>b({error:A,body:S,headers:_,unpacked:w,statusCode:B})),C.exec()})},e!=null&&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&&ni(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):ds()})}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}},Ie.methods=[M.Get,M.Delete,M.Post,M.Put,M.Patch],Ie.methodsWithoutBody=[M.Get,M.Delete],Ie.methodsWithBody=[M.Post,M.Put,M.Patch],Ie),gs=fs,pe="ablyjs-storage-test",me=typeof se<"u"?se:typeof window<"u"?window:self,Hr=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}},ps=new Hr,k=rt(),Wr=typeof EdgeRuntime=="string";typeof Window>"u"&&typeof WorkerGlobalScope>"u"&&!Wr&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function jr(){const e=k.location;return!k.WebSocket||!e||!e.origin||e.origin.indexOf("http")>-1}function Fr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}var Vr=k.navigator&&k.navigator.userAgent.toString(),zr=k.location&&k.location.href,Kr={agent:"browser",logTimestamps:!0,userAgent:Vr,currentUrl:zr,binaryType:"arraybuffer",WebSocket:k.WebSocket,fetchSupported:!!k.fetch,xhrSupported:k.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:jr(),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:Fr(),push:{platform:"browser",formFactor:"desktop",storage:ps}},ms=Kr;function Jr(e){const t=[80015,80017,80030];return e.code?Z.isTokenErr(e)?!1:t.includes(e.code)?!0:e.code>=4e4&&e.code<5e4:!1}function xt(e){return Jr(e)?[V({action:v.ERROR,error:e})]:[V({action:v.DISCONNECTED,error:e})]}var Qr=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=R.getHost(t,e.host),s=R.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:"+ve(h));let l=!1;const u=this.recvRequest=this.createRequest(r,null,h,null,this.stream?ne.REQ_RECV_STREAM:ne.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,ne.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",oe.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),ne.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?ne.REQ_RECV_STREAM:ne.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(Ct(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}},$r=Qr;function Xr(e,t){return st(Oe(t)).includes("x-ably-errorcode")}function Yr(e,t){if(Xr(e,t))return e.error&&f.fromValues(e.error)}var Zr=function(){},eo=0,ys={};function to(e,t){return e.getResponseHeader&&e.getResponseHeader(t)}function no(e){return e.getResponseHeader&&(e.getResponseHeader("transfer-encoding")||!e.getResponseHeader("content-length"))}function so(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 io=class Is extends U{constructor(t,n,s,i,r,a,c,h){super(c),s=s||{},s.rnd=Be(),this.uri=t+ve(s),this.headers=n||{},this.body=i,this.method=h?h.toUpperCase():W(i)?"GET":"POST",this.requestMode=r,this.timeouts=a,this.timedOut=!1,this.requestComplete=!1,this.id=String(++eo),ys[this.id]=this}static createRequest(t,n,s,i,r,a,c,h){const l=a||R.TIMEOUTS;return new Is(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==ne.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 w in t)r.setRequestHeader(w,t[w]);const l=(w,B,x,Ue)=>{var ye;let Bt=B+" (event type: "+w.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"+w.type+"()",Bt),this.complete(new P(Bt,x,Ue))};r.onerror=function(w){l(w,"XHR error occurred",null,400)},r.onabort=w=>{this.timedOut?l(w,"Request aborted due to request timeout expiring",null,408):l(w,"Request cancelled",null,400)},r.ontimeout=function(w){l(w,"Request timed out",null,408)};let u,g,m,p=0,b=!1;const y=()=>{if(clearTimeout(s),m=g<400,g==204){this.complete(null,null,null,null,g);return}u=this.requestMode==ne.REQ_RECV_STREAM&&m&&no(r)},C=()=>{let w;try{const x=to(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?w=JSON.parse(ye):w=ye,b=!0}else w=r.response;w.response!==void 0?(g=w.statusCode,m=g<400,t=w.headers,w=w.response):t=so(r)}catch(x){this.complete(new P("Malformed response body from server: "+x.message,null,400));return}if(m||Array.isArray(w)){this.complete(null,w,t,b,g);return}let B=Yr(w,t);B||(B=new P("Error response received from server: "+g+" body was: "+d.Config.inspect(w),null,g)),this.complete(B,w,t,b,g)};function A(){const w=r.responseText,B=w.length-1;let x,Ue;for(;p<B&&(x=w.indexOf(` `,p))>-1;)Ue=w.slice(p,x),p=x+1,S(Ue)}const S=w=>{try{w=JSON.parse(w)}catch(B){this.complete(new P("Malformed response body from server: "+B.message,null,400));return}this.emit("data",w)},_=()=>{A(),this.streamComplete=!0,d.Config.nextTick(()=>{this.complete()})};r.onreadystatechange=function(){const w=r.readyState;w<3||r.status!==0&&(g===void 0&&(g=r.status,y()),w==3&&u?A():w==4&&(u?_():C()))},r.send(c)}dispose(){const t=this.xhr;if(t){t.onreadystatechange=t.onerror=t.onabort=t.ontimeout=Zr,this.xhr=null;const n=this.timer;n&&(clearTimeout(n),this.timer=null),this.requestComplete||t.abort()}delete ys[this.id]}},bs=io,Cs=G.XhrPolling,ro=class extends $r{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)}},oo=ro,ao=["xhr_polling"],co={order:ao,bundledImplementations:{web_socket:os,xhr_polling:oo}},lo=co,ho={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[G.XhrPolling,G.WebSocket]},uo=ho;function fo(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 Ee(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 go(e,t){const n=Le(e,t);if(n===0)return;const s=new ArrayBuffer(n),i=new DataView(s);return Pe(e,i,0,t),s}var Gt=65536*65536,ws=1/Gt;function po(e,t){return t=t||0,e.getInt32(t)*Gt+e.getUint32(t+4)}function mo(e,t){return t=t||0,e.getUint32(t)*Gt+e.getUint32(t+4)}function yo(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=mo(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=po(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 Pe(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),Ee(t,n+1,e),1+r;if(r<256)return t.setUint8(n,217),t.setUint8(n+1,r),Ee(t,n+2,e),2+r;if(r<65536)return t.setUint8(n,218),t.setUint16(n+1,r),Ee(t,n+3,e),3+r;if(r<4294967296)return t.setUint8(n,219),t.setUint32(n+1,r),Ee(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),yo(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 Pe(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+=Pe(e[l],t,n+a,s);else if(c)for(let l=0;l<r;l++){const u=c[l];a+=Pe(u,t,n+a),a+=Pe(e[u],t,n+a,s)}return a}if(i==="function")return 0;throw new Error("Unknown type "+i)}function Le(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 Le(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+=Le(e[r],t)}else{const r=Os(e,t);s=r.length;for(let a=0;a<s;a++){const c=r[a];i+=Le(c)+Le(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:go,decode:Ro,inspect:fo,utf8Write:Ee,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 vo(e){const t={};return e.forEach((n,s)=>{t[s]=n}),t}async function Ao(e,t,n,s,i,r){const a=new Headers(s||{}),c=e?e.toUpperCase():W(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:R.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",Be());const b=n+"?"+p,y=await rt().fetch(b,g);if(clearTimeout(l),y.status==204)return{error:null,statusCode:y.status};const C=y.headers.get("Content-Type");let A;C&&C.indexOf("application/x-msgpack")>-1?A=await y.arrayBuffer():C&&C.indexOf("application/json")>-1?A=await y.json():A=await y.text();const S=!!C&&C.indexOf("application/x-msgpack")===-1,_=vo(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 So={XHRRequest:bs,FetchRequest:Ao},vs=Dr(ms,hs);d.Crypto=vs,d.BufferUtils=hs,d.Http=gs,d.Config=ms,d.Transports=lo,d.WebStorage=ps;for(const e of[yt,kt])e.Crypto=vs,e._MsgPack=qt;gs.bundledRequestImplementations=So,o.initLogHandlers(),d.Defaults=ei(uo),d.Config.agent&&(d.Defaults.agent+=" "+d.Config.agent);var _o={ErrorInfo:f,Rest:yt,Realtime:kt,msgpack:qt};if(typeof Q.exports=="object"&&typeof J=="object"){var To=(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};Q.exports=To(Q.exports,J)}return Q.exports})})(As);var Go=As.exports;function Qo(){const[D]=Io("user");return D?Mo.jsx(qo,{userSignalsChannel:D.userSignalsChannel},D.id):null}function qo({userSignalsChannel:D}){const[Re]=Eo(Bo),J=Po();function Q(){J.refetchQueries({include:[Uo]})}const ae=()=>{J.refetchQueries({include:[xo]})},Xe=()=>{J.refetchQueries({include:[No]})};return ko.useEffect(()=>{const we=new Go.Realtime({authCallback:(Ye,$)=>{Re().then(({data:j})=>{if(!(j!=null&&j.generateAblyTokenRequest.tokenRequest)){$("No data returned",null);return}$(null,JSON.parse(j.generateAblyTokenRequest.tokenRequest))}).catch(j=>{$("Error",null)})},realtimeRequestTimeout:25e3});return we.connection.on("connected",()=>{we.channels.get(D).subscribe($=>{$.name==="refetch_root_data"&&Q(),$.name==="refetch_balance_transaction_reports"&&ae(),$.name==="refetch_hris_integration"&&Xe()})}),()=>{we.close()}},[]),null}const Bo=Lo` mutation GenerateAblyTokenRequest { generateAblyTokenRequest { tokenRequest } } `;export{Qo as default}; //# sourceMappingURL=WSConnection-y77NOdLE.js.map