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