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