@v-tilt/browser 1.3.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/all-external-dependencies.js.map +1 -1
- package/dist/array.full.js +1 -1
- package/dist/array.full.js.map +1 -1
- package/dist/array.js +1 -1
- package/dist/array.js.map +1 -1
- package/dist/array.no-external.js +1 -1
- package/dist/array.no-external.js.map +1 -1
- package/dist/chat.js +2 -0
- package/dist/chat.js.map +1 -0
- package/dist/entrypoints/chat.d.ts +22 -0
- package/dist/extensions/chat/chat-wrapper.d.ts +172 -0
- package/dist/extensions/chat/chat.d.ts +87 -0
- package/dist/extensions/chat/index.d.ts +10 -0
- package/dist/extensions/chat/types.d.ts +156 -0
- package/dist/external-scripts-loader.js +1 -1
- package/dist/external-scripts-loader.js.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/module.d.ts +279 -2
- package/dist/module.js +1 -1
- package/dist/module.js.map +1 -1
- package/dist/module.no-external.d.ts +279 -2
- package/dist/module.no-external.js +1 -1
- package/dist/module.no-external.js.map +1 -1
- package/dist/recorder.js.map +1 -1
- package/dist/types.d.ts +27 -0
- package/dist/utils/globals.d.ts +111 -1
- package/dist/vtilt.d.ts +11 -1
- package/dist/web-vitals.js.map +1 -1
- package/lib/entrypoints/chat.d.ts +22 -0
- package/lib/entrypoints/chat.js +32 -0
- package/lib/entrypoints/external-scripts-loader.js +1 -1
- package/lib/extensions/chat/chat-wrapper.d.ts +172 -0
- package/lib/extensions/chat/chat-wrapper.js +497 -0
- package/lib/extensions/chat/chat.d.ts +87 -0
- package/lib/extensions/chat/chat.js +1004 -0
- package/lib/extensions/chat/index.d.ts +10 -0
- package/lib/extensions/chat/index.js +27 -0
- package/lib/extensions/chat/types.d.ts +156 -0
- package/lib/extensions/chat/types.js +22 -0
- package/lib/types.d.ts +27 -0
- package/lib/utils/globals.d.ts +111 -1
- package/lib/vtilt.d.ts +11 -1
- package/lib/vtilt.js +42 -1
- package/package.json +2 -1
package/dist/chat.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
!function(t){"use strict";var e="undefined"!=typeof window?window:void 0,n="undefined"!=typeof globalThis?globalThis:e,i=null==n?void 0:n.navigator,r=null==n?void 0:n.document;null==n||n.location,null==n||n.fetch,(null==n?void 0:n.XMLHttpRequest)&&"withCredentials"in new n.XMLHttpRequest&&n.XMLHttpRequest,null==n||n.AbortController,null==i||i.userAgent;var s=null!=e?e:{};function a(t,e,n,i,r,s,a){try{var o=t[s](a),h=o.value}catch(t){return void n(t)}o.done?e(h):Promise.resolve(h).then(i,r)}function o(t){return function(){var e=this,n=arguments;return new Promise(function(i,r){var s=t.apply(e,n);function o(t){a(s,i,r,o,h,"next",t)}function h(t){a(s,i,r,o,h,"throw",t)}o(void 0)})}}function h(){return h=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},h.apply(null,arguments)}var c="$chat_started",u="$chat_message_sent",l="$chat_message_received",d="$chat_widget_opened",f="$chat_widget_closed",v="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function p(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var g,y={exports:{}};g=()=>{var t,e={},n={exports:e},i=Object.defineProperty,r=Object.defineProperties,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyDescriptors,h=Object.getOwnPropertyNames,c=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable,d=(t,e,n)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,f=(t,e)=>{for(var n in e||(e={}))u.call(e,n)&&d(t,n,e[n]);if(c)for(var n of c(e))l.call(e,n)&&d(t,n,e[n]);return t},p=(t,e)=>r(t,a(e)),g=(t,e)=>{for(var n in e)i(t,n,{get:e[n],enumerable:!0})},y=function(t,e){this[0]=t,this[1]=e},m={};g(m,{ErrorInfo:()=>x,Realtime:()=>Pi,Rest:()=>Zn,default:()=>jr,makeProtocolMessageFromDeserialized:()=>Wn,msgpack:()=>xr}),n.exports=(t=m,((t,e,n,r)=>{if(e&&"object"==typeof e||"function"==typeof e){var a=function(a){u.call(t,a)||a===n||i(t,a,{get:()=>e[a],enumerable:!(r=s(e,a))||r.enumerable})};for(var o of h(e))a(o)}return t})(i({},"__esModule",{value:!0}),t));var w=class{},b=void 0!==v?v:"undefined"!=typeof window?window:self;function C(t,e){return(""+t).padStart(e?3:2,"0")}function k(t){return w.Config.logTimestamps?function(e){var n=new Date;t(C(n.getHours())+":"+C(n.getMinutes())+":"+C(n.getSeconds())+"."+C(n.getMilliseconds(),1)+" "+e)}:function(e){t(e)}}var T=class t{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)=>{void 0!==t&&(this.logLevel=t),void 0!==e&&(this.logHandler=this.logErrorHandler=e)},this.logLevel=t.defaultLogLevel,this.logHandler=t.defaultLogHandler,this.logErrorHandler=t.defaultLogErrorHandler}static initLogHandlers(){var e,n,i,[r,s]=("function"==typeof(null==(e=null==b?void 0:b.console)?void 0:e.log)?(n=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log.apply(console,e)},i=console.warn?function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.warn.apply(console,e)}:n):n=i=function(){},[n,i].map(k));this.defaultLogHandler=r,this.defaultLogErrorHandler=s,this.defaultLogger=new t}static logActionNoStrip(t,e,n,i){t.logAction(e,n,i)}logAction(t,e,n){this.shouldLog(t)&&(1===t?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+"`’s `"+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)}};T.defaultLogLevel=1,T.LOG_NONE=0,T.LOG_ERROR=1,T.LOG_MAJOR=2,T.LOG_MINOR=3,T.LOG_MICRO=4,T.logAction=(t,e,n,i)=>{T.logActionNoStrip(t,e,n,i)};var S=T,A={};function E(t){var e="["+t.constructor.name;return t.message&&(e+=": "+t.message),t.statusCode&&(e+="; statusCode="+t.statusCode),t.code&&(e+="; code="+t.code),t.cause&&(e+="; cause="+et(t.cause)),!t.href||t.message&&t.message.indexOf("help.ably.io")>-1||(e+="; see "+t.href+" "),e+="]"}g(A,{Format:()=>G,allSame:()=>K,allToLowerCase:()=>ut,allToUpperCase:()=>lt,arrChooseN:()=>at,arrDeleteValue:()=>V,arrEquals:()=>wt,arrIntersect:()=>W,arrIntersectOb:()=>H,arrPopRandomElement:()=>Q,arrWithoutValue:()=>z,cheapRandStr:()=>rt,containsValue:()=>q,copy:()=>P,createMissingPluginError:()=>bt,dataSizeBytes:()=>it,decodeBody:()=>ht,encodeBody:()=>ct,ensureArray:()=>O,forInOwnNonNullProperties:()=>J,getBackoffCoefficient:()=>dt,getGlobalObject:()=>pt,getJitterCoefficient:()=>ft,getRetryTime:()=>vt,inherits:()=>D,inspectBody:()=>nt,inspectError:()=>et,intersect:()=>B,isEmpty:()=>j,isErrorInfoOrPartialErrorInfo:()=>tt,isNil:()=>_,isObject:()=>I,keysArray:()=>L,listenerToAsyncIterator:()=>St,matchDerivedChannel:()=>yt,mixin:()=>R,parseQueryString:()=>Z,prototypicalClone:()=>N,randomString:()=>st,shallowClone:()=>U,shallowEquals:()=>gt,stringifyValues:()=>Y,throwMissingPluginError:()=>Ct,toBase64:()=>mt,toQueryString:()=>X,valuesArray:()=>F,whenPromiseSettles:()=>ot,withTimeoutAsync:()=>kt});var x=class t extends Error{constructor(e,n,i,r){super(e),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,t.prototype),this.code=n,this.statusCode=i,this.cause=r}toString(){return E(this)}static fromValues(e){var{message:n,code:i,statusCode:r}=e;if("string"!=typeof n||"number"!=typeof i||"number"!=typeof r)throw new Error("ErrorInfo.fromValues(): invalid values: "+w.Config.inspect(e));var s=Object.assign(new t(n,i,r),e);return s.code&&!s.href&&(s.href="https://help.ably.io/error/"+s.code),s}},M=class t extends Error{constructor(e,n,i,r){super(e),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,t.prototype),this.code=n,this.statusCode=i,this.cause=r}toString(){return E(this)}static fromValues(e){var{message:n,code:i,statusCode:r}=e;if("string"!=typeof n||!_(i)&&"number"!=typeof i||!_(r)&&"number"!=typeof r)throw new Error("PartialErrorInfo.fromValues(): invalid values: "+w.Config.inspect(e));var s=Object.assign(new t(n,i,r),e);return s.code&&!s.href&&(s.href="https://help.ably.io/error/"+s.code),s}};function R(t){for(var e=0;e<(arguments.length<=1?0:arguments.length-1);e++){var n=e+1<1||arguments.length<=e+1?void 0:arguments[e+1];if(!n)break;for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}function P(t){return R({},t)}function O(t){return _(t)?[]:Array.isArray(t)?t:[t]}function I(t){return"[object Object]"==Object.prototype.toString.call(t)}function j(t){for(var e in t)return!1;return!0}function _(t){return null==t}function U(t){var e=new Object;for(var n in t)e[n]=t[n];return e}function N(t,e){class n{}n.prototype=t;var i=new n;return e&&R(i,e),i}var D=function(t,e){w.Config.inherits?w.Config.inherits(t,e):(t.super_=e,t.prototype=N(e.prototype,{constructor:t}))};function q(t,e){for(var n in t)if(t[n]==e)return!0;return!1}function B(t,e){return Array.isArray(e)?W(t,e):H(t,e)}function W(t,e){for(var n=[],i=0;i<t.length;i++){var r=t[i];-1!=e.indexOf(r)&&n.push(r)}return n}function H(t,e){for(var n=[],i=0;i<t.length;i++){var r=t[i];r in e&&n.push(r)}return n}function V(t,e){var n=t.indexOf(e),i=-1!=n;return i&&t.splice(n,1),i}function z(t,e){var n=t.slice();return V(n,e),n}function L(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(i);return n}function F(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(t[i]);return n}function J(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&t[n]&&e(n)}function K(t,e){if(0===t.length)return!0;var n=t[0][e];return t.every(function(t){return t[e]===n})}var G=(t=>(t.msgpack="msgpack",t.json="json",t))(G||{});function Q(t){return t.splice((e=t,Math.floor(Math.random()*e.length)),1)[0];var e}function X(t){var e=[];if(t)for(var n in t)e.push(encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e.length?"?"+e.join("&"):""}function Y(t){return Object.fromEntries(Object.entries(t).map(t=>{var[e,n]=t;return[e,String(n)]}))}function Z(t){for(var e,n=/([^?&=]+)=?([^&]*)/g,i={};e=n.exec(t);)i[decodeURIComponent(e[1])]=decodeURIComponent(e[2]);return i}function tt(t){return"object"==typeof t&&null!==t&&(t instanceof x||t instanceof M)}function et(t){var e,n;return t instanceof Error||"ErrorInfo"===(null==(e=null==t?void 0:t.constructor)?void 0:e.name)||"PartialErrorInfo"===(null==(n=null==t?void 0:t.constructor)?void 0:n.name)?t.toString():w.Config.inspect(t)}function nt(t){return w.BufferUtils.isBuffer(t)?t.toString():"string"==typeof t?t:w.Config.inspect(t)}function it(t){if(w.BufferUtils.isBuffer(t))return w.BufferUtils.byteLength(t);if("string"==typeof t)return w.Config.stringByteSize(t);if("number"==typeof t)return 8;if("boolean"==typeof t)return 1;throw new Error("Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: "+typeof t)}function rt(){return String(Math.random()).substr(2)}var st=function(){var t=o(function*(t){var e=yield w.Config.getRandomArrayBuffer(t);return w.BufferUtils.base64Encode(e)});return function(e){return t.apply(this,arguments)}}();function at(t,e){for(var n=Math.min(e,t.length),i=t.slice(),r=[],s=0;s<n;s++)r.push(Q(i));return r}function ot(t,e){t.then(t=>{null==e||e(null,t)}).catch(t=>{null==e||e(t)})}function ht(t,e,n){return"msgpack"==n?(e||Ct("MsgPack"),e.decode(t)):JSON.parse(String(t))}function ct(t,e,n){return"msgpack"==n?(e||Ct("MsgPack"),e.encode(t,!0)):JSON.stringify(t)}function ut(t){return t.map(function(t){return t&&t.toLowerCase()})}function lt(t){return t.map(function(t){return t&&t.toUpperCase()})}function dt(t){return Math.min((t+2)/3,2)}function ft(){return 1-.2*Math.random()}function vt(t,e){return t*dt(e)*ft()}function pt(){return void 0!==v?v:"undefined"!=typeof window?window:self}function gt(t,e){return Object.keys(t).every(n=>t[n]===e[n])&&Object.keys(e).every(n=>e[n]===t[n])}function yt(t){var e=t.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!e||!e.length||e.length<5)throw new x("regex match failed",400,40010);if(e[2])throw new x("cannot use a derived option with a "+e[2]+" channel",400,40010);return{qualifierParam:e[3]||"",channelName:e[4]}}function mt(t){var e=w.BufferUtils,n=e.utf8Encode(t);return e.base64Encode(n)}function wt(t,e){return t.length===e.length&&t.every(function(t,n){return t===e[n]})}function bt(t){return new x(t+" plugin not provided",40019,400)}function Ct(t){throw bt(t)}function kt(t,e,n){return Tt.apply(this,arguments)}function Tt(){return(Tt=o(function*(t,e,n){void 0===e&&(e=5e3),void 0===n&&(n="Timeout expired");var i=new x(n,5e4,500);return Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(i),e))])})).apply(this,arguments)}function St(t){return n=(t,i,r,s)=>{try{var a=e[t](i),o=(i=a.value)instanceof y,h=a.done;Promise.resolve(o?i[0]:i).then(e=>o?n("return"===t?t:"next",i[1]?{done:e.done,value:e.value}:e,r,s):r({value:e,done:h})).catch(t=>n("throw",t,r,s))}catch(t){s(t)}},i=t=>r[t]=e=>new Promise((i,r)=>n(t,e,i,r)),r={},e=(e=function*(){var e=[],n=null,i=t(t=>{if(n){var i=n;n=null,i(t)}else e.push(t)});try{for(;;)if(e.length>0)yield e.shift();else{if(n)throw new x("Concurrent next() calls are not supported",4e4,400);var r=yield new y(new Promise(t=>{n=t}));yield r}}finally{i()}}).apply(this,null),r[Symbol.asyncIterator]=()=>r,i("next"),i("throw"),i("return"),r;var e,n,i,r}var At="2.17.0",Et={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:At,protocolVersion:5,agent:"ably-js/"+At,getPort:function(t,e){return e||t.tls?t.tlsPort:t.port},getHttpScheme:function(t){return t.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:Mt,getEndpointFallbackHosts:Rt,getFallbackHosts:Ot,getHosts:function(t){return[t.primaryDomain].concat(Ot(t))},checkHost:It,objectifyOptions:function(t,e,n,i,r){if(void 0===t){var s=e?n+" must be initialized with either a client options object, an Ably API key, or an Ably Token":n+" must be initialized with a client options object";throw S.logAction(i,S.LOG_ERROR,n+"()",s),new Error(s)}var a;if("string"==typeof t)if(-1==t.indexOf(":")){if(!e){var o=n+" cannot be initialized with just an Ably Token; you must provide a client options object with a `plugins` property. (Set this Ably Token as the object’s `token` property.)";throw S.logAction(i,S.LOG_ERROR,n+"()",o),new Error(o)}a={token:t}}else{if(!e){var h=n+" cannot be initialized with just an Ably API key; you must provide a client options object with a `plugins` property. (Set this Ably API key as the object’s `key` property.)";throw S.logAction(i,S.LOG_ERROR,n+"()",h),new Error(h)}a={key:t}}else a=t;return r&&(a=p(f({},a),{plugins:f(f({},r),a.plugins)})),a},normaliseOptions:function(t,e,n){var i=null!=n?n:S.defaultLogger;t.environment&&i.deprecated("The `environment` client option","Use the `endpoint` client option instead."),t.restHost&&i.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),t.realtimeHost&&i.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),function(t){if(t.endpoint&&(t.environment||t.restHost||t.realtimeHost))throw new x("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(t.environment&&(t.restHost||t.realtimeHost))throw new x("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}(t),"function"==typeof t.recover&&!0===t.closeOnUnload&&(S.logAction(i,S.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),t.recover=void 0),"closeOnUnload"in t||(t.closeOnUnload=!t.recover),"queueMessages"in t||(t.queueMessages=!0);var r=t.endpoint||Et.ENDPOINT;t.fallbackHosts||t.restHost||t.realtimeHost||t.port||t.tlsPort||(t.fallbackHosts=Rt(t.environment||r));var s=t.environment&&t.environment+".realtime.ably.net",a=t.restHost||t.realtimeHost||s||Mt(r);(t.fallbackHosts||[]).concat(a).forEach(It),t.port=t.port||Et.PORT,t.tlsPort=t.tlsPort||Et.TLS_PORT,"tls"in t||(t.tls=!0);var o=function(t){var e={};for(var n in Et.TIMEOUTS)e[n]=t[n]||Et.TIMEOUTS[n];return e}(t);t.useBinaryProtocol=!!e&&("useBinaryProtocol"in t?w.Config.supportsBinary&&t.useBinaryProtocol:w.Config.preferBinary);var h={};t.clientId&&(h["X-Ably-ClientId"]=w.BufferUtils.base64Encode(w.BufferUtils.utf8Encode(t.clientId))),"idempotentRestPublishing"in t||(t.idempotentRestPublishing=!0);var c=null,u=t.connectivityCheckUrl;if(t.connectivityCheckUrl){var[l,d]=t.connectivityCheckUrl.split("?");c=d?Z(d):{},-1===l.indexOf("://")&&(l="https://"+l),u=l}var v=t.wsConnectivityCheckUrl;return v&&-1===v.indexOf("://")&&(v="wss://"+v),p(f({},t),{primaryDomain:a,maxMessageSize:t.maxMessageSize||Et.maxMessageSize,timeouts:o,connectivityCheckParams:c,connectivityCheckUrl:u,wsConnectivityCheckUrl:v,headers:h})},defaultGetHeaders:function(t,e){var{format:n,protocolVersion:i=Nt.protocolVersion}=void 0===e?{}:e;return{accept:Ut[null!=n?n:t.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":i.toString(),"Ably-Agent":jt(t)}},defaultPostHeaders:function(t,e){var{format:n,protocolVersion:i=Nt.protocolVersion}=void 0===e?{}:e,r=Ut[null!=n?n:t.useBinaryProtocol?"msgpack":"json"];return{accept:r,"content-type":r,"X-Ably-Version":i.toString(),"Ably-Agent":jt(t)}}};function xt(t){return t.includes(".")||t.includes("::")||"localhost"===t}function Mt(t){return xt(t)?t:t.startsWith("nonprod:")?t.replace("nonprod:","")+".realtime.ably-nonprod.net":t+".realtime.ably.net"}function Rt(t){return xt(t)?[]:t.startsWith("nonprod:")?Pt(t.replace("nonprod:",""),"ably-realtime-nonprod.com"):Pt(t,"ably-realtime.com")}function Pt(t,e){return["a","b","c","d","e"].map(n=>t+"."+n+".fallback."+e)}function Ot(t){var e=t.fallbackHosts,n=void 0!==t.httpMaxRetryCount?t.httpMaxRetryCount:Et.httpMaxRetryCount;return e?at(e,n):[]}function It(t){if("string"!=typeof t)throw new x("host must be a string; was a "+typeof t,4e4,400);if(!t.length)throw new x("host must not be zero-length",4e4,400)}function jt(t){var e=Et.agent;if(t.agents)for(var n in t.agents)e+=" "+n+"/"+t.agents[n];return e}function _t(t,e,n){var i=n||{};if(i.cipher){t||Ct("Crypto");var r=t.getCipher(i.cipher,e);i.cipher=r.cipherParams,i.channelCipher=r.cipher}else"cipher"in i&&(i.cipher=void 0,i.channelCipher=null);return i}var Ut={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},Nt={protocolVersion:Et.protocolVersion},Dt=Et,qt=class t{constructor(t,e){this.logger=t,this.members=e||[]}call(t,e){for(var n of this.members)if(n)try{n(t,e)}catch(t){S.logAction(this.logger,S.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+t+"; stack = "+t.stack)}}push(){this.members.push(...arguments)}createPromise(){return new Promise((t,e)=>{this.push((n,i)=>{n?e(n):t(i)})})}resolveAll(t){this.call(null,t)}rejectAll(t){this.call(t)}static create(e,n){var i=new t(e,n);return Object.assign((t,e)=>i.call(t,e),{push:t=>i.push(t),createPromise:()=>i.createPromise(),resolveAll:t=>i.resolveAll(t),rejectAll:t=>i.rejectAll(t)})}},Bt=(t=>(t.Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t))(Bt||{}),Wt=Bt,Ht=(t=>(t[t.Success=200]="Success",t[t.NoContent=204]="NoContent",t[t.BadRequest=400]="BadRequest",t[t.Unauthorized=401]="Unauthorized",t[t.Forbidden=403]="Forbidden",t[t.RequestTimeout=408]="RequestTimeout",t[t.InternalServerError=500]="InternalServerError",t))(Ht||{}),Vt=Ht,zt=Math.pow(2,17);function Lt(t){return tt(t)?(t.code||(403===t.statusCode?t.code=40300:(t.code=40170,t.statusCode=401)),t):new x(et(t),t.code||40170,t.statusCode||401)}function Ft(t){if(!t)return"";"string"==typeof t&&(t=JSON.parse(t));var e=Object.create(null),n=L(t,!0);if(!n)return"";n.sort();for(var i=0;i<n.length;i++)e[n[i]]=t[n[i]].sort();return JSON.stringify(e)}function Jt(t,e){if(t.authCallback)S.logAction(e,S.LOG_MINOR,"Auth()","using token auth with authCallback");else if(t.authUrl)S.logAction(e,S.LOG_MINOR,"Auth()","using token auth with authUrl");else if(t.key)S.logAction(e,S.LOG_MINOR,"Auth()","using token auth with client-side signing");else{if(!t.tokenDetails){var n="authOptions must include valid authentication parameters";throw S.logAction(e,S.LOG_ERROR,"Auth()",n),new Error(n)}S.logAction(e,S.LOG_MINOR,"Auth()","using token auth with supplied token only")}}function $t(t){return t.useTokenAuth||!function(t){return"useTokenAuth"in t&&!t.useTokenAuth}(t)&&(t.authCallback||t.authUrl||t.token||t.tokenDetails)}var Kt=0,Gt=class{constructor(t,e){if(this.authOptions={},this.client=t,this.tokenParams=e.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,$t(e))(function(t){return!t.key&&!t.authCallback&&!t.authUrl})(e)&&S.logAction(this.logger,S.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.t(e.defaultTokenParams,e),Jt(this.authOptions,this.logger);else{if(!e.key){var n="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw S.logAction(this.logger,S.LOG_ERROR,"Auth()",n),new x(n,40160,401)}S.logAction(this.logger,S.LOG_MINOR,"Auth()","anonymous, using basic auth"),this.i(e)}}get logger(){return this.client.logger}authorize(t,e){var n=this;return o(function*(){if(e&&e.key&&n.authOptions.key!==e.key)throw new x("Unable to update auth options with incompatible key",40102,401);try{var i=yield n.o(null!=t?t:null,null!=e?e:null);return n.client.connection?new Promise((t,e)=>{n.client.connection.connectionManager.onAuthUpdated(i,(n,i)=>n?e(n):t(i))}):i}catch(t){throw n.client.connection&&t.statusCode===Vt.Forbidden&&n.client.connection.connectionManager.actOnErrorFromAuthorize(t),t}})()}o(t,e){var n=this;return o(function*(){n.tokenDetails=null,n.t(t,e),Jt(n.authOptions,n.logger);try{return n.h(!0)}finally{delete n.tokenParams.timestamp,delete n.authOptions.queryTime}})()}requestToken(t,e){var n=this;return o(function*(){var i,r=e||n.authOptions,s=t||P(n.tokenParams),a=n.client;if(r.authCallback)S.logAction(n.logger,S.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),i=r.authCallback;else if(r.authUrl)S.logAction(n.logger,S.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),i=(t,e)=>{var i,s=R({accept:"application/json, text/plain"},r.authHeaders),a=r.authMethod&&"post"===r.authMethod.toLowerCase(),o=r.authUrl.indexOf("?");o>-1&&(i=Z(r.authUrl.slice(o)),r.authUrl=r.authUrl.slice(0,o),a||(r.authParams=R(i,r.authParams)));var h=R({},r.authParams||{},t),c=t=>{var i,r,s=null!=(i=t.body)?i:null,a=null;if(t.error)S.logAction(n.logger,S.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+et(t.error));else{var o=null!=(r=t.headers["content-type"])?r:null;a=Array.isArray(o)?o.join(", "):o,S.logAction(n.logger,S.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+a+"; body: "+nt(s))}if(t.error)e(t.error,null);else if(t.unpacked)e(null,s);else if(w.BufferUtils.isBuffer(s)&&(s=s.toString()),a){var h=a.indexOf("application/json")>-1,c=a.indexOf("text/plain")>-1||a.indexOf("application/jwt")>-1;if(h||c){if(h){if(s.length>zt)return void e(new x("authUrl response exceeded max permitted length",40170,401),null);try{s=JSON.parse(s)}catch(t){return void e(new x("Unexpected error processing authURL response; err = "+t.message,40170,401),null)}}e(null,s,a)}else e(new x("authUrl responded with unacceptable content-type "+a+", should be either text/plain, application/jwt or application/json",40170,401),null)}else e(new x("authUrl response is missing a content-type header",40170,401),null)};if(S.logAction(n.logger,S.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+r.authUrl+"; Params: "+JSON.stringify(h)+"; method: "+(a?"POST":"GET")),a){var u=s||{};u["content-type"]="application/x-www-form-urlencoded";var l=X(h).slice(1);ot(n.client.http.doUri(Wt.Post,r.authUrl,u,l,i),(t,e)=>c(t||e))}else ot(n.client.http.doUri(Wt.Get,r.authUrl,s||{},null,h),(t,e)=>c(t||e))};else{if(!r.key)throw S.logAction(n.logger,S.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new x("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403);S.logAction(n.logger,S.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),i=(t,e)=>{ot(n.createTokenRequest(t,r),(t,n)=>e(t,null!=n?n:null))}}return"capability"in s&&(s.capability=Ft(s.capability)),new Promise((t,e)=>{var o=!1,h=n.client.options.timeouts.realtimeRequestTimeout,c=setTimeout(()=>{o=!0;var t="Token request callback timed out after "+h/1e3+" seconds";S.logAction(n.logger,S.LOG_ERROR,"Auth.requestToken()",t),e(new x(t,40170,401))},h);i(s,(i,s,h)=>{if(!o){if(clearTimeout(c),i)return S.logAction(n.logger,S.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+et(i)),void e(Lt(i));if("string"!=typeof s){if("object"!=typeof s||null===s){var u="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof s;return S.logAction(n.logger,S.LOG_ERROR,"Auth.requestToken()",u),void e(new x(u,40170,401))}var l=JSON.stringify(s).length;if(l>zt&&!r.suppressMaxLengthCheck)e(new x("Token request/details object exceeded max permitted stringified size (was "+l+" bytes)",40170,401));else if("issued"in s)t(s);else{if(!("keyName"in s)){var d="Expected token request callback to call back with a token string, token request object, or token details object";return S.logAction(n.logger,S.LOG_ERROR,"Auth.requestToken()",d),void e(new x(d,40170,401))}var f,v,p,g;v=(i,r,s)=>{if(i)return S.logAction(n.logger,S.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+et(i)),void e(Lt(i));s||(r=JSON.parse(r)),S.logAction(n.logger,S.LOG_MINOR,"Auth.getToken()","token received"),t(r)},p="/keys/"+(f=s).keyName+"/requestToken",g=Dt.defaultPostHeaders(n.client.options,{format:"json"}),r.requestHeaders&&R(g,r.requestHeaders),S.logAction(n.logger,S.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+p+"; Token params: "+JSON.stringify(f)),ot(n.client.http.do(Wt.Post,function(t){return a.baseUri(t)+p},g,JSON.stringify(f),null),(t,e)=>t?v(t):v(e.error,e.body,e.unpacked))}}else 0===s.length?e(new x("Token string is empty",40170,401)):s.length>zt?e(new x("Token string exceeded max permitted length (was "+s.length+" bytes)",40170,401)):"undefined"===s||"null"===s?e(new x("Token string was literal null/undefined",40170,401)):"{"!==s[0]||h&&h.indexOf("application/jwt")>-1?t({token:s}):e(new x("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401))}})})})()}createTokenRequest(t,e){var n=this;return o(function*(){e=e||n.authOptions,t=t||P(n.tokenParams);var i=e.key;if(!i)throw new x("No key specified",40101,403);var r=i.split(":"),s=r[0],a=r[1];if(!a)throw new x("Invalid key specified",40101,403);if(""===t.clientId)throw new x("clientId can’t be an empty string",40012,400);"capability"in t&&(t.capability=Ft(t.capability));var o=R({keyName:s},t),h=t.clientId||"",c=t.ttl||"",u=t.capability||"";o.timestamp||(o.timestamp=yield n.u(e&&e.queryTime));var l=o.nonce||(o.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),d=o.timestamp,f=o.keyName+"\n"+c+"\n"+u+"\n"+h+"\n"+d+"\n"+l+"\n";return o.mac=o.mac||((t,e)=>{var n=w.BufferUtils,i=n.utf8Encode(t),r=n.utf8Encode(e),s=n.hmacSha256(i,r);return n.base64Encode(s)})(f,a),S.logAction(n.logger,S.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),o})()}getAuthParams(){var t=this;return o(function*(){if("basic"==t.method)return{key:t.key};var e=yield t.h(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}})()}getAuthHeaders(){var t=this;return o(function*(){if("basic"==t.method)return{authorization:"Basic "+t.basicKey};var e=yield t.h(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+mt(e.token)}})()}i(t){this.method="basic",this.key=t.key,this.basicKey=mt(t.key),this.authOptions=t||{},"clientId"in t&&this.l(t.clientId)}t(t,e){this.method="token",t&&(this.tokenParams=t),e&&(e.token&&(e.tokenDetails="string"==typeof e.token?{token:e.token}:e.token),e.tokenDetails&&(this.tokenDetails=e.tokenDetails),"clientId"in e&&this.l(e.clientId),this.authOptions=e)}h(t){var e=this;return o(function*(){var n=e.tokenDetails;if(n){if(e.p(n.clientId))throw new x("Mismatch between clientId in token ("+n.clientId+") and current clientId ("+e.clientId+")",40102,403);if(!e.client.isTimeOffsetSet()||!n.expires||n.expires>=e.client.getTimestampUsingOffset())return S.logAction(e.logger,S.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+n.expires),n;S.logAction(e.logger,S.LOG_MINOR,"Auth.getToken()","deleting expired token"),e.tokenDetails=null}var i=(e.waitingForTokenRequest||(e.waitingForTokenRequest=qt.create(e.logger))).createPromise();if(null!==e.currentTokenRequestId&&!t)return i;var r,s=e.currentTokenRequestId=Kt++,a=null;try{r=yield e.requestToken(e.tokenParams,e.authOptions)}catch(t){a=t}if(e.currentTokenRequestId>s)return S.logAction(e.logger,S.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),i;e.currentTokenRequestId=null;var o=e.waitingForTokenRequest;return e.waitingForTokenRequest=null,a?(null==o||o.rejectAll(a),i):(null==o||o.resolveAll(e.tokenDetails=r),i)})()}l(t){if("string"!=typeof t&&null!==t)throw new x("clientId must be either a string or null",40012,400);if("*"===t)throw new x('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);var e=this.m(t);if(e)throw e}m(t){if(this.p(t)){var e="Unexpected clientId mismatch: client has "+this.clientId+", requested "+t,n=new x(e,40102,401);return S.logAction(this.logger,S.LOG_ERROR,"Auth._uncheckedSetClientId()",e),n}return this.clientId=this.tokenParams.clientId=t,null}p(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)}u(t){var e=this;return o(function*(){return e.client.getTimestamp(t||!!e.authOptions.queryTime)})()}};function Qt(t){var e=[];if(t)for(var n in t)e.push(n+"="+t[n]);return e.join("&")}function Xt(t,e){return t+(e?"?":"")+Qt(e)}var Yt=class{constructor(t){this.client=t,this.platformHttp=new w.Http(t),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var t,e;return null!=(e=null==(t=this.client)?void 0:t.logger)?e:S.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}C(t){var e=t.connection,n=e&&e.connectionManager.host;return n?[n].concat(Dt.getFallbackHosts(t.options)):Dt.getHosts(t.options)}do(t,e,n,i,r){var s=this;return o(function*(){try{var a=s.client;if(!a)return{error:new x("http.do called without client",5e4,500)};var h="function"==typeof e?e:function(t){return a.baseUri(t)+e},c=a.k;if(c){if(c.validUntil>Date.now()){var u=yield s.doUri(t,h(c.host),n,i,r);return u.error&&s.platformHttp.shouldFallback(u.error)?(a.k=null,s.do(t,e,n,i,r)):u}a.k=null}var l=s.C(a);if(1===l.length)return s.doUri(t,h(l[0]),n,i,r);var d=null,f=function(){var e=o(function*(e,o){var c=e.shift();d=null!=d?d:new Date;var u=yield s.doUri(t,h(c),n,i,r);return u.error&&s.platformHttp.shouldFallback(u.error)&&e.length?Date.now()-d.getTime()>a.options.timeouts.httpMaxRetryDuration?{error:new x("Timeout for trying fallback hosts retries. Total elapsed time exceeded the "+a.options.timeouts.httpMaxRetryDuration+"ms limit",50003,500)}:f(e,!0):(o&&(a.k={host:c,validUntil:Date.now()+a.options.timeouts.fallbackRetryTimeout}),u)});return function(t,n){return e.apply(this,arguments)}}();return f(l)}catch(t){return{error:new x("Unexpected error in Http.do: "+et(t),500,5e4)}}})()}doUri(t,e,n,i,r){var s=this;return o(function*(){try{!function(t,e,n,i,r){r.shouldLog(S.LOG_MICRO)&&S.logActionNoStrip(r,S.LOG_MICRO,"Http."+t+"()","Sending; "+Xt(e,i)+"; Body"+(w.BufferUtils.isBuffer(n)?" (Base64): "+w.BufferUtils.base64Encode(n):": "+n))}(t,e,i,r,s.logger);var a=yield s.platformHttp.doUri(t,e,n,i,r);return s.logger.shouldLog(S.LOG_MICRO)&&function(t,e,n,i,r){t.error?S.logActionNoStrip(r,S.LOG_MICRO,"Http."+e+"()","Received Error; "+Xt(n,i)+"; Error: "+et(t.error)):S.logActionNoStrip(r,S.LOG_MICRO,"Http."+e+"()","Received; "+Xt(n,i)+"; Headers: "+Qt(t.headers)+"; StatusCode: "+t.statusCode+"; Body"+(w.BufferUtils.isBuffer(t.body)?" (Base64): "+w.BufferUtils.base64Encode(t.body):": "+t.body))}(a,t,e,r,s.logger),a}catch(t){return{error:new x("Unexpected error in Http.doUri: "+et(t),500,5e4)}}})()}};function Zt(t,e,n){for(var i,r,s,a=0;a<t.length;a++)if(i=t[a],n&&(i=i[n]),Array.isArray(i)){for(;-1!==(r=i.indexOf(e));)i.splice(r,1);n&&0===i.length&&delete t[a][n]}else if(I(i))for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&Array.isArray(i[s])&&Zt([i],e,s)}var te=class{constructor(t){this.logger=t,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];if(1===e.length){var i=e[0];if("function"!=typeof i)throw new Error("EventListener.on(): Invalid arguments: "+w.Config.inspect(e));this.any.push(i)}if(2===e.length){var[r,s]=e;if("function"!=typeof s)throw new Error("EventListener.on(): Invalid arguments: "+w.Config.inspect(e));if(_(r))this.any.push(s);else if(Array.isArray(r))r.forEach(t=>{this.on(t,s)});else{if("string"!=typeof r)throw new Error("EventListener.on(): Invalid arguments: "+w.Config.inspect(e));(this.events[r]||(this.events[r]=[])).push(s)}}}off(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];if(0==e.length||_(e[0])&&_(e[1]))return this.any=[],this.events=Object.create(null),this.anyOnce=[],void(this.eventsOnce=Object.create(null));var[i,r]=e,s=null,a=null;if(1!==e.length&&r){if("function"!=typeof r)throw new Error("EventEmitter.off(): invalid arguments:"+w.Config.inspect(e));[a,s]=[i,r]}else"function"==typeof i?s=i:a=i;if(s&&_(a))Zt([this.any,this.events,this.anyOnce,this.eventsOnce],s);else if(Array.isArray(a))a.forEach(t=>{this.off(t,s)});else{if("string"!=typeof a)throw new Error("EventEmitter.off(): invalid arguments:"+w.Config.inspect(e));s?Zt([this.events,this.eventsOnce],s,a):(delete this.events[a],delete this.eventsOnce[a])}}listeners(t){if(t){var 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){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];var r={event:t},s=[];this.anyOnce.length&&(Array.prototype.push.apply(s,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(s,this.any);var a=this.eventsOnce[t];a&&(Array.prototype.push.apply(s,a),delete this.eventsOnce[t]);var o=this.events[t];o&&Array.prototype.push.apply(s,o),s.forEach(t=>{!function(t,e,n,i){try{n.apply(e,i)}catch(e){S.logAction(t,S.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+e+"; stack = "+(e&&e.stack))}}(this.logger,r,t,n)})}once(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var i=e.length;if(0===i||1===i&&"function"!=typeof e[0]){var r=e[0];return new Promise(t=>{this.once(r,t)})}var[s,a]=e;if(1===e.length&&"function"==typeof s)this.anyOnce.push(s);else if(_(s)){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+w.Config.inspect(e));this.anyOnce.push(a)}else if(Array.isArray(s)){var o=this,h=function(){var t=Array.prototype.slice.call(arguments);if(s.forEach(function(t){o.off(t,h)}),"function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+w.Config.inspect(e));a.apply(this,t)};s.forEach(function(t){o.on(t,h)})}else{if("string"!=typeof s)throw new Error("EventEmitter.once(): Invalid arguments:"+w.Config.inspect(e));var c=this.eventsOnce[s]||(this.eventsOnce[s]=[]);if(a){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+w.Config.inspect(e));c.push(a)}}}whenState(t,e){var n=this;return o(function*(){if("string"!=typeof t||"string"!=typeof e)throw new Error("whenState requires a valid state String argument");return t===e?null:n.once(t)})()}},ee={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},ne=[];Object.keys(ee).forEach(function(t){ne[ee[t]]=t});var ie={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},re=Object.keys(ie);ie.MODE_ALL=ie.PRESENCE|ie.PUBLISH|ie.SUBSCRIBE|ie.PRESENCE_SUBSCRIBE|ie.ANNOTATION_PUBLISH|ie.ANNOTATION_SUBSCRIBE|ie.OBJECT_SUBSCRIBE|ie.OBJECT_PUBLISH;var se=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function ae(t,e,n){if(n&&n.cipher){t||Ct("Crypto");var i=t.getCipher(n.cipher,e);return{cipher:i.cipherParams,channelCipher:i.cipher}}return null!=n?n:{}}function oe(){return(oe=o(function*(t,e){var{data:n,encoding:i}=yield he(t.data,t.encoding,e);return t.data=n,t.encoding=i,t})).apply(this,arguments)}function he(t,e,n){return ce.apply(this,arguments)}function ce(){return(ce=o(function*(t,e,n){var i=n.channelCipher,r=t,s=e?e+"/":"";return w.BufferUtils.isBuffer(r)||(r=w.BufferUtils.utf8Encode(String(r)),s+="utf-8/"),{data:yield i.encrypt(r),encoding:s=s+"cipher+"+i.algorithm}})).apply(this,arguments)}function ue(t,e){return le.apply(this,arguments)}function le(){return le=o(function*(t,e){var{data:n,encoding:i}=de(t.data,t.encoding);return t.data=n,t.encoding=i,null!=e&&e.cipher?function(t,e){return oe.apply(this,arguments)}(t,e):t}),le.apply(this,arguments)}function de(t,e){if("string"==typeof t||w.BufferUtils.isBuffer(t)||null==t)return{data:t,encoding:e};if(I(t)||Array.isArray(t))return{data:JSON.stringify(t),encoding:e?e+"/json":"json"};throw new x("Data type is unsupported",40013,400)}function fe(t,e){return ve.apply(this,arguments)}function ve(){return(ve=o(function*(t,e){var{data:n,encoding:i,error:r}=yield pe(t.data,t.encoding,e);if(t.data=n,t.encoding=i,r)throw r})).apply(this,arguments)}function pe(t,e,n){return ge.apply(this,arguments)}function ge(){return(ge=o(function*(t,e,n){var i,r=function(t){return t&&t.channelOptions?t:{channelOptions:t,plugins:{},baseEncodedPreviousPayload:void 0}}(n),s=t,a=t,o=e;if(e){var h,c=e.split("/"),u=c.length,l="";try{for(;(h=u)>0;){var d=c[--u].match(/([-\w]+)(\+([\w-]+))?/);if(!d)break;switch(l=d[1]){case"base64":a=w.BufferUtils.base64Decode(String(a)),h==c.length&&(s=a);continue;case"utf-8":a=w.BufferUtils.utf8Decode(a);continue;case"json":a=JSON.parse(a);continue;case"cipher":if(null!=r.channelOptions&&r.channelOptions.cipher&&r.channelOptions.channelCipher){var f=d[3],v=r.channelOptions.channelCipher;if(f!=v.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");a=yield v.decrypt(a);continue}throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!r.plugins||!r.plugins.vcdiff)throw new x("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new x("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var p=r.baseEncodedPreviousPayload;"string"==typeof p&&(p=w.BufferUtils.utf8Encode(p));var g=w.BufferUtils.toBuffer(p);a=w.BufferUtils.toBuffer(a),s=a=w.BufferUtils.arrayBufferViewToBuffer(r.plugins.vcdiff.decode(a,g))}catch(t){throw new x("Vcdiff delta decode failed with "+t,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(t){var y=t;i=new x("Error processing the "+l+" encoding, decoder returned ‘"+y.message+"’",y.code||40013,400)}finally{o=h<=0?null:c.slice(0,h).join("/")}}return i?{error:i,data:a,encoding:o}:(r.baseEncodedPreviousPayload=s,{data:a,encoding:o})})).apply(this,arguments)}function ye(){var t=arguments.length>0?"json":"msgpack",{data:e,encoding:n}=me(this.data,this.encoding,t);return Object.assign({},this,{encoding:n,data:e})}function me(t,e,n){return t&&w.BufferUtils.isBuffer(t)?"msgpack"===n?{data:w.BufferUtils.toBuffer(t),encoding:e}:{data:w.BufferUtils.base64Encode(t),encoding:e?e+"/base64":"base64"}:{data:t,encoding:e}}var we={encryptData:he,encodeData:de,encodeDataForWire:me,decodeData:pe};function be(t){var e,{id:n,connectionId:i,timestamp:r}=t;switch(t.action){case ee.MESSAGE:e=t.messages;break;case ee.PRESENCE:case ee.SYNC:e=t.presence;break;case ee.ANNOTATION:e=t.annotations;break;case ee.OBJECT:case ee.OBJECT_SYNC:e=t.state;break;default:throw new x("Unexpected action "+t.action,4e4,400)}for(var s=0;s<e.length;s++){var a=e[s];a.connectionId||(a.connectionId=i),a.timestamp||(a.timestamp=r),n&&!a.id&&(a.id=n+":"+s)}}function Ce(t,e){var n="["+e;for(var i in t)"data"===i?"string"==typeof t.data?n+="; data="+t.data:w.BufferUtils.isBuffer(t.data)?n+="; data (buffer)="+w.BufferUtils.base64Encode(t.data):void 0!==t.data&&(n+="; data (json)="+JSON.stringify(t.data)):!i||"extras"!==i&&"operation"!==i?"version"===i?n+="; version="+JSON.stringify(t[i]):"annotations"===i?n+="; annotations="+JSON.stringify(t[i]):void 0!==t[i]&&(n+="; "+i+"="+t[i]):n+="; "+i+"="+JSON.stringify(t[i]);return n+="]"}var ke=class{},Te=class{constructor(t){var e,n,i,r,s,a,o,h,c,u;this.Platform=w,this.ErrorInfo=x,this.Logger=S,this.Defaults=Dt,this.Utils=A,this.EventEmitter=te,this.MessageEncoding=we,this.T=null!=(e=t.plugins)?e:null,this.logger=new S,this.logger.setLog(t.logLevel,t.logHandler),S.logAction(this.logger,S.LOG_MICRO,"BaseClient()","initialized with clientOptions "+w.Config.inspect(t)),this.S=null!=(i=null==(n=t.plugins)?void 0:n.MsgPack)?i:null;var l=this.options=Dt.normaliseOptions(t,this.S,this.logger);if(l.key){var d=l.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!d){var f="invalid key parameter";throw S.logAction(this.logger,S.LOG_ERROR,"BaseClient()",f),new x(f,40400,404)}l.keyName=d[1],l.keySecret=d[2]}if("clientId"in l){if("string"!=typeof l.clientId&&null!==l.clientId)throw new x("clientId must be either a string or null",40012,400);if("*"===l.clientId)throw new x('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}S.logAction(this.logger,S.LOG_MINOR,"BaseClient()","started; version = "+Dt.version),this.k=null,this.serverTimeOffset=null,this.http=new Yt(this),this.auth=new Gt(this,l),this.A=(null==(r=t.plugins)?void 0:r.Rest)?new t.plugins.Rest(this):null,this.M=null!=(a=null==(s=t.plugins)?void 0:s.Crypto)?a:null,this.__FilteredSubscriptions=null!=(h=null==(o=t.plugins)?void 0:o.MessageInteractions)?h:null,this.R=null!=(u=null==(c=t.plugins)?void 0:c.Annotations)?u:null}get rest(){return this.A||Ct("Rest"),this.A}get P(){return this.__FilteredSubscriptions||Ct("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var t;return(null==(t=this.options.plugins)?void 0:t.Push)&&this.push.LocalDevice||Ct("Push"),this.O||(this.O=this.push.LocalDevice.load(this)),this.O}baseUri(t){return Dt.getHttpScheme(this.options)+t+":"+Dt.getPort(this.options,!1)}stats(t){var e=this;return o(function*(){return e.rest.stats(t)})()}time(t){var e=this;return o(function*(){return e.rest.time(t)})()}request(t,e,n,i,r,s){var a=this;return o(function*(){return a.rest.request(t,e,n,i,r,s)})()}batchPublish(t){return this.rest.batchPublish(t)}batchPresence(t){return this.rest.batchPresence(t)}setLog(t){this.logger.setLog(t.level,t.handler)}getTimestamp(t){var e=this;return o(function*(){return!e.isTimeOffsetSet()&&t?e.time():e.getTimestampUsingOffset()})()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return null!==this.serverTimeOffset}};Te.Platform=w;var Se=Te,Ae=class t{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:null==(t=this.push)?void 0:t.recipient,state:null==(e=this.push)?void 0:e.state,error:null==(n=this.push)?void 0:n.error}}}toString(){var t,e,n,i,r="[DeviceDetails";return this.id&&(r+="; id="+this.id),this.platform&&(r+="; platform="+this.platform),this.formFactor&&(r+="; formFactor="+this.formFactor),this.clientId&&(r+="; clientId="+this.clientId),this.metadata&&(r+="; metadata="+this.metadata),this.deviceIdentityToken&&(r+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(null==(t=this.push)?void 0:t.recipient)&&(r+="; push.recipient="+JSON.stringify(this.push.recipient)),(null==(e=this.push)?void 0:e.state)&&(r+="; push.state="+this.push.state),(null==(n=this.push)?void 0:n.error)&&(r+="; push.error="+JSON.stringify(this.push.error)),(null==(i=this.push)?void 0:i.metadata)&&(r+="; push.metadata="+this.push.metadata),r+="]"}static toRequestBody(t,e,n){return ct(t,e,n)}static fromResponseBody(e,n,i){return i&&(e=ht(e,n,i)),Array.isArray(e)?t.fromValuesArray(e):t.fromValues(e)}static fromValues(e){return e.error=e.error&&x.fromValues(e.error),Object.assign(new t,e)}static fromLocalDevice(e){return Object.assign(new t,e)}static fromValuesArray(e){for(var n=e.length,i=new Array(n),r=0;r<n;r++)i[r]=t.fromValues(e[r]);return i}};function Ee(t,e,n,i){return xe.apply(this,arguments)}function xe(){return(xe=o(function*(t,e,n,i){return t.http.supportsAuthHeaders?i(R(yield t.auth.getAuthHeaders(),e),n):i(e,R(yield t.auth.getAuthParams(),n))})).apply(this,arguments)}var Me=class t{static get(e,n,i,r,s,a){return o(function*(){return t.do(Wt.Get,e,n,null,i,r,s,null!=a&&a)})()}static delete(e,n,i,r,s,a){return o(function*(){return t.do(Wt.Delete,e,n,null,i,r,s,a)})()}static post(e,n,i,r,s,a,h){return o(function*(){return t.do(Wt.Post,e,n,i,r,s,a,h)})()}static patch(e,n,i,r,s,a,h){return o(function*(){return t.do(Wt.Patch,e,n,i,r,s,a,h)})()}static put(e,n,i,r,s,a,h){return o(function*(){return t.do(Wt.Put,e,n,i,r,s,a,h)})()}static do(t,e,n,i,r,s,a,h){return o(function*(){a&&((s=s||{}).envelope=a);var c=e.logger;function u(t,e){return l.apply(this,arguments)}function l(){return(l=o(function*(r,s){var a;if(c.shouldLog(S.LOG_MICRO)){var o=i;if((null==(a=r["content-type"])?void 0:a.indexOf("msgpack"))>0)try{e.S||Ct("MsgPack"),o=e.S.decode(i)}catch(e){S.logAction(c,S.LOG_MICRO,"Resource."+t+"()","Sending MsgPack Decoding Error: "+et(e))}S.logAction(c,S.LOG_MICRO,"Resource."+t+"()","Sending; "+Xt(n,s)+"; Body: "+o)}var h=yield e.http.do(t,n,r,i,s);return h.error&&Gt.isTokenErr(h.error)?(yield e.auth.authorize(null,null),Ee(e,r,s,u)):{err:h.error,body:h.body,headers:h.headers,unpacked:h.unpacked,statusCode:h.statusCode}})).apply(this,arguments)}var d=yield Ee(e,r,s,u);if(a&&(d=function(t,e,n){if(t.err&&!t.body)return{err:t.err};if(t.statusCode===Vt.NoContent)return p(f({},t),{body:[],unpacked:!0});var i=t.body;if(!t.unpacked)try{i=ht(i,e,n)}catch(t){return tt(t)?{err:t}:{err:new M(et(t),null)}}if(!i)return{err:new M("unenvelope(): Response body is missing",null)};var{statusCode:r,response:s,headers:a}=i;if(void 0===r)return p(f({},t),{body:i,unpacked:!0});if(r<200||r>=300){var o=s&&s.error||t.err;return o||((o=new Error("Error in unenveloping "+i)).statusCode=r),{err:o,body:s,headers:a,unpacked:!0,statusCode:r}}return{err:t.err,body:s,headers:a,unpacked:!0,statusCode:r}}(d,e.S,a)),c.shouldLog(S.LOG_MICRO)&&function(t,e,n,i,r){t.err?S.logAction(r,S.LOG_MICRO,"Resource."+e+"()","Received Error; "+Xt(n,i)+"; Error: "+et(t.err)):S.logAction(r,S.LOG_MICRO,"Resource."+e+"()","Received; "+Xt(n,i)+"; Headers: "+Qt(t.headers)+"; StatusCode: "+t.statusCode+"; Body: "+(w.BufferUtils.isBuffer(t.body)?" (Base64): "+w.BufferUtils.base64Encode(t.body):": "+w.Config.inspect(t.body)))}(d,t,n,s,c),h){if(d.err)throw d.err;var v=f({},d);return delete v.err,v}return d})()}};function Re(t){var e=t.match(/^\.\/(\w+)\?(.*)$/);return e&&e[2]&&Z(e[2])}var Pe=class{constructor(t,e,n){this.resource=t,this.items=e,this.I=n}first(){var t=this;return o(function*(){if(t.hasFirst())return t.get(t.I.first);throw new x("No link to the first page of results",40400,404)})()}current(){var t=this;return o(function*(){if(t.hasCurrent())return t.get(t.I.current);throw new x("No link to the current page of results",40400,404)})()}next(){var t=this;return o(function*(){return t.hasNext()?t.get(t.I.next):null})()}hasFirst(){return null!=this.I&&"first"in this.I}hasCurrent(){return null!=this.I&&"current"in this.I}hasNext(){return null!=this.I&&"next"in this.I}isLast(){return!this.hasNext()}get(t){var e=this;return o(function*(){var n=e.resource,i=yield Me.get(n.client,n.path,n.headers,t,n.envelope,!1);return n.handlePage(i)})()}},Oe=class extends Pe{constructor(t,e,n,i,r,s){super(t,e,r),this.statusCode=i,this.success=i<300&&i>=200,this.headers=n,this.errorCode=s&&s.code,this.errorMessage=s&&s.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},Ie=class{constructor(t,e,n,i,r,s){this.client=t,this.path=e,this.headers=n,this.envelope=null!=i?i:null,this.bodyHandler=r,this.useHttpPaginatedResponse=s||!1}get logger(){return this.client.logger}get(t){var e=this;return o(function*(){var n=yield Me.get(e.client,e.path,e.headers,t,e.envelope,!1);return e.handlePage(n)})()}delete(t){var e=this;return o(function*(){var n=yield Me.delete(e.client,e.path,e.headers,t,e.envelope,!1);return e.handlePage(n)})()}post(t,e){var n=this;return o(function*(){var i=yield Me.post(n.client,n.path,e,n.headers,t,n.envelope,!1);return n.handlePage(i)})()}put(t,e){var n=this;return o(function*(){var i=yield Me.put(n.client,n.path,e,n.headers,t,n.envelope,!1);return n.handlePage(i)})()}patch(t,e){var n=this;return o(function*(){var i=yield Me.patch(n.client,n.path,e,n.headers,t,n.envelope,!1);return n.handlePage(i)})()}handlePage(t){var e=this;return o(function*(){if(t.err&&(n=t.err,i=t.body,!e.useHttpPaginatedResponse||!i&&"number"!=typeof n.code))throw S.logAction(e.logger,S.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+et(t.err)),t.err;var n,i,r,s,a;try{r=t.statusCode==Vt.NoContent?[]:yield e.bodyHandler(t.body,t.headers||{},t.unpacked)}catch(e){throw t.err||e}return t.headers&&(s=t.headers.Link||t.headers.link)&&(a=function(t){"string"==typeof t&&(t=t.split(","));for(var e={},n=0;n<t.length;n++){var i=t[n].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(i){var r=Re(i[1]);r&&(e[i[2]]=r)}}return e}(s)),e.useHttpPaginatedResponse?new Oe(e,r,t.headers||{},t.statusCode,a,t.err):new Pe(e,r,a)})()}},je=class t{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){var t="[PushChannelSubscription";return this.channel&&(t+="; channel="+this.channel),this.deviceId&&(t+="; deviceId="+this.deviceId),this.clientId&&(t+="; clientId="+this.clientId),t+="]"}static fromResponseBody(e,n,i){return i&&(e=ht(e,n,i)),Array.isArray(e)?t.fromValuesArray(e):t.fromValues(e)}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){for(var n=e.length,i=new Array(n),r=0;r<n;r++)i[r]=t.fromValues(e[r]);return i}};je.toRequestBody=ct;var _e=je,Ue=class{constructor(t){this.client=t,this.deviceRegistrations=new Ne(t),this.channelSubscriptions=new De(t)}publish(t,e){var n=this;return o(function*(){var i=n.client,r=i.options.useBinaryProtocol?"msgpack":"json",s=Dt.defaultPostHeaders(i.options),a={},o=R({recipient:t},e);R(s,i.options.headers),i.options.pushFullWait&&R(a,{fullWait:"true"});var h=ct(o,i.S,r);yield Me.post(i,"/push/publish",h,s,a,null,!0)})()}},Ne=class{constructor(t){this.client=t}save(t){var e=this;return o(function*(){var n=e.client,i=Ae.fromValues(t),r=n.options.useBinaryProtocol?"msgpack":"json",s=Dt.defaultPostHeaders(n.options),a={};R(s,n.options.headers),n.options.pushFullWait&&R(a,{fullWait:"true"});var o=ct(i,n.S,r),h=yield Me.put(n,"/push/deviceRegistrations/"+encodeURIComponent(t.id),o,s,a,null,!0);return Ae.fromResponseBody(h.body,n.S,h.unpacked?void 0:r)})()}get(t){var e=this;return o(function*(){var n=e.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=Dt.defaultGetHeaders(n.options),s=t.id||t;if("string"!=typeof s||!s.length)throw new x("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);R(r,n.options.headers);var a=yield Me.get(n,"/push/deviceRegistrations/"+encodeURIComponent(s),r,{},null,!0);return Ae.fromResponseBody(a.body,n.S,a.unpacked?void 0:i)})()}list(t){var e=this;return o(function*(){var n=e.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=e.client.http.supportsLinkHeaders?void 0:i,s=Dt.defaultGetHeaders(n.options);return R(s,n.options.headers),new Ie(n,"/push/deviceRegistrations",s,r,function(){var t=o(function*(t,e,r){return Ae.fromResponseBody(t,n.S,r?void 0:i)});return function(e,n,i){return t.apply(this,arguments)}}()).get(t)})()}remove(t){var e=this;return o(function*(){var n=e.client,i=Dt.defaultGetHeaders(n.options),r={},s=t.id||t;if("string"!=typeof s||!s.length)throw new x("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);R(i,n.options.headers),n.options.pushFullWait&&R(r,{fullWait:"true"}),yield Me.delete(n,"/push/deviceRegistrations/"+encodeURIComponent(s),i,r,null,!0)})()}removeWhere(t){var e=this;return o(function*(){var n=e.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=Dt.defaultGetHeaders(n.options,{format:i});R(r,n.options.headers),n.options.pushFullWait&&R(t,{fullWait:"true"}),yield Me.delete(n,"/push/deviceRegistrations",r,t,null,!0)})()}},De=class t{constructor(e){this.remove=t.prototype.removeWhere,this.client=e}save(t){var e=this;return o(function*(){var n=e.client,i=_e.fromValues(t),r=n.options.useBinaryProtocol?"msgpack":"json",s=Dt.defaultPostHeaders(n.options),a={};R(s,n.options.headers),n.options.pushFullWait&&R(a,{fullWait:"true"});var o=ct(i,n.S,r),h=yield Me.post(n,"/push/channelSubscriptions",o,s,a,null,!0);return _e.fromResponseBody(h.body,n.S,h.unpacked?void 0:r)})()}list(t){var e=this;return o(function*(){var n=e.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=e.client.http.supportsLinkHeaders?void 0:i,s=Dt.defaultGetHeaders(n.options);return R(s,n.options.headers),new Ie(n,"/push/channelSubscriptions",s,r,function(){var t=o(function*(t,e,r){return _e.fromResponseBody(t,n.S,r?void 0:i)});return function(e,n,i){return t.apply(this,arguments)}}()).get(t)})()}removeWhere(t){var e=this;return o(function*(){var n=e.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=Dt.defaultGetHeaders(n.options,{format:i});R(r,n.options.headers),n.options.pushFullWait&&R(t,{fullWait:"true"}),yield Me.delete(n,"/push/channelSubscriptions",r,t,null,!0)})()}listChannels(t){var e=this;return o(function*(){var n=e.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=e.client.http.supportsLinkHeaders?void 0:i,s=Dt.defaultGetHeaders(n.options);return R(s,n.options.headers),n.options.pushFullWait&&R(t,{fullWait:"true"}),new Ie(n,"/push/channels",s,r,function(){var t=o(function*(t,e,r){for(var s=!r&&i?ht(t,n.S,i):t,a=0;a<s.length;a++)s[a]=String(s[a]);return s});return function(e,n,i){return t.apply(this,arguments)}}()).get(t)})()}},qe=class{constructor(t){var e;this.client=t,this.admin=new Ue(t),w.Config.push&&(null==(e=t.options.plugins)?void 0:e.Push)&&(this.stateMachine=new t.options.plugins.Push.ActivationStateMachine(t),this.LocalDevice=t.options.plugins.Push.localDeviceFactory(Ae))}activate(t,e){var n=this;return o(function*(){yield new Promise((i,r)=>{var s;(null==(s=n.client.options.plugins)?void 0:s.Push)?n.stateMachine?n.stateMachine.activatedCallback?r(new x("Activation already in progress",4e4,400)):(n.stateMachine.activatedCallback=t=>{t?r(t):i()},n.stateMachine.updateFailedCallback=e,n.stateMachine.handleEvent(new n.client.options.plugins.Push.CalledActivate(n.stateMachine,t))):r(new x("This platform is not supported as a target of push notifications",4e4,400)):r(bt("Push"))})})()}deactivate(t){var e=this;return o(function*(){yield new Promise((n,i)=>{var r;(null==(r=e.client.options.plugins)?void 0:r.Push)?e.stateMachine?e.stateMachine.deactivatedCallback?i(new x("Deactivation already in progress",4e4,400)):(e.stateMachine.deactivatedCallback=t=>{t?i(t):n()},e.stateMachine.handleEvent(new e.client.options.plugins.Push.CalledDeactivate(e.stateMachine,t))):i(new x("This platform is not supported as a target of push notifications",4e4,400)):i(bt("Push"))})})()}},Be=["absent","present","enter","leave","update"];function We(t,e,n,i){return He.apply(this,arguments)}function He(){return(He=o(function*(t,e,n,i){var r=ae(e,t,null!=i?i:null);return $e.fromValues(n).decode(r,t)})).apply(this,arguments)}function Ve(){return(Ve=o(function*(t,e,n,i){return Promise.all(n.map(function(n){return We(t,e,n,i)}))})).apply(this,arguments)}function ze(){return(ze=o(function*(t,e){return $e.fromValues(t).decode(e.channelOptions,e.logger)})).apply(this,arguments)}function Le(t,e){return Fe.apply(this,arguments)}function Fe(){return Fe=o(function*(t,e){return Promise.all(t.map(function(t){return function(t,e){return ze.apply(this,arguments)}(t,e)}))}),Fe.apply(this,arguments)}var Je=class t extends ke{isSynthesized(){return!this.id||!this.connectionId||this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");var t=this.id.split(":");return{connectionId:t[0],msgSerial:parseInt(t[1],10),index:parseInt(t[2],10)}}encode(t){var e=this;return o(function*(){return ue(Object.assign(new $e,e,{action:Be.indexOf(e.action||"present")}),t)})()}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}static fromData(e){return e instanceof t?e:t.fromValues({data:e})}toString(){return Ce(this,"PresenceMessage")}},$e=class t extends ke{toJSON(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return ye.call(this,...e)}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}decode(t,e){var n=this;return o(function*(){var i=Object.assign(new Je,p(f({},n),{action:Be[n.action]}));try{yield fe(i,t)}catch(t){S.logAction(e,S.LOG_ERROR,"WirePresenceMessage.decode()",et(t))}return i})()}toString(){return Ce(this,"WirePresenceMessage")}},Ke=Je,Ge=class{constructor(t){this.channel=t}get logger(){return this.channel.logger}get(t){var e=this;return o(function*(){S.logAction(e.logger,S.LOG_MICRO,"RestPresence.get()","channel = "+e.channel.name);var n=e.channel.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=e.channel.client.http.supportsLinkHeaders?void 0:i,s=Dt.defaultGetHeaders(n.options);return R(s,n.options.headers),new Ie(n,e.channel.client.rest.presenceMixin.basePath(e),s,r,function(){var t=o(function*(t,r,s){return Le(s?t:ht(t,n.S,i),e.channel)});return function(e,n,i){return t.apply(this,arguments)}}()).get(t)})()}history(t){var e=this;return o(function*(){return S.logAction(e.logger,S.LOG_MICRO,"RestPresence.history()","channel = "+e.channel.name),e.channel.client.rest.presenceMixin.history(e,t)})()}},Qe=["message.create","message.update","message.delete","meta","message.summary","message.append"];function Xe(t){var e=0;return t.name&&(e+=t.name.length),t.clientId&&(e+=t.clientId.length),t.extras&&(e+=JSON.stringify(t.extras).length),t.data&&(e+=it(t.data)),e}function Ye(t,e,n,i){return Ze.apply(this,arguments)}function Ze(){return(Ze=o(function*(t,e,n,i){var r=ae(e,t,null!=i?i:null);return ln.fromValues(n).decode(r,t)})).apply(this,arguments)}function tn(){return(tn=o(function*(t,e,n,i){return Promise.all(n.map(function(n){return Ye(t,e,n,i)}))})).apply(this,arguments)}function en(t,e){return nn.apply(this,arguments)}function nn(){return(nn=o(function*(t,e){return ln.fromValues(t).decode(e.channelOptions,e.logger)})).apply(this,arguments)}function rn(t,e){return sn.apply(this,arguments)}function sn(){return(sn=o(function*(t,e){return Promise.all(t.map(function(t){return en(t,e)}))})).apply(this,arguments)}function an(t,e){return on.apply(this,arguments)}function on(){return(on=o(function*(t,e){return Promise.all(t.map(t=>t.encode(e)))})).apply(this,arguments)}var hn=ct;function cn(t){for(var e,n=0,i=0;i<t.length;i++)n+=(e=t[i]).size||(e.size=Xe(e));return n}var un=class t extends ke{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(var[t,e]of Object.entries(this.annotations.summary))if(t.endsWith(":distinct.v1")||t.endsWith(":unique.v1")||t.endsWith(":multiple.v1"))for(var[,n]of Object.entries(e))n.clipped||(n.clipped=!1);else t.endsWith(":flag.v1")&&(e.clipped||(e.clipped=!1))}encode(t){var e=this;return o(function*(){return ue(Object.assign(new ln,e,{action:Qe.indexOf(e.action||"message.create")}),t)})()}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}toString(){return Ce(this,"Message")}},ln=class t extends ke{toJSON(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return ye.call(this,...e)}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}decodeWithErr(t,e){var n=this;return o(function*(){var i,r,s=Object.assign(new un,p(f({},n),{action:(i=n.action,Qe[i||0]||"unknown")}));try{yield fe(s,t)}catch(t){S.logAction(e,S.LOG_ERROR,"WireMessage.decode()",et(t)),r=t}return s.expandFields(),{decoded:s,err:r}})()}decode(t,e){var n=this;return o(function*(){var{decoded:i}=yield n.decodeWithErr(t,e);return i})()}toString(){return Ce(this,"WireMessage")}},dn=un,fn=class{constructor(t,e,n){var i,r;this.j=null,S.logAction(t.logger,S.LOG_MINOR,"RestChannel()","started; name = "+e),this.name=e,this.client=t,this.presence=new Ge(this),this.channelOptions=_t(null!=(i=t.M)?i:null,this.logger,n),(null==(r=t.options.plugins)?void 0:r.Push)&&(this.U=new t.options.plugins.Push.PushChannel(this)),t.R&&(this.j=new t.R.RestAnnotations(this))}get annotations(){return this.j||Ct("Annotations"),this.j}get push(){return this.U||Ct("Push"),this.U}get logger(){return this.client.logger}setOptions(t){var e;this.channelOptions=_t(null!=(e=this.client.M)?e:null,this.logger,t)}history(t){var e=this;return o(function*(){return S.logAction(e.logger,S.LOG_MICRO,"RestChannel.history()","channel = "+e.name),e.client.rest.channelMixin.history(e,t)})()}publish(){var t=arguments,e=this;return o(function*(){var n,i,r=t.length<=0?void 0:t[0],s=t.length<=1?void 0:t[1];if("string"==typeof r||null===r)n=[dn.fromValues({name:r,data:s})],i=t.length<=2?void 0:t[2];else if(I(r))n=[dn.fromValues(r)],i=t.length<=1?void 0:t[1];else{if(!Array.isArray(r))throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n=dn.fromValuesArray(r),i=t.length<=1?void 0:t[1]}i||(i={});var a=e.client,o=a.options,h=o.useBinaryProtocol?"msgpack":"json",c=a.options.idempotentRestPublishing,u=Dt.defaultPostHeaders(a.options);if(R(u,o.headers),c&&function(t){return t.every(function(t){return!t.id})}(n)){var l=yield st(9);n.forEach(function(t,e){t.id=l+":"+e.toString()})}var d=yield an(n,e.channelOptions),f=cn(d),v=o.maxMessageSize;if(f>v)throw new x("Maximum size of messages that can be published at once exceeded (was "+f+" bytes; limit is "+v+" bytes)",40009,400);return e.N(hn(d,a.S,h),u,i)})()}N(t,e,n){var i=this;return o(function*(){var r=i.client,s=r.options.useBinaryProtocol?"msgpack":"json",{body:a,unpacked:o}=yield Me.post(r,r.rest.channelMixin.basePath(i)+"/messages",t,e,n,null,!0),h=(o?a:ht(a,r.S,s))||{};return delete h.channel,delete h.messageId,h})()}status(){var t=this;return o(function*(){return t.client.rest.channelMixin.status(t)})()}getMessage(t){var e=this;return o(function*(){return S.logAction(e.logger,S.LOG_MICRO,"RestChannel.getMessage()","channel = "+e.name),e.client.rest.channelMixin.getMessage(e,t)})()}updateMessage(t,e,n){var i=this;return o(function*(){return S.logAction(i.logger,S.LOG_MICRO,"RestChannel.updateMessage()","channel = "+i.name),i.client.rest.channelMixin.updateDeleteMessage(i,"message.update",t,e,n)})()}deleteMessage(t,e,n){var i=this;return o(function*(){return S.logAction(i.logger,S.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+i.name),i.client.rest.channelMixin.updateDeleteMessage(i,"message.delete",t,e,n)})()}appendMessage(t,e,n){var i=this;return o(function*(){return S.logAction(i.logger,S.LOG_MICRO,"RestChannel.appendMessage()","channel = "+i.name),i.client.rest.channelMixin.updateDeleteMessage(i,"message.append",t,e,n)})()}getMessageVersions(t,e){var n=this;return o(function*(){return S.logAction(n.logger,S.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+n.name),n.client.rest.channelMixin.getMessageVersions(n,t,e)})()}},vn=class t{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(e){return new t(e)}},pn=class{static basePath(t){return"/channels/"+encodeURIComponent(t.name)}static history(t,e){var n=t.client,i=n.options.useBinaryProtocol?"msgpack":"json",r=t.client.http.supportsLinkHeaders?void 0:i,s=Dt.defaultGetHeaders(n.options);return R(s,n.options.headers),new Ie(n,this.basePath(t)+"/messages",s,r,function(){var e=o(function*(e,r,s){return rn(s?e:ht(e,n.S,i),t)});return function(t,n,i){return e.apply(this,arguments)}}()).get(e)}static status(t){var e=this;return o(function*(){var n=t.client.options.useBinaryProtocol?"msgpack":"json",i=Dt.defaultPostHeaders(t.client.options);return(yield Me.get(t.client,e.basePath(t),i,{},n,!0)).body})()}static getMessage(t,e){var n=this;return o(function*(){var i="string"==typeof e?e:e.serial;if(!i)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);var r=t.client,s=r.options.useBinaryProtocol?"msgpack":"json",a=Dt.defaultGetHeaders(r.options);R(a,r.options.headers);var{body:o,unpacked:h}=yield Me.get(r,n.basePath(t)+"/messages/"+encodeURIComponent(i),a,{},null,!0);return en(h?o:ht(o,r.S,s),t)})()}static updateDeleteMessage(t,e,n,i,r){var s=this;return o(function*(){if(!n.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);var a=t.client,o=a.options.useBinaryProtocol?"msgpack":"json",h=Dt.defaultPostHeaders(a.options);R(h,a.options.headers);var c=dn.fromValues(n);c.action=e,c.version=i;var u=yield c.encode(t.channelOptions),l=hn(u,a.S,o),d=Me.patch,{body:f,unpacked:v}=yield d(a,s.basePath(t)+"/messages/"+encodeURIComponent(n.serial),l,h,r||{},null,!0);return(v?f:ht(f,a.S,o))||{versionSerial:null}})()}static getMessageVersions(t,e,n){var i="string"==typeof e?e:e.serial;if(!i)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);var r=t.client,s=r.options.useBinaryProtocol?"msgpack":"json",a=t.client.http.supportsLinkHeaders?void 0:s,h=Dt.defaultGetHeaders(r.options);return R(h,r.options.headers),new Ie(r,this.basePath(t)+"/messages/"+encodeURIComponent(i)+"/versions",h,a,function(){var e=o(function*(e,n,i){return rn(i?e:ht(e,r.S,s),t)});return function(t,n,i){return e.apply(this,arguments)}}()).get(n||{})}},gn=class{static basePath(t){return pn.basePath(t.channel)+"/presence"}static history(t,e){var n=this;return o(function*(){var i=t.channel.client,r=i.options.useBinaryProtocol?"msgpack":"json",s=t.channel.client.http.supportsLinkHeaders?void 0:r,a=Dt.defaultGetHeaders(i.options);return R(a,i.options.headers),new Ie(i,n.basePath(t)+"/history",a,s,function(){var e=o(function*(e,n,s){return Le(s?e:ht(e,i.S,r),t.channel)});return function(t,n,i){return e.apply(this,arguments)}}()).get(e)})()}},yn=class{constructor(t){this.channelMixin=pn,this.presenceMixin=gn,this.Resource=Me,this.PaginatedResource=Ie,this.DeviceDetails=Ae,this.PushChannelSubscription=_e,this.client=t,this.channels=new mn(this.client),this.push=new qe(this.client)}stats(t){var e=this;return o(function*(){var n=Dt.defaultGetHeaders(e.client.options),i=e.client.options.useBinaryProtocol?"msgpack":"json",r=e.client.http.supportsLinkHeaders?void 0:i;return R(n,e.client.options.headers),new Ie(e.client,"/stats",n,r,function(){var t=o(function*(t,n,r){for(var s=r?t:ht(t,e.client.S,i),a=0;a<s.length;a++)s[a]=vn.fromValues(s[a]);return s});return function(e,n,i){return t.apply(this,arguments)}}()).get(t)})()}time(t){var e=this;return o(function*(){var n=Dt.defaultGetHeaders(e.client.options,{format:"json"});e.client.options.headers&&R(n,e.client.options.headers);var{error:i,body:r,unpacked:s}=yield e.client.http.do(Wt.Get,t=>e.client.baseUri(t)+"/time",n,null,t);if(i)throw i;s||(r=JSON.parse(r));var a=r[0];if(!a)throw new x("Internal error (unexpected result type from GET /time)",5e4,500);return e.client.serverTimeOffset=a-Date.now(),a})()}request(t,e,n,i,r,s){var a=this;return o(function*(){var h,[c,u,l]=a.client.options.useBinaryProtocol?(a.client.S||Ct("MsgPack"),[a.client.S.encode,a.client.S.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],d=a.client.http.supportsLinkHeaders?void 0:l;i=i||{};var f=t.toLowerCase(),v="get"==f?Dt.defaultGetHeaders(a.client.options,{format:l,protocolVersion:n}):Dt.defaultPostHeaders(a.client.options,{format:l,protocolVersion:n});"string"!=typeof r&&(r=null!=(h=c(r))?h:null),R(v,a.client.options.headers),s&&R(v,s);var p=new Ie(a.client,e,v,d,function(){var t=o(function*(t,e,n){return O(n?t:u(t))});return function(e,n,i){return t.apply(this,arguments)}}(),!0);if(!w.Http.methods.includes(f))throw new x("Unsupported method "+f,40500,405);return w.Http.methodsWithBody.includes(f)?p[f](i,r):p[f](i)})()}batchPublish(t){var e=this;return o(function*(){var n,i;Array.isArray(t)?(n=t,i=!1):(n=[t],i=!0);var r=e.client.options.useBinaryProtocol?"msgpack":"json",s=Dt.defaultPostHeaders(e.client.options);e.client.options.headers&&R(s,e.client.options.headers);var a=ct(n,e.client.S,r),o=yield Me.post(e.client,"/messages",a,s,{},null,!0),h=o.unpacked?o.body:ht(o.body,e.client.S,r);return i?h[0]:h})()}batchPresence(t){var e=this;return o(function*(){var n=e.client.options.useBinaryProtocol?"msgpack":"json",i=Dt.defaultGetHeaders(e.client.options);e.client.options.headers&&R(i,e.client.options.headers);var r=t.join(","),s=yield Me.get(e.client,"/presence",i,{channels:r},null,!0);return s.unpacked?s.body:ht(s.body,e.client.S,n)})()}revokeTokens(t,e){var n=this;return o(function*(){if($t(n.client.options))throw new x("Cannot revoke tokens when using token auth",40162,401);var i=n.client.options.keyName,r=null!=e?e:{},s=f({targets:t.map(t=>t.type+":"+t.value)},r),a=n.client.options.useBinaryProtocol?"msgpack":"json",o=Dt.defaultPostHeaders(n.client.options);n.client.options.headers&&R(o,n.client.options.headers);var h=ct(s,n.client.S,a),c=yield Me.post(n.client,"/keys/"+i+"/revokeTokens",h,o,{},null,!0);return c.unpacked?c.body:ht(c.body,n.client.S,a)})()}},mn=class{constructor(t){this.client=t,this.all=Object.create(null)}get(t,e){t=String(t);var n=this.all[t];return n?e&&n.setOptions(e):this.all[t]=n=new fn(this.client,t,e),n}release(t){delete this.all[String(t)]}},wn=class extends Se{constructor(t){super(Dt.objectifyOptions(t,!1,"BaseRest",S.defaultLogger,{Rest:yn}))}},bn={Rest:yn},Cn=class extends dn{static fromEncoded(t,e){return o(function*(){return Ye(S.defaultLogger,w.Crypto,t,e)})()}static fromEncodedArray(t,e){return o(function*(){return function(t,e,n,i){return tn.apply(this,arguments)}(S.defaultLogger,w.Crypto,t,e)})()}static fromValues(t){return dn.fromValues(t)}},kn=class extends Ke{static fromEncoded(t,e){return o(function*(){return We(S.defaultLogger,w.Crypto,t,e)})()}static fromEncodedArray(t,e){return o(function*(){return function(t,e,n,i){return Ve.apply(this,arguments)}(S.defaultLogger,w.Crypto,t,e)})()}static fromValues(t){return Ke.fromValues(t)}},Tn=["annotation.create","annotation.delete"];function Sn(t,e,n){return An.apply(this,arguments)}function An(){return(An=o(function*(t,e,n){return Pn.fromValues(e).decode(n||{},t)})).apply(this,arguments)}function En(){return(En=o(function*(t,e,n){return Promise.all(e.map(function(e){return Sn(t,e,n)}))})).apply(this,arguments)}function xn(){return(xn=o(function*(t,e){return Pn.fromValues(t).decode(e.channelOptions,e.logger)})).apply(this,arguments)}function Mn(){return Mn=o(function*(t,e){return Promise.all(t.map(function(t){return function(t,e){return xn.apply(this,arguments)}(t,e)}))}),Mn.apply(this,arguments)}var Rn=class t extends ke{encode(){var t=this;return o(function*(){return ue(Object.assign(new Pn,t,{action:Tn.indexOf(t.action||"annotation.create")}),{})})()}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}toString(){return Ce(this,"Annotation")}},Pn=class t extends ke{toJSON(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return ye.call(this,...e)}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}decode(t,e){var n=this;return o(function*(){var i=Object.assign(new Rn,p(f({},n),{action:Tn[n.action]}));try{yield fe(i,t)}catch(t){S.logAction(e,S.LOG_ERROR,"WireAnnotation.decode()",et(t))}return i})()}toString(){return Ce(this,"WireAnnotation")}},On=Rn,In=class extends On{static fromEncoded(t,e){return o(function*(){return Sn(S.defaultLogger,t,e)})()}static fromEncodedArray(t,e){return o(function*(){return function(t,e,n){return En.apply(this,arguments)}(S.defaultLogger,t,e)})()}static fromValues(t){return On.fromValues(t)}};function jn(t){var e;switch(typeof t){case"string":e=t;break;case"object":e=t.serial}if(!e||"string"!=typeof e)throw new x("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return e}function _n(t,e){var n=jn(t);if(!e||"object"!=typeof e)throw new x("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);var i=On.fromValues(e);return i.messageSerial=n,i.action||(i.action="annotation.create"),i}function Un(t,e){return t.client.rest.channelMixin.basePath(t)+"/messages/"+encodeURIComponent(e)+"/annotations"}var Nn=class{constructor(t){this.channel=t}publish(t,e){var n=this;return o(function*(){var i=_n(t,e),r=yield i.encode(),s=n.channel.client,a=s.options.useBinaryProtocol?"msgpack":"json",o=Dt.defaultPostHeaders(s.options);R(o,s.options.headers);var h=ct([r],s.S,a);yield Me.post(s,Un(n.channel,i.messageSerial),h,o,{},null,!0)})()}delete(t,e){var n=this;return o(function*(){return e.action="annotation.delete",n.publish(t,e)})()}get(t,e){var n=this;return o(function*(){var i=n.channel.client,r=jn(t),s=i.options.useBinaryProtocol?"msgpack":"json",a=i.http.supportsLinkHeaders?void 0:s,h=Dt.defaultGetHeaders(i.options);return R(h,i.options.headers),new Ie(i,Un(n.channel,r),h,a,function(){var t=o(function*(t,e,r){return function(t,e){return Mn.apply(this,arguments)}(r?t:ht(t,i.S,s),n.channel)});return function(e,n,i){return t.apply(this,arguments)}}()).get(e)})()}},Dn=ct;function qn(t){var e=[];if(t)for(var n=0;n<t.length;n++)e.push(t[n].toString());return"[ "+e.join(", ")+" ]"}function Bn(t,e,n,i){var r,s,a,o,h;return t.error&&(r=x.fromValues(t.error)),t.messages&&(s=ln.fromValuesArray(t.messages)),e&&t.presence&&(a=e.WirePresenceMessage.fromValuesArray(t.presence)),n&&t.annotations&&(o=n.WireAnnotation.fromValuesArray(t.annotations)),i&&t.state&&(h=i.WireObjectMessage.fromValuesArray(t.state,A,we)),Object.assign(new zn,p(f({},t),{presence:a,messages:s,annotations:o,state:h,error:r}))}function Wn(t){return e=>{var n;return Bn(e,{WirePresenceMessage:$e},{WireAnnotation:Pn},null!=(n=null==t?void 0:t.LiveObjectsPlugin)?n:null)}}function Hn(t){return Object.assign(new zn,t)}function Vn(t,e,n,i){var r="[ProtocolMessage";void 0!==t.action&&(r+="; action="+ne[t.action]||t.action);for(var s,a=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],o=0;o<a.length;o++)void 0!==t[s=a[o]]&&(r+="; "+s+"="+t[s]);if(t.messages&&(r+="; messages="+qn(ln.fromValuesArray(t.messages))),t.presence&&e&&(r+="; presence="+qn(e.WirePresenceMessage.fromValuesArray(t.presence))),t.annotations&&n&&(r+="; annotations="+qn(n.WireAnnotation.fromValuesArray(t.annotations))),t.state&&i&&(r+="; state="+qn(i.WireObjectMessage.fromValuesArray(t.state,A,we))),t.error&&(r+="; error="+x.fromValues(t.error).toString()),t.auth&&t.auth.accessToken&&(r+="; token="+t.auth.accessToken),t.flags&&(r+="; flags="+re.filter(t.hasFlag).join(",")),t.params){var h="";J(t.params,function(e){h.length>0&&(h+="; "),h+=e+"="+t.params[e]}),h.length>0&&(r+="; params=["+h+"]")}return r+="]"}var zn=class{constructor(){this.hasFlag=t=>(this.flags&ie[t])>0}setFlag(t){return this.flags=this.flags|ie[t]}getMode(){return(this.flags||0)&ie.MODE_ALL}encodeModesToFlags(t){t.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){var t=[];return se.forEach(e=>{this.hasFlag(e)&&t.push(e)}),t.length>0?t:void 0}},Ln=zn,Fn=class{constructor(t,e,n,i,r){this.previous=t,this.current=e,"attached"===e&&(this.resumed=n,this.hasBacklog=i),r&&(this.reason=r)}},Jn=function(){};function $n(t){var e=t||{},{agent:n}=e;return((t,e)=>{var n={};for(var i in t)u.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&c)for(var i of c(t))e.indexOf(i)<0&&l.call(t,i)&&(n[i]=t[i]);return n})(e,["agent"])}var Kn=class t extends te{constructor(t,e,n){var i,r,s;super(t.logger),this.j=null,this.D=0,this.retryCount=0,this.history=function(){var t=o(function*(t){S.logAction(this.logger,S.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);var e=this.client.rest.channelMixin;if(t&&t.untilAttach){if("attached"!==this.state)throw new x("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new x("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete t.untilAttach,t.from_serial=this.properties.attachSerial}return e.history(this,t)});return function(e){return t.apply(this,arguments)}}(),this.whenState=t=>te.prototype.whenState.call(this,t,this.state),S.logAction(this.logger,S.LOG_MINOR,"RealtimeChannel()","started; name = "+e),this.name=e,this.channelOptions=_t(null!=(i=t.M)?i:null,this.logger,n),this.client=t,this.q=t.B?new t.B.RealtimePresence(this):null,t.R&&(this.j=new t.R.RealtimeAnnotations(this)),this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new te(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this.W=!1,this.H={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this.V={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this.L=new te(this.logger),(null==(r=t.options.plugins)?void 0:r.Push)&&(this.U=new t.options.plugins.Push.PushChannel(this)),(null==(s=t.options.plugins)?void 0:s.LiveObjects)&&(this.F=new t.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this.q||Ct("RealtimePresence"),this.q}get annotations(){return this.j||Ct("Annotations"),this.j}get push(){return this.U||Ct("Push"),this.U}get object(){return this.F||Ct("LiveObjects"),this.F}invalidStateError(){return new x("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(t){return"function"==typeof(t=Array.prototype.slice.call(t))[0]&&t.unshift(null),t}setOptions(t){var e=this;return o(function*(){var n,i=e.channelOptions,r=function(t){if(t&&"params"in t&&!I(t.params))return new x("options.params must be an object",4e4,400);if(t&&"modes"in t){if(!Array.isArray(t.modes))return new x("options.modes must be an array",4e4,400);for(var e=0;e<t.modes.length;e++){var n=t.modes[e];if(!n||"string"!=typeof n||!se.includes(String.prototype.toUpperCase.call(n)))return new x("Invalid channel mode: "+n,4e4,400)}}}(t);if(r)throw r;if(e.channelOptions=_t(null!=(n=e.client.M)?n:null,e.logger,t),e.H&&(e.H.channelOptions=e.channelOptions),e.J(t,i))return e.attachImpl(),new Promise((t,n)=>{e.L.once(["attached","update","detached","failed"],function(e){switch(this.event){case"update":case"attached":t();break;default:n(e.reason)}})})})()}J(t,e){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==t?void 0:t.params){var n=$n(t.params),i=$n(e.params);if(Object.keys(n).length!==Object.keys(i).length)return!0;if(!gt(i,n))return!0}return!(!(null==t?void 0:t.modes)||e.modes&&wt(t.modes,e.modes))}publish(){var t=arguments,e=this;return o(function*(){var n,i,r=t.length<=0?void 0:t[0],s=t.length<=1?void 0:t[1];if("string"==typeof r||null==r)n=[dn.fromValues({name:r,data:s})],i=t.length<=2?void 0:t[2];else if(I(r))n=[dn.fromValues(r)],i=t.length<=1?void 0:t[1];else{if(!Array.isArray(r))throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n=dn.fromValuesArray(r),i=t.length<=1?void 0:t[1]}var a=e.client.options.maxMessageSize,o=yield an(n,e.channelOptions),h=cn(o);if(h>a)throw new x("Maximum size of messages that can be published at once exceeded (was "+h+" bytes; limit is "+a+" bytes)",40009,400);e.throwIfUnpublishableState(),S.logAction(e.logger,S.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+e.state+", message count = "+o.length);var c=Hn({action:ee.MESSAGE,channel:e.name,messages:o,params:i?Y(i):void 0});return(yield e.sendMessage(c))||{serials:[]}})()}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(t){S.logAction(this.logger,S.LOG_MICRO,"RealtimeChannel.onEvent()","received message");for(var e=this.subscriptions,n=0;n<t.length;n++){var i=t[n];e.emit(i.name,i)}}attach(){var t=this;return o(function*(){return"attached"===t.state?null:new Promise((e,n)=>{t.$(!1,null,(t,i)=>t?n(t):e(i))})})()}$(t,e,n){n||(n=t=>{t&&S.logAction(this.logger,S.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+t.toString())});var i=this.connectionManager;i.activeState()?(("attaching"!==this.state||t)&&this.requestState("attaching",e),this.once(function(t){switch(this.event){case"attached":null==n||n(null,t);break;case"detached":case"suspended":case"failed":null==n||n(t.reason||i.getError()||new x("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new x("Attach request superseded by a subsequent detach request",9e4,409))}})):n(i.getError())}attachImpl(){S.logAction(this.logger,S.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");var t=Hn({action:ee.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&t.encodeModesToFlags(lt(this.channelOptions.modes)),this.W&&t.setFlag("ATTACH_RESUME"),this.V.decodeFailureRecoveryInProgress&&(t.channelSerial=this.V.protocolMessageChannelSerial),this.sendMessage(t).catch(Jn)}detach(){var t=this;return o(function*(){var e=t.connectionManager;switch(t.state){case"suspended":return void t.notifyState("detached");case"detached":return;case"failed":throw new x("Unable to detach; channel state = failed",90001,400);default:if("connected"!==e.state.state)return void t.notifyState("detached");t.requestState("detaching");case"detaching":return new Promise((n,i)=>{t.once(function(t){switch(this.event){case"detached":n();break;case"attached":case"suspended":case"failed":i(t.reason||e.getError()||new x("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":i(new x("Detach request superseded by a subsequent attach request",9e4,409))}})})}})()}detachImpl(){S.logAction(this.logger,S.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");var t=Hn({action:ee.DETACH,channel:this.name});this.sendMessage(t).catch(Jn)}subscribe(){var e=arguments,n=this;return o(function*(){for(var i=e.length,r=new Array(i),s=0;s<i;s++)r[s]=e[s];var[a,o]=t.processListenerArgs(r);if("failed"===n.state)throw x.fromValues(n.invalidStateError());return a&&"object"==typeof a&&!Array.isArray(a)?n.client.P.subscribeFilter(n,a,o):n.subscriptions.on(a,o),!1!==n.channelOptions.attachOnSubscribe?n.attach():null})()}unsubscribe(){for(var e,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];var[s,a]=t.processListenerArgs(i);"object"==typeof s&&!a||(null==(e=this.filteredSubscriptions)?void 0:e.has(a))?this.client.P.getAndDeleteFilteredSubscriptions(this,s,a).forEach(t=>this.subscriptions.off(t)):this.subscriptions.off(s,a)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new M("Unable to sync to channel; not attached",4e4)}var t=this.connectionManager;if(!t.activeState())throw t.getError();var e=Hn({action:ee.SYNC,channel:this.name});this.syncChannelSerial&&(e.channelSerial=this.syncChannelSerial),t.send(e)}sendMessage(t){var e=this;return o(function*(){return new Promise((n,i)=>{e.connectionManager.send(t,e.client.options.queueMessages,(t,e)=>{t?i(t):n(e)})})})()}sendPresence(t){var e=this;return o(function*(){var n=Hn({action:ee.PRESENCE,channel:e.name,presence:t});yield e.sendMessage(n)})()}sendState(t){var e=this;return o(function*(){var n=Hn({action:ee.OBJECT,channel:e.name,state:t});yield e.sendMessage(n)})()}processMessage(t){var e=this;return o(function*(){t.action!==ee.ATTACHED&&t.action!==ee.MESSAGE&&t.action!==ee.PRESENCE&&t.action!==ee.OBJECT&&t.action!==ee.ANNOTATION||e.setChannelSerial(t.channelSerial);var n,i=!1;switch(t.action){case ee.ATTACHED:e.properties.attachSerial=t.channelSerial,e.D=t.getMode(),e.params=t.params||{};var r=t.decodeModesFromFlags();e.modes=r&&ut(r)||void 0;var s=t.hasFlag("RESUMED"),a=t.hasFlag("HAS_PRESENCE"),o=t.hasFlag("HAS_BACKLOG"),h=t.hasFlag("HAS_OBJECTS");if("attached"===e.state){s||(e.q&&e.q.onAttached(a),e.F&&e.F.onAttached(h));var c=new Fn(e.state,e.state,s,o,t.error);e.L.emit("update",c),s&&!e.channelOptions.updateOnAttached||e.emit("update",c)}else"detaching"===e.state?e.checkPendingState():e.notifyState("attached",t.error,s,a,o,h);break;case ee.DETACHED:var u=t.error?x.fromValues(t.error):new x("Channel detached",90001,404);"detaching"===e.state?e.notifyState("detached",u):"attaching"===e.state?e.notifyState("suspended",u):"attached"!==e.state&&"suspended"!==e.state||e.requestState("attaching",u);break;case ee.SYNC:if(i=!0,n=e.syncChannelSerial=t.channelSerial,!t.presence)break;case ee.PRESENCE:if(!t.presence)break;be(t);var l=e.channelOptions;if(e.q){var d=yield Promise.all(t.presence.map(t=>t.decode(l,e.logger)));e.q.setPresence(d,i,n)}break;case ee.OBJECT:case ee.OBJECT_SYNC:if(!e.F||!t.state)return;be(t);var f=e.client.connection.connectionManager.getActiveTransportFormat(),v=t.state.map(t=>t.decode(e.client,f));t.action===ee.OBJECT?e.F.handleObjectMessages(v):e.F.handleObjectSyncMessages(v,t.channelSerial);break;case ee.MESSAGE:if("attached"!==e.state)return void S.logAction(e.logger,S.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+t.id+'" skipped as this channel "'+e.name+'" state is not "attached" (state is "'+e.state+'").');be(t);var p=t.messages,g=p[0],y=p[p.length-1];if(g.extras&&g.extras.delta&&g.extras.delta.from!==e.V.messageId){var m='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+e.name+'".';S.logAction(e.logger,S.LOG_ERROR,"RealtimeChannel.processMessage()",m),e.K(new x(m,40018,400));break}for(var w=[],b=0;b<p.length;b++){var{decoded:C,err:k}=yield p[b].decodeWithErr(e.H,e.logger);if(w[b]=C,k)switch(k.code){case 40018:return void e.K(k);case 40019:case 40021:return void e.notifyState("failed",k)}}e.V.messageId=y.id,e.V.protocolMessageChannelSerial=t.channelSerial,e.onEvent(w);break;case ee.ANNOTATION:be(t);var T=e.channelOptions;if(e.j){var A=yield Promise.all((t.annotations||[]).map(t=>t.decode(T,e.logger)));e.j.G(A)}break;case ee.ERROR:var E=t.error;E&&80016==E.code?e.checkPendingState():e.notifyState("failed",x.fromValues(E));break;default:S.logAction(e.logger,S.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+t.action+")")}})()}K(t){this.V.decodeFailureRecoveryInProgress||(S.logAction(this.logger,S.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this.V.decodeFailureRecoveryInProgress=!0,this.$(!0,t,()=>{this.V.decodeFailureRecoveryInProgress=!1}))}onAttached(){S.logAction(this.logger,S.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(t,e,n,i,r,s){if(S.logAction(this.logger,S.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+t),this.clearStateTimer(),["detached","suspended","failed"].includes(t)&&(this.properties.channelSerial=null),t!==this.state){this.q&&this.q.actOnChannelState(t,i,e),this.F&&this.F.actOnChannelState(t,s),"suspended"===t&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),e&&(this.errorReason=e);var a=new Fn(this.state,t,n,r,e),o='Channel state for channel "'+this.name+'"',h=t+(e?"; reason: "+e:"");"failed"===t?S.logAction(this.logger,S.LOG_ERROR,o,h):S.logAction(this.logger,S.LOG_MAJOR,o,h),"attaching"!==t&&"suspended"!==t&&(this.retryCount=0),"attached"===t&&this.onAttached(),"attached"===t?this.W=!0:"detaching"!==t&&"failed"!==t||(this.W=!1),this.state=t,this.L.emit(t,a),this.emit(t,a)}}requestState(t,e){S.logAction(this.logger,S.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+t),this.notifyState(t,e),this.checkPendingState()}checkPendingState(){if(this.connectionManager.state.sendEvents)switch(S.logAction(this.logger,S.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()}else S.logAction(this.logger,S.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state)}timeoutPendingState(){switch(this.state){case"attaching":var t=new x("Channel attach timed out",90007,408);this.notifyState("suspended",t);break;case"detaching":var e=new x("Channel detach timed out",90007,408);this.notifyState("attached",e);break;default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{S.logAction(this.logger,S.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){var t=this.stateTimer;t&&(clearTimeout(t),this.stateTimer=null)}startRetryTimer(){if(!this.retryTimer){this.retryCount++;var t=vt(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,S.logAction(this.logger,S.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},t)}}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){var t=this.state;return"initialized"===t||"detached"===t||"failed"===t?null:new x("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+t,90001,400)}setChannelSerial(t){S.logAction(this.logger,S.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+t+"; previous = "+this.properties.channelSerial),t&&(this.properties.channelSerial=t)}status(){var t=this;return o(function*(){return t.client.rest.channelMixin.status(t)})()}getMessage(t){var e=this;return o(function*(){return S.logAction(e.logger,S.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+e.name),e.client.rest.channelMixin.getMessage(e,t)})()}updateMessage(t,e,n){var i=this;return o(function*(){return S.logAction(i.logger,S.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+i.name),i.sendUpdate(t,"message.update",e,n)})()}deleteMessage(t,e,n){var i=this;return o(function*(){return S.logAction(i.logger,S.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+i.name),i.sendUpdate(t,"message.delete",e,n)})()}appendMessage(t,e,n){var i=this;return o(function*(){return S.logAction(i.logger,S.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+i.name),i.sendUpdate(t,"message.append",e,n)})()}sendUpdate(t,e,n,i){var r=this;return o(function*(){var s,a;if(!t.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);r.throwIfUnpublishableState();var o=dn.fromValues(p(f({},t),{action:e,version:n})),h=yield o.encode(r.channelOptions),c=Hn({action:ee.MESSAGE,channel:r.name,messages:[h],params:i?Y(i):void 0}),u=yield r.sendMessage(c);return{versionSerial:null!=(a=null==(s=null==u?void 0:u.serials)?void 0:s[0])?a:null}})()}getMessageVersions(t,e){var n=this;return o(function*(){return S.logAction(n.logger,S.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+n.name),n.client.rest.channelMixin.getMessageVersions(n,t,e)})()}ensureAttached(){var t=this;return o(function*(){switch(t.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":yield t.attach();break;default:throw x.fromValues(t.invalidStateError())}})()}},Gn=class{constructor(t){this.channel=t,this.logger=t.logger,this.subscriptions=new te(this.logger)}publish(t,e){var n=this;return o(function*(){var i=n.channel.name,r=_n(t,e),s=yield r.encode();n.channel.throwIfUnpublishableState(),S.logAction(n.logger,S.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+i+", sending annotation with messageSerial = "+r.messageSerial+", type = "+r.type);var a=Hn({action:ee.ANNOTATION,channel:i,annotations:[s]});yield n.channel.sendMessage(a)})()}delete(t,e){var n=this;return o(function*(){e.action="annotation.delete",yield n.publish(t,e)})()}subscribe(){var t=arguments,e=this;return o(function*(){for(var n=t.length,i=new Array(n),r=0;r<n;r++)i[r]=t[r];var s=Kn.processListenerArgs(i),a=s[0],o=s[1],h=e.channel;if("failed"===h.state)throw x.fromValues(h.invalidStateError());if(e.subscriptions.on(a,o),!1!==e.channel.channelOptions.attachOnSubscribe&&(yield h.attach()),0===("attached"===e.channel.state&&e.channel.D&ie.ANNOTATION_SUBSCRIBE))throw new x("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)})()}unsubscribe(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var i=Kn.processListenerArgs(e),r=i[0],s=i[1];this.subscriptions.off(r,s)}G(t){for(var e of t)this.subscriptions.emit(e.type||"",e)}get(t,e){var n=this;return o(function*(){return Nn.prototype.get.call(n,t,e)})()}},Qn=class t extends wn{constructor(e){var n,i;if(!t.S)throw new Error("Expected DefaultRest._MsgPack to have been set");super(Dt.objectifyOptions(e,!0,"Rest",S.defaultLogger,p(f({},bn),{Crypto:null!=(n=t.Crypto)?n:void 0,MsgPack:null!=(i=t.S)?i:void 0,Annotations:{Annotation:On,WireAnnotation:Pn,RealtimeAnnotations:Gn,RestAnnotations:Nn}})))}static get Crypto(){if(null===this.M)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this.M}static set Crypto(t){this.M=t}};Qn.M=null,Qn.Message=Cn,Qn.PresenceMessage=kn,Qn.Annotation=In,Qn.S=null,Qn.X=Yt;var Xn,Yn,Zn=Qn,ti=class extends te{constructor(t){super(t),this.messages=[]}count(){return this.messages.length}push(t){this.messages.push(t)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(t){this.messages.push.apply(this.messages,t)}prepend(t){this.messages.unshift.apply(this.messages,t)}completeMessages(t,e,n){S.logAction(this.logger,S.LOG_MICRO,"MessageQueue.completeMessages()","all"==t?"(all)":"serial = "+t.serial+"; count = "+t.count),e=e||null;var i=this.messages;if(0===i.length)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");var r=[];if("all"===t)r=i.splice(0);else{var s=i[0];if(s){var a=s.message.msgSerial,o=t.serial+t.count;o>a&&(r=i.splice(0,o-a))}}for(var h=0;h<r.length;h++){var c=r[h],u=null==n?void 0:n[h];c.callback(e,u)}0==i.length&&this.emit("idle")}completeAllMessages(t){this.completeMessages("all",t)}resetSendAttempted(){for(var t of this.messages)t.sendAttempted=!1}clear(){S.logAction(this.logger,S.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},ei=class{constructor(t,e){this.message=t,this.callback=e,this.merged=!1;var n=t.action;this.sendAttempted=!1,this.ackRequired="number"==typeof n&&[ee.MESSAGE,ee.PRESENCE,ee.ANNOTATION,ee.OBJECT].includes(n)}},ni=class extends te{constructor(t){super(t.logger),this.transport=t,this.messageQueue=new ti(this.logger),t.on("ack",(t,e,n)=>{this.onAck(t,e,n)}),t.on("nack",(t,e,n)=>{this.onNack(t,e,n)})}onAck(t,e,n){S.logAction(this.logger,S.LOG_MICRO,"Protocol.onAck()","serial = "+t+"; count = "+e),this.messageQueue.completeMessages({serial:t,count:e},null,n)}onNack(t,e,n){S.logAction(this.logger,S.LOG_ERROR,"Protocol.onNack()","serial = "+t+"; count = "+e+"; err = "+et(n)),n||(n=new x("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:t,count:e},n)}onceIdle(t){var e=this.messageQueue;0!==e.count()?e.once("idle",t):t()}send(t){t.ackRequired&&this.messageQueue.push(t),this.logger.shouldLog(S.LOG_MICRO)&&S.logActionNoStrip(this.logger,S.LOG_MICRO,"Protocol.send()","sending msg; "+Vn(t.message,this.transport.connectionManager.realtime.B,this.transport.connectionManager.realtime.R,this.transport.connectionManager.realtime.Y)),t.sendAttempted=!0,this.transport.send(t.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){var t=this.transport;this.onceIdle(function(){t.disconnect()})}},ii=class{constructor(t,e,n,i){this.previous=t,this.current=e,n&&(this.retryIn=n),i&&(this.reason=i)}},ri={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},si={disconnected:()=>x.fromValues({statusCode:400,code:ri.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>x.fromValues({statusCode:400,code:ri.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>x.fromValues({statusCode:400,code:ri.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>x.fromValues({statusCode:400,code:ri.CLOSING,message:"Connection closing"}),closed:()=>x.fromValues({statusCode:400,code:ri.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>x.fromValues({statusCode:500,code:ri.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>x.fromValues({statusCode:500,code:ri.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},ai=Hn({action:ee.CLOSE}),oi=Hn({action:ee.DISCONNECT}),hi=class extends te{constructor(t,e,n,i){super(t.logger),i&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=t,this.auth=e,this.params=n,this.timeouts=n.options.timeouts,this.format=n.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",si.closed())}disconnect(t){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",t||si.disconnected())}fail(t){this.isConnected&&this.requestDisconnect(),this.finish("failed",t||si.failed())}finish(t,e){var n;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout(null!=(n=this.idleTimer)?n:void 0),this.idleTimer=null,this.emit(t,e),this.dispose())}onProtocolMessage(t){switch(this.logger.shouldLog(S.LOG_MICRO)&&S.logActionNoStrip(this.logger,S.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+Vn(t,this.connectionManager.realtime.B,this.connectionManager.realtime.R,this.connectionManager.realtime.Y)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),t.action){case ee.HEARTBEAT:S.logActionNoStrip(this.logger,S.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",t.id);break;case ee.CONNECTED:this.onConnect(t),this.emit("connected",t.error,t.connectionId,t.connectionDetails,t);break;case ee.CLOSED:this.onClose(t);break;case ee.DISCONNECTED:this.onDisconnect(t);break;case ee.ACK:this.emit("ack",t.msgSerial,t.count,t.res);break;case ee.NACK:this.emit("nack",t.msgSerial,t.count,t.error);break;case ee.SYNC:this.connectionManager.onChannelMessage(t,this);break;case ee.ACTIVATE:break;case ee.AUTH:ot(this.auth.authorize(),t=>{t&&S.logAction(this.logger,S.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+et(t))});break;case ee.ERROR:if(S.logAction(this.logger,S.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+w.Config.inspect(t.error)+(t.channel?", channel: "+t.channel:"")),void 0===t.channel){this.onFatalError(t);break}this.connectionManager.onChannelMessage(t,this);break;default:this.connectionManager.onChannelMessage(t,this)}}onConnect(t){if(this.isConnected=!0,!t.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");var e=t.connectionDetails.maxIdleInterval;e&&(this.maxIdleInterval=e+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(t){var e=t&&t.error;S.logAction(this.logger,S.LOG_MINOR,"Transport.onDisconnect()","err = "+et(e)),this.finish("disconnected",e)}onFatalError(t){var e=t&&t.error;S.logAction(this.logger,S.LOG_MINOR,"Transport.onFatalError()","err = "+et(e)),this.finish("failed",e)}onClose(t){var e=t&&t.error;S.logAction(this.logger,S.LOG_MINOR,"Transport.onClose()","err = "+et(e)),this.finish("closed",e)}requestClose(){S.logAction(this.logger,S.LOG_MINOR,"Transport.requestClose()",""),this.send(ai)}requestDisconnect(){S.logAction(this.logger,S.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(oi)}ping(t){var e={action:ee.HEARTBEAT};t&&(e.id=t),this.send(Hn(e))}dispose(){S.logAction(this.logger,S.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(t){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},t))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;var t=Date.now()-this.lastActivity,e=this.maxIdleInterval-t;if(e<=0){var n="No activity seen from realtime in "+t+"ms; assuming connection has dropped";S.logAction(this.logger,S.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new x(n,80003,408))}else this.setIdleTimer(e+100)}static tryConnect(t,e,n,i,r){var s,a=new t(e,n,i),o=function(t){clearTimeout(s),r({event:this.event,error:t})},h=e.options.timeouts.realtimeRequestTimeout;return s=setTimeout(()=>{a.off(["preconnect","disconnected","failed"]),a.dispose(),o.call({event:"disconnected"},new x("Timeout waiting for transport to indicate itself viable",5e4,500))},h),a.on(["failed","disconnected"],o),a.on("preconnect",function(){S.logAction(e.logger,S.LOG_MINOR,"Transport.tryConnect()","viable transport "+a),clearTimeout(s),a.off(["failed","disconnected"],o),r(null,a)}),a.connect(),a}static isAvailable(){throw new x("isAvailable not implemented for transport",5e4,500)}};(Yn=Xn||(Xn={})).WebSocket="web_socket",Yn.Comet="comet",Yn.XhrPolling="xhr_polling";var ci=void 0!==v?v:"undefined"!=typeof window?window:self,ui=()=>{var t;return void 0!==w.WebStorage&&(null==(t=w.WebStorage)?void 0:t.localSupported)},li=()=>{var t;return void 0!==w.WebStorage&&(null==(t=w.WebStorage)?void 0:t.sessionSupported)},di=function(){},fi="ably-transport-preference";function vi(t){try{return JSON.parse(t)}catch(t){return null}}var pi=class{constructor(t,e,n,i){this.options=t,this.host=e,this.mode=n,this.connectionKey=i,this.format=t.useBinaryProtocol?"msgpack":"json"}getConnectParams(t){var e=t?P(t):{},n=this.options;switch(this.mode){case"resume":e.resume=this.connectionKey;break;case"recover":var i=vi(n.recover);i&&(e.recover=i.connectionKey)}return void 0!==n.clientId&&(e.clientId=n.clientId),!1===n.echoMessages&&(e.echo="false"),void 0!==this.format&&(e.format=this.format),void 0!==this.stream&&(e.stream=this.stream),void 0!==this.heartbeats&&(e.heartbeats=this.heartbeats),e.v=Dt.protocolVersion,e.agent=jt(this.options),void 0!==n.transportParams&&R(e,n.transportParams),e}toString(){var t="[mode="+this.mode;return this.host&&(t+=",host="+this.host),this.connectionKey&&(t+=",connectionKey="+this.connectionKey),this.format&&(t+=",format="+this.format),t+="]"}},gi=class t extends te{constructor(t,e){super(t.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=t,this.initTransports(),this.options=e;var n=e.timeouts,i=n.webSocketConnectTimeout+n.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:i,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:n.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new ti(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=n.connectionStateTtl,this.maxIdleInterval=null,this.transports=B(e.transports||Dt.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(Xn.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(Xn.XhrPolling)?this.baseTransport=Xn.XhrPolling:this.transports.includes(Xn.Comet)&&(this.baseTransport=Xn.Comet),this.domains=Dt.getHosts(e),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,S.logAction(this.logger,S.LOG_MINOR,"Realtime.ConnectionManager()","started"),S.logAction(this.logger,S.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(e.transports||Dt.defaultTransports)+"]"),S.logAction(this.logger,S.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),S.logAction(this.logger,S.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){var r="no requested transports available";throw S.logAction(this.logger,S.LOG_ERROR,"realtime.ConnectionManager()",r),new Error(r)}var s=w.Config.addEventListener;s&&(li()&&"function"==typeof e.recover&&s("beforeunload",this.persistConnection.bind(this)),!0===e.closeOnUnload&&s("beforeunload",()=>{S.logAction(this.logger,S.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),s("online",()=>{var t;this.state==this.states.disconnected||this.state==this.states.suspended?(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager caught browser ‘online’ event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&(null==(t=this.pendingTransport)||t.off(),this.disconnectAllTransports(),this.startConnect())}),s("offline",()=>{this.state==this.states.connected&&(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager caught browser ‘offline’ event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(t){var e={supportedTransports:{}};return this.initTransports(t,e),e.supportedTransports}static initTransports(t,e){var n=f(f({},w.Transports.bundledImplementations),t);[Xn.WebSocket,...w.Transports.order].forEach(t=>{var i=n[t];i&&i.isAvailable()&&(e.supportedTransports[t]=i)})}initTransports(){t.initTransports(this.realtime.Z,this)}createTransportParams(t,e){return new pi(this.options,t,e,this.connectionKey)}getTransportParams(t){(t=>{if(this.connectionKey)t("resume");else if("string"!=typeof this.options.recover){var e=this.options.recover,n=this.getSessionRecoverData(),i=this.sessionRecoveryName();if(n&&"function"==typeof e)return S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+i+")"),void e(n,e=>{e?(this.options.recover=n.recoveryKey,t("recover")):t("clean")});t("clean")}else t("recover")})(e=>{var n=this.createTransportParams(null,e);if("recover"===e){S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);var i=vi(this.options.recover);i&&(this.msgSerial=i.msgSerial)}else S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+n.toString());t(n)})}tryATransport(t,e,n){S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+e),this.proposedTransport=hi.tryConnect(this.supportedTransports[e],this,this.realtime.auth,t,(i,r)=>{var s,a=this.state;return a==this.states.closing||a==this.states.closed||a==this.states.failed?(r&&(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+a.state+" while we were attempting the transport; closing "+r),r.close()),void n(!0)):i?(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+e+" "+i.event+", err: "+i.error.toString()),void(!Gt.isTokenErr(i.error)||this.errorReason&&Gt.isTokenErr(this.errorReason)?"failed"===i.event?(this.notifyState({state:"failed",error:i.error}),n(!0)):"disconnected"===i.event&&(!(s=i.error).statusCode||!s.code||s.statusCode>=500||Object.values(ri).includes(s.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:i.error}),n(!0))):(this.errorReason=i.error,ot(this.realtime.auth.o(null,null),i=>{i?this.actOnErrorFromAuthorize(i):this.tryATransport(t,e,n)})))):(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+e+"; setting pending"),this.setTransportPending(r,t),void n(null,r))})}setTransportPending(t,e){var n=e.mode;S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+t+"; mode = "+n),this.pendingTransport=t,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),t.once("connected",(e,i,r)=>{this.activateTransport(e,t,i,r),"recover"===n&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});var i=this;t.on(["disconnected","closed","failed"],function(e){i.deactivateTransport(t,this.event,e)}),this.emit("transport.pending",t)}activateTransport(t,e,n,i){S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+e),t&&S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+t),n&&S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+n),i&&S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(i)),this.persistTransportPreference(e);var r=this.state,s=this.states.connected.state;if(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+r.state),r.state==this.states.closing.state||r.state==this.states.closed.state||r.state==this.states.failed.state)return S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),e.disconnect(),!1;if(delete this.pendingTransport,!e.isConnected)return S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+e+" since it appears to no longer be connected"),!1;var a=this.activeProtocol;this.activeProtocol=new ni(e),this.host=e.params.host;var o=i.connectionKey;if(o&&this.connectionKey!=o&&this.setConnection(n,i,!!t),this.onConnectionDetailsUpdate(i,e),w.Config.nextTick(()=>{e.on("connected",(t,n,i)=>{this.onConnectionDetailsUpdate(i,e),this.emit("update",new ii(s,s,null,t))})}),r.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new ii(s,s,null,t))):(this.notifyState({state:"connected",error:t}),this.errorReason=this.realtime.connection.errorReason=t||null),this.emit("transport.active",e),a)if(a.messageQueue.count()>0&&S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+a.transport.shortName+", new one is "+e.shortName+") finishing with "+a.messageQueue.count()+" messages still pending"),a.transport===e){var h="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+e.shortName+"; stack = "+(new Error).stack;S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.activateTransport()",h)}else a.finish();return!0}deactivateTransport(t,e,n){var i=this.activeProtocol,r=i&&i.getTransport()===t,s=t===this.pendingTransport,a=this.noTransportsScheduledForActivation();if(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+t),S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+e+(r?"; was active":s?"; was pending":"")+(a?"":"; another transport is scheduled for activation")),n&&n.message&&S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+n.message),r&&(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(i.getPendingMessages()),i.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",t),r&&a||r&&"failed"===e||"closed"===e||null===i&&s){if("disconnected"===e&&n&&n.statusCode>500&&this.domains.length>1)return this.unpersistTransportPreference(),this.forceFallbackHost=!0,void this.notifyState({state:e,error:n,retryImmediately:!0});var o="failed"===e&&Gt.isTokenErr(n)?"disconnected":e;this.notifyState({state:o,error:n})}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(t,e,n){var i=this.connectionId;(i&&i!==t||!i&&n)&&(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==t&&S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=t,this.realtime.connection.key=this.connectionKey=e.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(this.lastActivity&&this.connectionId){var t=Date.now()-this.lastActivity;t>this.connectionStateTtl+this.maxIdleInterval&&(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+t+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}}persistConnection(){if(li()){var t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:ci.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var t;return null==(t=this.activeProtocol)?void 0:t.getTransport().format}getError(){if(this.errorReason){var t=M.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,e;return null==(e=(t=si)[this.state.state])?void 0:e.call(t)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(t){var e="Connection state",n=t.current+(t.reason?"; reason: "+t.reason:"");"failed"===t.current?S.logAction(this.logger,S.LOG_ERROR,e,n):S.logAction(this.logger,S.LOG_MAJOR,e,n),S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+t.current+"; reason = "+(t.reason&&t.reason.message));var i=this.state=this.states[t.current];t.reason&&(this.errorReason=t.reason,this.realtime.connection.errorReason=t.reason),(i.terminal||"suspended"===i.state)&&this.clearConnection(),this.emit("connectionstate",t)}startTransitionTimer(t){S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+t.state),this.transitionTimer&&(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager "+t.state+" timer expired","requesting new state: "+t.failState),this.notifyState({state:t.failState}))},t.retryDelay)}cancelTransitionTimer(){S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(t){"disconnected"!==t&&"suspended"!==t&&"connecting"!==t&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(t){this.retryTimer=setTimeout(()=>{S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{S.logAction(this.logger,S.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&ot(this.realtime.http.checkConnectivity(),(t,e)=>{t||!e?(S.logAction(this.logger,S.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new x("Unable to connect (network unreachable)",80003,404)})):S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(t){this.webSocketGiveUpTimer=setTimeout(()=>{var e,n;this.wsCheckResult||(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,null==(e=this.proposedTransport)||e.dispose(),null==(n=this.pendingTransport)||n.dispose(),this.connectBase(t,++this.connectCounter)):S.logAction(this.logger,S.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(t){var e,n,i=t.state,r="disconnected"===i&&(this.state===this.states.connected||t.retryImmediately||this.state===this.states.connecting&&t.error&&Gt.isTokenErr(t.error)&&!(this.errorReason&&Gt.isTokenErr(this.errorReason)));if(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+i+(r?"; will retry connection immediately":"")),i!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(t.state),"suspended"!==i&&"connected"!==i||(this.disconnectedRetryCount=0),!this.state.terminal)){var s=this.states[t.state],a=s.retryDelay;"disconnected"===s.state&&(this.disconnectedRetryCount++,a=vt(s.retryDelay,this.disconnectedRetryCount));var o=new ii(this.state.state,s.state,a,t.error||(null==(n=(e=si)[s.state])?void 0:n.call(e)));if(r){var h=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},c=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;c&&c<1e3?(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+c+"ms ago, waiting another "+(1e3-c)+"ms before trying again"),setTimeout(h,1e3-c)):w.Config.nextTick(h)}else"disconnected"!==i&&"suspended"!==i||this.startRetryTimer(a);("disconnected"===i&&!r||"suspended"===i||s.terminal)&&w.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=i||this.activeProtocol||S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(o),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(i,o.reason),this.failQueuedMessages(o.reason))}}requestState(t){var e,n,i=t.state;if(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+i+"; current state: "+this.state.state),i!=this.state.state&&(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(i),!("connecting"==i&&"connected"==this.state.state||"closing"==i&&"closed"==this.state.state))){var r=this.states[i],s=new ii(this.state.state,r.state,null,t.error||(null==(n=(e=si)[r.state])?void 0:n.call(e)));this.enactStateChange(s),"connecting"==i&&w.Config.nextTick(()=>{this.startConnect()}),"closing"==i&&this.closeImpl()}}startConnect(){if(this.state===this.states.connecting){var t=this.realtime.auth,e=++this.connectCounter,n=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(t=>{if("recover"===t.mode&&t.options.recover){var n=vi(t.options.recover);n&&this.realtime.channels.recoverChannels(n.channelSerials)}e===this.connectCounter&&this.connectImpl(t,e)})};if(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),"basic"===t.method)n();else{var i=t=>{e===this.connectCounter&&(t?this.actOnErrorFromAuthorize(t):n())};this.errorReason&&Gt.isTokenErr(this.errorReason)?ot(t.o(null,null),i):ot(t.h(!1),i)}}else S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state)}connectImpl(t,e){var n=this.state.state;if(n===this.states.connecting.state){var i=this.getTransportPreference();i&&i===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(t,++this.connectCounter))}).catch(di),i&&i===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(t,e):this.connectWs(t,e)}else S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+n)}connectWs(t,e){S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(t),this.tryTransportWithFallbacks("web_socket",t,!0,e,()=>!1!==this.wsCheckResult&&!this.abandonedWebSocket)}connectBase(t,e){S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,t,!1,e,()=>!0):this.notifyState({state:"disconnected",error:new x("No transports left to try",8e4,404)})}tryTransportWithFallbacks(t,e,n,i,r){S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",t);var s=t=>{this.notifyState({state:this.states.connecting.failState,error:t})},a=this.domains.slice(),o=(t,e)=>{i===this.connectCounter&&(r()?e||t||c():e&&e.dispose())},h=a.shift();if(h){e.host=h;var c=()=>{a.length?this.realtime.http.checkConnectivity?ot(this.realtime.http.checkConnectivity(),(n,h)=>{i===this.connectCounter&&r()&&(n?s(n):h?(e.host=Q(a),this.tryATransport(e,t,o)):s(new x("Unable to connect (network unreachable)",80003,404)))}):s(new M("Internal error: Http.checkConnectivity not set",null,500)):s(new x("Unable to connect (and no more fallback hosts to try)",80003,404))};if(this.forceFallbackHost&&a.length)return this.forceFallbackHost=!1,void c();this.tryATransport(e,t,o)}else s(new x("Unable to connect (no available host)",80003,404))}closeImpl(){S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(t,e){var n;switch(this.state.state){case"connected":S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");var i=null==(n=this.activeProtocol)?void 0:n.getTransport();i&&i.onAuthUpdated&&i.onAuthUpdated(t);var r=Hn({action:ee.AUTH,auth:{accessToken:t.token}});this.send(r);var s=()=>{this.off(a),e(null,t)},a=t=>{"failed"===t.current&&(this.off(s),this.off(a),e(t.reason||this.getStateError()))};this.once("connectiondetails",s),this.on("connectionstate",a);break;case"connecting":S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");var o=n=>{switch(n.current){case"connected":this.off(o),e(null,t);break;case"failed":case"closed":case"suspended":this.off(o),e(n.reason||this.getStateError())}};this.on("connectionstate",o),"connecting"===this.state.state?this.startConnect():this.requestState({state:"connecting"})}}disconnectAllTransports(){S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(t,e,n){n=n||di;var i=this.state;if(i.sendEvents)return S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.send()","sending event"),void this.sendImpl(new ei(t,n));if(!e||!i.queueEvents){var r="rejecting event, queueEvent was "+e+", state was "+i.state;return S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.send()",r),void n(this.errorReason||new x(r,9e4,400))}this.logger.shouldLog(S.LOG_MICRO)&&S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+Vn(t,this.realtime.B,this.realtime.R,this.realtime.Y)),this.queue(t,n)}sendImpl(t){var e=t.message;t.ackRequired&&!t.sendAttempted&&(e.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(t){S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+t.stack)}}queue(t,e){S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new ei(t,e))}sendQueuedMessages(){var t;for(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");t=this.queuedMessages.shift();)this.sendImpl(t)}queuePendingMessages(t){t&&t.length&&(S.logAction(this.logger,S.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+t.length+" pending messages"),this.queuedMessages.prepend(t))}failQueuedMessages(t){var e=this.queuedMessages.count();e>0&&(S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+e+" queued messages, err = "+et(t)),this.queuedMessages.completeAllMessages(t))}onChannelMessage(t,e){this.pendingChannelMessagesState.queue.push({message:t,transport:e}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;var t=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(t.message).catch(t=>{S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",t)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}processChannelMessage(t){var e=this;return o(function*(){yield e.realtime.channels.processChannelMessage(t)})()}ping(){var t=this;return o(function*(){var e;if("connected"!==t.state.state)throw new x("Unable to ping service; not connected",4e4,400);var n=null==(e=t.activeProtocol)?void 0:e.getTransport();if(!n)throw t.getStateError();S.logAction(t.logger,S.LOG_MINOR,"ConnectionManager.ping()","transport = "+n);var i=Date.now(),r=rt();return kt(new Promise(t=>{var e=s=>{s===r&&(n.off("heartbeat",e),t(Date.now()-i))};n.on("heartbeat",e),n.ping(r)}),t.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")})()}abort(t){this.activeProtocol.getTransport().fail(t)}getTransportPreference(){var t,e;return this.transportPreference||ui()&&(null==(e=null==(t=w.WebStorage)?void 0:t.get)?void 0:e.call(t,fi))}persistTransportPreference(t){var e,n;this.transportPreference=t.shortName,ui()&&(null==(n=null==(e=w.WebStorage)?void 0:e.set)||n.call(e,fi,t.shortName))}unpersistTransportPreference(){var t,e;this.transportPreference=null,ui()&&(null==(e=null==(t=w.WebStorage)?void 0:t.remove)||e.call(t,fi))}actOnErrorFromAuthorize(t){if(40171===t.code)this.notifyState({state:"failed",error:t});else if(40102===t.code)this.notifyState({state:"failed",error:t});else if(t.statusCode===Vt.Forbidden){var e="Client configured authentication provider returned 403; failing the connection";S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",e),this.notifyState({state:"failed",error:new x(e,80019,403,t)})}else{var n="Client configured authentication provider request failed";S.logAction(this.logger,S.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",n),this.notifyState({state:this.state.failState,error:new x(n,80019,401,t)})}}onConnectionDetailsUpdate(t,e){if(t){this.connectionDetails=t,t.maxMessageSize&&(this.options.maxMessageSize=t.maxMessageSize);var n=t.clientId;if(n){var i=this.realtime.auth.m(n);if(i)return S.logAction(this.logger,S.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",i.message),void e.fail(i)}var r=t.connectionStateTtl;r&&(this.connectionStateTtl=r),this.maxIdleInterval=t.maxIdleInterval,this.emit("connectiondetails",t)}}checkWsConnectivity(){var t=this.options.wsConnectivityCheckUrl||Dt.wsConnectivityCheckUrl,e=new w.Config.WebSocket(t);return new Promise((t,n)=>{var i=!1;e.onopen=()=>{i||(i=!0,t(),e.close())},e.onclose=e.onerror=()=>{i||(i=!0,n())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var t,e;return li()&&(null==(e=null==(t=w.WebStorage)?void 0:t.getSession)?void 0:e.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var e,n;return li()&&(null==(n=null==(e=w.WebStorage)?void 0:e.setSession)?void 0:n.call(e,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,e;return li()&&(null==(e=null==(t=w.WebStorage)?void 0:t.removeSession)?void 0:e.call(t,this.sessionRecoveryName()))}},yi=class extends te{constructor(t,e){super(t.logger),this.whenState=t=>te.prototype.whenState.call(this,t,this.state),this.ably=t,this.connectionManager=new gi(t,e),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",t=>{var e=this.state=t.current;w.Config.nextTick(()=>{this.emit(e,t)})}),this.connectionManager.on("update",t=>{w.Config.nextTick(()=>{this.emit("update",t)})})}connect(){S.logAction(this.logger,S.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}ping(){var t=this;return o(function*(){return S.logAction(t.logger,S.LOG_MINOR,"Connection.ping()",""),t.connectionManager.ping()})()}close(){S.logAction(this.logger,S.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()}},mi=class t extends Se{constructor(e){var n,i,r,s;if(super(Dt.objectifyOptions(e,!1,"BaseRealtime",S.defaultLogger)),S.logAction(this.logger,S.LOG_MINOR,"Realtime()",""),"string"==typeof EdgeRuntime)throw new x('Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === \'string\')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.',4e4,400);this.Z=t.transportImplementationsFromPlugins(this.options.plugins),this.B=null!=(i=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?i:null,this.Y=null!=(s=null==(r=this.options.plugins)?void 0:r.LiveObjects)?s:null,this.connection=new yi(this,this.options),this.tt=new bi(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(t){var e={};return(null==t?void 0:t.WebSocketTransport)&&(e[Xn.WebSocket]=t.WebSocketTransport),(null==t?void 0:t.XHRPolling)&&(e[Xn.XhrPolling]=t.XHRPolling),e}get channels(){return this.tt}get clientId(){return this.auth.clientId}connect(){S.logAction(this.logger,S.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){S.logAction(this.logger,S.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};mi.EventEmitter=te;var wi=mi,bi=class extends te{constructor(t){super(t.logger),this.realtime=t,this.all=Object.create(null),t.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){var t={};for(var e of L(this.all,!0)){var n=this.all[e];n.properties.channelSerial&&(t[e]=n.properties.channelSerial)}return t}recoverChannels(t){for(var e of L(t,!0))this.get(e).properties.channelSerial=t[e]}processChannelMessage(t){var e=this;return o(function*(){var n=t.channel;if(void 0!==n){var i=e.all[n];i?yield i.processMessage(t):S.logAction(e.logger,S.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n)}else S.logAction(e.logger,S.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+t.action)})()}onTransportActive(){for(var t in this.all){var e=this.all[t];"attaching"===e.state||"detaching"===e.state?e.checkPendingState():"suspended"===e.state?e.$(!1,null):"attached"===e.state&&e.requestState("attaching")}}propogateConnectionInterruption(t,e){var n=["attaching","attached","detaching","suspended"],i={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"}[t];for(var r in this.all){var s=this.all[r];n.includes(s.state)&&s.notifyState(i,e)}}get(t,e){t=String(t);var n=this.all[t];if(n){if(e){if(n.J(e,n.channelOptions))throw new x("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);n.setOptions(e)}}else n=this.all[t]=new Kn(this.realtime,t,e);return n}getDerived(t,e,n){if(e.filter){var i=mt(e.filter),r=yt(t);t="[filter="+i+r.qualifierParam+"]"+r.channelName}return this.get(t,n)}release(t){t=String(t);var e=this.all[t];if(e){var n=e.getReleaseErr();if(n)throw n;delete this.all[t]}}},Ci=wi;function ki(t,e){if(t.isSynthesized()||e.isSynthesized())return t.timestamp>=e.timestamp;var n=t.parseId(),i=e.parseId();return n.msgSerial===i.msgSerial?n.index>i.index:n.msgSerial>i.msgSerial}var Ti=class extends te{constructor(t,e,n){void 0===n&&(n=ki),super(t.logger),this.presence=t,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=e,this.newerThan=n}get(t){return this.map[t]}getClient(t){var e=this.map,n=[];for(var i in e){var r=e[i];r.clientId==t&&"absent"!=r.action&&n.push(r)}return n}list(t){var e=this.map,n=t&&t.clientId,i=t&&t.connectionId,r=[];for(var s in e){var a=e[s];"absent"!==a.action&&(n&&n!=a.clientId||i&&i!=a.connectionId||r.push(a))}return r}put(t){"enter"!==t.action&&"update"!==t.action||((t=Ke.fromValues(t)).action="present");var e=this.map,n=this.memberKey(t);this.residualMembers&&delete this.residualMembers[n];var i=e[n];return!(i&&!this.newerThan(t,i)||(e[n]=t,0))}values(){var t=this.map,e=[];for(var n in t){var i=t[n];"absent"!=i.action&&e.push(i)}return e}remove(t){var e=this.map,n=this.memberKey(t),i=e[n];return!(i&&!this.newerThan(t,i)||(this.syncInProgress?((t=Ke.fromValues(t)).action="absent",e[n]=t):delete e[n],!i))}startSync(){var t=this.map,e=this.syncInProgress;S.logAction(this.logger,S.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+e),this.syncInProgress||(this.residualMembers=P(t),this.setInProgress(!0))}endSync(){var t=this.map,e=this.syncInProgress;if(S.logAction(this.logger,S.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+e),e){for(var n in t)"absent"===t[n].action&&delete t[n];for(var i in this.presence.et(F(this.residualMembers)),this.residualMembers)delete t[i];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}waitSync(){var t=this;return o(function*(){var e=t.syncInProgress;S.logAction(t.logger,S.LOG_MINOR,"PresenceMap.waitSync()","channel = "+t.presence.channel.name+"; syncInProgress = "+e),e&&(yield t.once("sync"))})()}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(t){S.logAction(this.logger,S.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+t),this.syncInProgress=t,this.presence.syncComplete=!t}};function Si(t){var e=t.channel.client,n=e.auth.clientId;return(!n||"*"===n)&&"connected"===e.connection.state}var Ai=class extends te{constructor(t){super(t.logger),this.channel=t,this.syncComplete=!1,this.members=new Ti(this,t=>t.clientId+":"+t.connectionId),this.nt=new Ti(this,t=>t.clientId),this.subscriptions=new te(this.logger),this.pendingPresence=[]}enter(t){var e=this;return o(function*(){if(Si(e))throw new x("clientId must be specified to enter a presence channel",40012,400);return e.it(void 0,void 0,t,"enter")})()}update(t){var e=this;return o(function*(){if(Si(e))throw new x("clientId must be specified to update presence data",40012,400);return e.it(void 0,void 0,t,"update")})()}enterClient(t,e){var n=this;return o(function*(){return n.it(void 0,t,e,"enter")})()}updateClient(t,e){var n=this;return o(function*(){return n.it(void 0,t,e,"update")})()}it(t,e,n,i){var r=this;return o(function*(){var s=r.channel;if(!s.connectionManager.activeState())throw s.connectionManager.getError();S.logAction(r.logger,S.LOG_MICRO,"RealtimePresence."+i+"Client()","channel = "+s.name+", id = "+t+", client = "+(e||"(implicit) "+r.channel.client.auth.clientId));var a=Ke.fromData(n);a.action=i,t&&(a.id=t),e&&(a.clientId=e);var o=yield a.encode(s.channelOptions);switch(s.state){case"attached":return s.sendPresence([o]);case"initialized":case"detached":s.attach();case"attaching":return new Promise((t,e)=>{r.pendingPresence.push({presence:o,callback:n=>n?e(n):t()})});default:var h=new M("Unable to "+i+" presence channel while in "+s.state+" state",90001);throw h.code=90001,h}})()}leave(t){var e=this;return o(function*(){if(Si(e))throw new x("clientId must have been specified to enter or leave a presence channel",40012,400);return e.leaveClient(void 0,t)})()}leaveClient(t,e){var n=this;return o(function*(){var i=n.channel;if(!i.connectionManager.activeState())throw i.connectionManager.getError();S.logAction(n.logger,S.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+n.channel.name+", client = "+t);var r=Ke.fromData(e);r.action="leave",t&&(r.clientId=t);var s=yield r.encode(i.channelOptions);switch(i.state){case"attached":return i.sendPresence([s]);case"attaching":return new Promise((t,e)=>{n.pendingPresence.push({presence:s,callback:n=>n?e(n):t()})});case"initialized":case"failed":throw new M("Unable to leave presence channel (incompatible state)",90001);default:throw i.invalidStateError()}})()}get(t){var e=this;return o(function*(){var n=!t||!("waitForSync"in t)||t.waitForSync;function i(e){return t?e.list(t):e.values()}if("suspended"===e.channel.state){if(n)throw x.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return i(e.members)}yield e.channel.ensureAttached();var r=e.members;return n&&(yield r.waitSync()),i(e.members)})()}history(t){var e=this;return o(function*(){S.logAction(e.logger,S.LOG_MICRO,"RealtimePresence.history()","channel = "+e.name);var n=e.channel.client.rest.presenceMixin;if(t&&t.untilAttach){if("attached"!==e.channel.state)throw new x("option untilAttach requires the channel to be attached, was: "+e.channel.state,4e4,400);delete t.untilAttach,t.from_serial=e.channel.properties.attachSerial}return n.history(e,t)})()}setPresence(t,e,n){var i,r;S.logAction(this.logger,S.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+t.length+" participants; syncChannelSerial = "+n);var s=this.members,a=this.nt,o=[],h=this.channel.connectionManager.connectionId;for(var c of(e&&(this.members.startSync(),n&&(r=n.match(/^[\w-]+:(.*)$/))&&(i=r[1])),t))switch(c.action){case"leave":s.remove(c)&&o.push(c),c.connectionId!==h||c.isSynthesized()||a.remove(c);break;case"enter":case"present":case"update":s.put(c)&&o.push(c),c.connectionId===h&&a.put(c)}e&&!i&&(s.endSync(),this.channel.syncChannelSerial=null);for(var u=0;u<o.length;u++){var l=o[u];this.subscriptions.emit(l.action,l)}}onAttached(t){S.logAction(this.logger,S.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+t),t?this.members.startSync():(this.et(this.members.values()),this.members.clear()),this.rt();var e=this.pendingPresence,n=e.length;if(n){this.pendingPresence=[];var i=[],r=qt.create(this.logger);S.logAction(this.logger,S.LOG_MICRO,"RealtimePresence.onAttached","sending "+n+" queued presence messages");for(var s=0;s<n;s++){var a=e[s];i.push(a.presence),r.push(a.callback)}this.channel.sendPresence(i).then(()=>r()).catch(t=>r(t))}}actOnChannelState(t,e,n){switch(t){case"attached":this.onAttached(e);break;case"detached":case"failed":this.st(),this.members.clear();case"suspended":this.failPendingPresence(n)}}failPendingPresence(t){if(this.pendingPresence.length){S.logAction(this.logger,S.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+et(t));for(var e=0;e<this.pendingPresence.length;e++)try{this.pendingPresence[e].callback(t)}catch(t){}this.pendingPresence=[]}}st(){this.nt.clear()}rt(){var t=this.nt,e=this.channel.connectionManager.connectionId;for(var n in t.map){var i=t.map[n];S.logAction(this.logger,S.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+i.clientId+'" into the presence set');var r=i.connectionId===e?i.id:void 0;this.it(r,i.clientId,i.data,"enter").catch(t=>{var e=new x("Presence auto re-enter failed",91004,400,t);S.logAction(this.logger,S.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+et(t));var n=new Fn(this.channel.state,this.channel.state,!0,!1,e);this.channel.emit("update",n)})}}et(t){var e=this.subscriptions;t.forEach(function(t){var n=Ke.fromValues({action:"leave",connectionId:t.connectionId,clientId:t.clientId,data:t.data,encoding:t.encoding,timestamp:Date.now()});e.emit("leave",n)})}subscribe(){var t=arguments,e=this;return o(function*(){for(var n=t.length,i=new Array(n),r=0;r<n;r++)i[r]=t[r];var s=Kn.processListenerArgs(i),a=s[0],o=s[1],h=e.channel;if("failed"===h.state)throw x.fromValues(h.invalidStateError());e.subscriptions.on(a,o),!1!==h.channelOptions.attachOnSubscribe&&(yield h.attach())})()}unsubscribe(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var i=Kn.processListenerArgs(e),r=i[0],s=i[1];this.subscriptions.off(r,s)}},Ei=Xn.WebSocket,xi=class extends hi{constructor(t,e,n){super(t,e,n),this.shortName=Ei,n.heartbeats=w.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!w.Config.WebSocket}createWebSocket(t,e){return this.uri=t+X(e),new w.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){S.logAction(this.logger,S.LOG_MINOR,"WebSocketTransport.connect()","starting"),hi.prototype.connect.call(this);var t=this,e=this.params,n=e.options,i=(n.tls?"wss://":"ws://")+this.wsHost+":"+Dt.getPort(n)+"/";S.logAction(this.logger,S.LOG_MINOR,"WebSocketTransport.connect()","uri: "+i),ot(this.auth.getAuthParams(),function(n,r){if(!t.isDisposed){var s="";for(var a in r)s+=" "+a+": "+r[a]+";";if(S.logAction(t.logger,S.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+s+" err: "+n),n)t.disconnect(n);else{var o=e.getConnectParams(r);try{var h=t.wsConnection=t.createWebSocket(i,o);h.binaryType=w.Config.binaryType,h.onopen=function(){t.onWsOpen()},h.onclose=function(e){t.onWsClose(e)},h.onmessage=function(e){t.onWsData(e.data)},h.onerror=function(e){t.onWsError(e)},h.on&&h.on("ping",function(){t.onActivity()})}catch(e){S.logAction(t.logger,S.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(e.stack||e.message)),t.disconnect(e)}}}})}send(t){var e=this.wsConnection;if(e)try{e.send(Dn(t,this.connectionManager.realtime.S,this.params.format))}catch(t){var n="Exception from ws connection when trying to send: "+et(t);S.logAction(this.logger,S.LOG_ERROR,"WebSocketTransport.send()",n),this.finish("disconnected",new x(n,5e4,500))}else S.logAction(this.logger,S.LOG_ERROR,"WebSocketTransport.send()","No socket connection")}onWsData(t){S.logAction(this.logger,S.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+t.length+"; type = "+typeof t);try{this.onProtocolMessage((e=t,n=this.connectionManager.realtime.S,i=this.connectionManager.realtime.B,r=this.connectionManager.realtime.R,s=this.connectionManager.realtime.Y,a=this.format,Bn(ht(e,n,a),i,r,s)))}catch(t){S.logAction(this.logger,S.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+t.stack)}var e,n,i,r,s,a}onWsOpen(){S.logAction(this.logger,S.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(t){var e,n;if("object"==typeof t?(n=t.code,e=t.wasClean||1e3===n):e=1e3==(n=t),delete this.wsConnection,e){S.logAction(this.logger,S.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");var i=new x("Websocket closed",80003,400);this.finish("disconnected",i)}else{var r="Unclean disconnection of WebSocket ; code = "+n,s=new x(r,80003,400);S.logAction(this.logger,S.LOG_MINOR,"WebSocketTransport.onWsClose()",r),this.finish("disconnected",s)}this.emit("disposed")}onWsError(t){S.logAction(this.logger,S.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+t.message),w.Config.nextTick(()=>{this.disconnect(Error(t.message))})}dispose(){S.logAction(this.logger,S.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;var t=this.wsConnection;t&&(t.onmessage=function(){},delete this.wsConnection,w.Config.nextTick(()=>{if(S.logAction(this.logger,S.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!t)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");t.close()}))}},Mi=class{static subscribeFilter(t,e,n){var i=t=>{var i,r,s,a,o,h,c={name:t.name,refTimeserial:null==(r=null==(i=t.extras)?void 0:i.ref)?void 0:r.timeserial,refType:null==(a=null==(s=t.extras)?void 0:s.ref)?void 0:a.type,isRef:!!(null==(h=null==(o=t.extras)?void 0:o.ref)?void 0:h.timeserial),clientId:t.clientId};Object.entries(e).find(t=>{var[e,n]=t;return void 0!==n&&c[e]!==n})||n(t)};this.addFilteredSubscription(t,e,n,i),t.subscriptions.on(i)}static addFilteredSubscription(t,e,n,i){var r;if(t.filteredSubscriptions||(t.filteredSubscriptions=new Map),t.filteredSubscriptions.has(n)){var s=t.filteredSubscriptions.get(n);s.set(e,(null==(r=null==s?void 0:s.get(e))?void 0:r.concat(i))||[i])}else t.filteredSubscriptions.set(n,new Map([[e,[i]]]))}static getAndDeleteFilteredSubscriptions(t,e,n){if(!t.filteredSubscriptions)return[];if(!n&&e)return Array.from(t.filteredSubscriptions.entries()).map(n=>{var i,[r,s]=n,a=s.get(e);return s.delete(e),0===s.size&&(null==(i=t.filteredSubscriptions)||i.delete(r)),a}).reduce((t,e)=>e?t.concat(...e):t,[]);if(!n||!t.filteredSubscriptions.has(n))return[];var i=t.filteredSubscriptions.get(n);if(!e){var r=Array.from(i.values()).reduce((t,e)=>t.concat(...e),[]);return t.filteredSubscriptions.delete(n),r}var s=i.get(e);return i.delete(e),s||[]}},Ri=class t extends Ci{constructor(e){var n,i=t.S;if(!i)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(Dt.objectifyOptions(e,!0,"Realtime",S.defaultLogger,p(f({},bn),{Crypto:null!=(n=t.Crypto)?n:void 0,MsgPack:i,RealtimePresence:{RealtimePresence:Ai,PresenceMessage:Ke,WirePresenceMessage:$e},Annotations:{Annotation:On,WireAnnotation:Pn,RealtimeAnnotations:Gn,RestAnnotations:Nn},WebSocketTransport:xi,MessageInteractions:Mi})))}static get Crypto(){if(null===this.M)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this.M}static set Crypto(t){this.M=t}};Ri.Utils=A,Ri.ConnectionManager=gi,Ri.ProtocolMessage=Ln,Ri.M=null,Ri.Message=Cn,Ri.PresenceMessage=kn,Ri.Annotation=In,Ri.S=null,Ri.X=Yt,Ri.ot=Ti,Ri.ht=we;var Pi=Ri,Oi=Uint8Array,Ii=Uint32Array,ji=Math.pow,_i=new Ii(8),Ui=[],Ni=new Ii(64);function Di(t){return(t-(0|t))*ji(2,32)|0}for(var qi,Bi,Wi=2,Hi=0;Hi<64;){for(qi=!0,Bi=2;Bi<=Wi/2;Bi++)Wi%Bi===0&&(qi=!1);qi&&(Hi<8&&(_i[Hi]=Di(ji(Wi,.5))),Ui[Hi]=Di(ji(Wi,1/3)),Hi++),Wi++}var Vi=!!new Oi(new Ii([1]).buffer)[0];function zi(t){return Vi?t>>>24|(t>>>16&255)<<8|(65280&t)<<8|t<<24:t}function Li(t,e){return t>>>e|t<<32-e}function Fi(t){var e,n=_i.slice(),i=t.length,r=8*i,s=512-(r+64)%512-1+r+65,a=new Oi(s/8),o=new Ii(a.buffer);a.set(t,0),a[i]=128,o[o.length-1]=zi(r);for(var h=0;h<s/32;h+=16){var c=n.slice();for(e=0;e<64;e++){var u;if(e<16)u=zi(o[h+e]);else{var l=Ni[e-15],d=Ni[e-2];u=Ni[e-7]+Ni[e-16]+(Li(l,7)^Li(l,18)^l>>>3)+(Li(d,17)^Li(d,19)^d>>>10)}Ni[e]=u|=0;for(var f=(Li(c[4],6)^Li(c[4],11)^Li(c[4],25))+(c[4]&c[5]^~c[4]&c[6])+c[7]+u+Ui[e],v=(Li(c[0],2)^Li(c[0],13)^Li(c[0],22))+(c[0]&c[1]^c[2]&(c[0]^c[1])),p=7;p>0;p--)c[p]=c[p-1];c[0]=f+v|0,c[4]=c[4]+f|0}for(e=0;e<8;e++)n[e]=n[e]+c[e]|0}return new Oi(new Ii(n.map(function(t){return zi(t)})).buffer)}var Ji,$i=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(t){for(var e,n,i,r,s="",a=this.base64CharSet,o=t.byteLength,h=o%3,c=o-h,u=0;u<c;u+=3)e=(258048&(r=t[u]<<16|t[u+1]<<8|t[u+2]))>>12,n=(4032&r)>>6,i=63&r,s+=a[(16515072&r)>>18]+a[e]+a[n]+a[i];return 1==h?(e=(3&(r=t[c]))<<4,s+=a[(252&r)>>2]+a[e]+"=="):2==h&&(e=(1008&(r=t[c]<<8|t[c+1]))>>4,n=(15&r)<<2,s+=a[(64512&r)>>10]+a[e]+a[n]+"="),s}base64ToArrayBuffer(t){for(var e=null==atob?void 0:atob(t),n=e.length,i=new Uint8Array(n),r=0;r<n;r++){var s=e.charCodeAt(r);i[r]=s}return this.toArrayBuffer(i)}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&&w.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((t,e)=>t+e.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");for(var e=new Uint8Array(t.length/2),n=0;n<e.length;n++)e[n]=parseInt(t.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(e)}utf8Encode(t){if(w.Config.TextEncoder){var e=(new w.Config.TextEncoder).encode(t);return this.toArrayBuffer(e)}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;var n=this.toArrayBuffer(t),i=this.toArrayBuffer(e);if(n.byteLength!=i.byteLength)return!1;for(var r=new Uint8Array(n),s=new Uint8Array(i),a=0;a<r.length;a++)if(r[a]!=s[a])return!1;return!0}byteLength(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:-1}arrayBufferViewToBuffer(t){return this.toArrayBuffer(t)}concat(t){var e=t.reduce((t,e)=>t+e.byteLength,0),n=new Uint8Array(e),i=0;for(var r of t){var s=this.toBuffer(r);n.set(s,i),i+=s.byteLength}return n.buffer}sha256(t){var e=Fi(this.toBuffer(t));return this.toArrayBuffer(e)}hmacSha256(t,e){var n=function(t,e){if(t.length>64&&(t=Fi(t)),t.length<64){var n=new Uint8Array(64);n.set(t,0),t=n}for(var i=new Uint8Array(64),r=new Uint8Array(64),s=0;s<64;s++)i[s]=54^t[s],r[s]=92^t[s];var a=new Uint8Array(e.length+64);a.set(i,0),a.set(e,64);var o=new Uint8Array(96);return o.set(r,0),o.set(Fi(a),64),Fi(o)}(this.toBuffer(e),this.toBuffer(t));return this.toArrayBuffer(n)}},Ki=(t=>(t[t.REQ_SEND=0]="REQ_SEND",t[t.REQ_RECV=1]="REQ_RECV",t[t.REQ_RECV_POLL=2]="REQ_RECV_POLL",t[t.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",t))(Ki||{}),Gi=Ki;function Qi(){return new x("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var Xi=(Ji=class{constructor(t){var e;this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this.client=null!=t?t:null;var n=(null==t?void 0:t.options.connectivityCheckUrl)||Dt.connectivityCheckUrl,i=null!=(e=null==t?void 0:t.options.connectivityCheckParams)?e:null,r=!(null==t?void 0:t.options.connectivityCheckUrl),s=f(f({},Xi.bundledRequestImplementations),null==t?void 0:t.T),a=s.XHRRequest,h=s.FetchRequest,c=!(!a&&!h);if(!c)throw Qi();w.Config.xhrSupported&&a?(this.supportsAuthHeaders=!0,this.Request=function(){var e=o(function*(e,n,i,r,s){return new Promise(o=>{var h,c=a.createRequest(n,i,r,s,Gi.REQ_SEND,null!=(h=t&&t.options.timeouts)?h:null,this.logger,e);c.once("complete",(t,e,n,i,r)=>o({error:t,body:e,headers:n,unpacked:i,statusCode:r})),c.exec()})});return function(t,n,i,r,s){return e.apply(this,arguments)}}(),(null==t?void 0:t.options.disableConnectivityCheck)?this.checkConnectivity=o(function*(){return!0}):this.checkConnectivity=o(function*(){var t;S.logAction(this.logger,S.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);var e,s=yield this.doUri(Wt.Get,n,null,null,i),a=!1;return a=r?!s.error&&"yes"==(null==(t=s.body)?void 0:t.replace(/\n/,"")):!s.error&&(e=s.statusCode)>=200&&e<400,S.logAction(this.logger,S.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+a),a})):w.Config.fetchSupported&&h?(this.supportsAuthHeaders=!0,this.Request=function(){var e=o(function*(e,n,i,r,s){return h(e,null!=t?t:null,n,i,r,s)});return function(t,n,i,r,s){return e.apply(this,arguments)}}(),(null==t?void 0:t.options.disableConnectivityCheck)?this.checkConnectivity=o(function*(){return!0}):this.checkConnectivity=o(function*(){var t;S.logAction(this.logger,S.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);var e=yield this.doUri(Wt.Get,n,null,null,null),i=!e.error&&"yes"==(null==(t=e.body)?void 0:t.replace(/\n/,""));return S.logAction(this.logger,S.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+i),i})):this.Request=o(function*(){return{error:c?new M("no supported HTTP transports available",null,400):Qi()}})}get logger(){var t,e;return null!=(e=null==(t=this.client)?void 0:t.logger)?e:S.defaultLogger}doUri(t,e,n,i,r){var s=this;return o(function*(){return s.Request?s.Request(t,e,n,r,i):{error:new M("Request invoked before assigned to",null,500)}})()}shouldFallback(t){var e=t.statusCode;return 408===e&&!t.code||400===e&&!t.code||e>=500&&e<=504}},Ji.methods=[Wt.Get,Wt.Delete,Wt.Post,Wt.Put,Wt.Patch],Ji.methodsWithoutBody=[Wt.Get,Wt.Delete],Ji.methodsWithBody=[Wt.Post,Wt.Put,Wt.Patch],Ji),Yi=Xi,Zi="ablyjs-storage-test",tr=void 0!==v?v:"undefined"!=typeof window?window:self,er=new class{constructor(){try{tr.sessionStorage.setItem(Zi,Zi),tr.sessionStorage.removeItem(Zi),this.sessionSupported=!0}catch(t){this.sessionSupported=!1}try{tr.localStorage.setItem(Zi,Zi),tr.localStorage.removeItem(Zi),this.localSupported=!0}catch(t){this.localSupported=!1}}get(t){return this.ct(t,!1)}getSession(t){return this.ct(t,!0)}remove(t){return this.ut(t,!1)}removeSession(t){return this.ut(t,!0)}set(t,e,n){return this.lt(t,e,n,!1)}setSession(t,e,n){return this.lt(t,e,n,!0)}lt(t,e,n,i){var r={value:e};return n&&(r.expires=Date.now()+n),this.storageInterface(i).setItem(t,JSON.stringify(r))}ct(t,e){if(e&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!e&&!this.localSupported)throw new Error("Local Storage not supported");var n=this.storageInterface(e).getItem(t);if(!n)return null;var i=JSON.parse(n);return i.expires&&i.expires<Date.now()?(this.storageInterface(e).removeItem(t),null):i.value}ut(t,e){return this.storageInterface(e).removeItem(t)}storageInterface(t){return t?tr.sessionStorage:tr.localStorage}},nr=pt(),ir="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||ir||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var rr,sr,ar={agent:"browser",logTimestamps:!0,userAgent:nr.navigator&&nr.navigator.userAgent.toString(),currentUrl:nr.location&&nr.location.href,binaryType:"arraybuffer",WebSocket:nr.WebSocket,fetchSupported:!!nr.fetch,xhrSupported:nr.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:(sr=nr.location,!nr.WebSocket||!sr||!sr.origin||sr.origin.indexOf("http")>-1),useProtocolHeartbeats:!0,supportsBinary:!!nr.TextDecoder,preferBinary:!1,ArrayBuffer:nr.ArrayBuffer,atob:nr.atob,nextTick:"function"==typeof nr.queueMicrotask?t=>nr.queueMicrotask(t):t=>Promise.resolve().then(t),addEventListener:nr.addEventListener,inspect:JSON.stringify,stringByteSize:function(t){return nr.TextDecoder&&(new nr.TextEncoder).encode(t).length||t.length},TextEncoder:nr.TextEncoder,TextDecoder:nr.TextDecoder,getRandomArrayBuffer:(rr=o(function*(t){var e=new Uint8Array(t);return nr.crypto.getRandomValues(e),e.buffer}),function(t){return rr.apply(this,arguments)}),isWebworker:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,push:{platform:"browser",formFactor:"desktop",storage:er}},or=ar;function hr(t){return function(t){return!!t.code&&!Gt.isTokenErr(t)&&(!![80015,80017,80030].includes(t.code)||t.code>=4e4&&t.code<5e4)}(t)?[Hn({action:ee.ERROR,error:t})]:[Hn({action:ee.DISCONNECTED,error:t})]}var cr=class extends hi{constructor(t,e,n){super(t,e,n,!0),this.onAuthUpdated=t=>{this.authParams={access_token:t.token}},this.stream=!("stream"in n)||n.stream,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){S.logAction(this.logger,S.LOG_MINOR,"CometTransport.connect()","starting"),hi.prototype.connect.call(this);var t=this.params,e=t.options,n=t.host||e.primaryDomain,i=Dt.getPort(e),r=e.tls?"https://":"http://";this.baseUri=r+n+":"+i+"/comet/";var s=this.baseUri+"connect";S.logAction(this.logger,S.LOG_MINOR,"CometTransport.connect()","uri: "+s),ot(this.auth.getAuthParams(),(t,e)=>{if(t)this.disconnect(t);else if(!this.isDisposed){this.authParams=e;var n=this.params.getConnectParams(e);"stream"in n&&(this.stream=n.stream),S.logAction(this.logger,S.LOG_MINOR,"CometTransport.connect()","connectParams:"+X(n));var i=!1,r=this.recvRequest=this.createRequest(s,null,n,null,this.stream?Gi.REQ_RECV_STREAM:Gi.REQ_RECV);r.on("data",t=>{this.recvRequest&&(i||(i=!0,this.emit("preconnect")),this.onData(t))}),r.on("complete",t=>{this.recvRequest||(t=t||new x("Request cancelled",80003,400)),this.recvRequest=null,i||t||(i=!0,this.emit("preconnect")),this.onActivity(),t?t.code?this.onData(hr(t)):this.disconnect(t):w.Config.nextTick(()=>{this.recv()})}),r.exec()}})}requestClose(){S.logAction(this.logger,S.LOG_MINOR,"CometTransport.requestClose()"),this.dt(!0)}requestDisconnect(){S.logAction(this.logger,S.LOG_MINOR,"CometTransport.requestDisconnect()"),this.dt(!1)}dt(t){var e=t?this.closeUri:this.disconnectUri;if(e){var n=this.createRequest(e,null,this.authParams,null,Gi.REQ_SEND);n.on("complete",e=>{e&&(S.logAction(this.logger,S.LOG_ERROR,"CometTransport.request"+(t?"Close()":"Disconnect()"),"request returned err = "+et(e)),this.finish("disconnected",e))}),n.exec()}}dispose(){S.logAction(this.logger,S.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(S.logAction(this.logger,S.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",si.disconnected()),w.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(t){var e;if(!this.isDisposed){var n=null==(e=t.connectionDetails)?void 0:e.connectionKey;hi.prototype.onConnect.call(this,t);var i=this.baseUri+n;S.logAction(this.logger,S.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+i),this.sendUri=i+"/send",this.recvUri=i+"/recv",this.closeUri=i+"/close",this.disconnectUri=i+"/disconnect"}}send(t){if(this.sendRequest)return this.pendingItems=this.pendingItems||[],void this.pendingItems.push(t);var e=this.pendingItems||[];e.push(t),this.pendingItems=null,this.sendItems(e)}sendAnyPending(){var t=this.pendingItems;t&&(this.pendingItems=null,this.sendItems(t))}sendItems(t){var e=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(t),Gi.REQ_SEND);e.on("complete",(t,e)=>{t&&S.logAction(this.logger,S.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+et(t)),this.sendRequest=null,t?t.code?this.onData(hr(t)):this.disconnect(t):(e&&this.onData(e),this.pendingItems&&w.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()}))}),e.exec()}recv(){if(!this.recvRequest&&this.isConnected){var t=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?Gi.REQ_RECV_STREAM:Gi.REQ_RECV_POLL);t.on("data",t=>{this.onData(t)}),t.on("complete",t=>{this.recvRequest=null,this.onActivity(),t?t.code?this.onData(hr(t)):this.disconnect(t):w.Config.nextTick(()=>{this.recv()})}),t.exec()}}onData(t){try{var e=this.decodeResponse(t);if(e&&e.length)for(var n=0;n<e.length;n++)this.onProtocolMessage(Bn(e[n],this.connectionManager.realtime.B,this.connectionManager.realtime.R,this.connectionManager.realtime.Y))}catch(t){S.logAction(this.logger,S.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+t.stack)}}encodeRequest(t){return JSON.stringify(t)}decodeResponse(t){return"string"==typeof t?JSON.parse(t):t}};function ur(t,e){if(function(t,e){return ut(L(e)).includes("x-ably-errorcode")}(0,e))return t.error&&x.fromValues(t.error)}var lr=function(){},dr=0,fr={},vr=class t extends te{constructor(t,e,n,i,r,s,a,o){super(a),(n=n||{}).rnd=rt(),this.uri=t+X(n),this.headers=e||{},this.body=i,this.method=o?o.toUpperCase():_(i)?"GET":"POST",this.requestMode=r,this.timeouts=s,this.timedOut=!1,this.requestComplete=!1,this.id=String(++dr),fr[this.id]=this}static createRequest(e,n,i,r,s,a,o,h){var c=a||Dt.TIMEOUTS;return new t(e,n,P(i),r,s,c,o,h)}complete(t,e,n,i,r){this.requestComplete||(this.requestComplete=!0,!t&&e&&this.emit("data",e),this.emit("complete",t,e,n,i,r),this.dispose())}abort(){this.dispose()}exec(){var t=this.headers,e=this.requestMode==Gi.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,n=this.timer=setTimeout(()=>{this.timedOut=!0,r.abort()},e),i=this.method,r=this.xhr=new XMLHttpRequest,s=t.accept,a=this.body,o="text";for(var h in s?0===s.indexOf("application/x-msgpack")&&(o="arraybuffer"):t.accept="application/json",a&&(t["content-type"]||(t["content-type"]="application/json")).indexOf("application/json")>-1&&"string"!=typeof a&&(a=JSON.stringify(a)),r.open(i,this.uri,!0),r.responseType=o,"authorization"in t&&(r.withCredentials=!0),t)r.setRequestHeader(h,t[h]);var c,u,l,d=(t,e,n,i)=>{var r,s=e+" (event type: "+t.type+")";(null==(r=null==this?void 0:this.xhr)?void 0:r.statusText)&&(s+=", current statusText is "+this.xhr.statusText),S.logAction(this.logger,S.LOG_ERROR,"Request.on"+t.type+"()",s),this.complete(new M(s,n,i))};r.onerror=t=>{d(t,"XHR error occurred",null,400)},r.onabort=t=>{this.timedOut?d(t,"Request aborted due to request timeout expiring",null,408):d(t,"Request cancelled",null,400)},r.ontimeout=t=>{d(t,"Request timed out",null,408)};var f=0,v=!1,p=()=>{clearTimeout(n),l=u<400,204!=u?c=this.requestMode==Gi.REQ_RECV_STREAM&&l&&function(t){return t.getResponseHeader&&(t.getResponseHeader("transfer-encoding")||!t.getResponseHeader("content-length"))}(r):this.complete(null,null,null,null,u)},g=()=>{var e;try{var n=function(t,e){return t.getResponseHeader&&t.getResponseHeader(e)}(r,"content-type");if(n?n.indexOf("application/json")>=0:"text"==r.responseType){var i="arraybuffer"===r.responseType?w.BufferUtils.utf8Decode(r.response):String(r.responseText);e=i.length?JSON.parse(i):i,v=!0}else e=r.response;void 0!==e.response?(u=e.statusCode,l=u<400,t=e.headers,e=e.response):t=function(t){for(var e=t.getAllResponseHeaders().trim().split("\r\n"),n={},i=0;i<e.length;i++){var r=e[i].split(":").map(t=>t.trim());n[r[0].toLowerCase()]=r[1]}return n}(r)}catch(t){return void this.complete(new M("Malformed response body from server: "+t.message,null,400))}if(l||Array.isArray(e))this.complete(null,e,t,v,u);else{var s=ur(e,t);s||(s=new M("Error response received from server: "+u+" body was: "+w.Config.inspect(e),null,u)),this.complete(s,e,t,v,u)}};function y(){for(var t,e,n=r.responseText,i=n.length-1;f<i&&(t=n.indexOf("\n",f))>-1;)e=n.slice(f,t),f=t+1,m(e)}var m=t=>{try{t=JSON.parse(t)}catch(t){return void this.complete(new M("Malformed response body from server: "+t.message,null,400))}this.emit("data",t)},b=()=>{y(),this.streamComplete=!0,w.Config.nextTick(()=>{this.complete()})};r.onreadystatechange=()=>{var t=r.readyState;t<3||0!==r.status&&(void 0===u&&(u=r.status,p()),3==t&&c?y():4==t&&(c?b():g()))},r.send(a)}dispose(){var t=this.xhr;if(t){t.onreadystatechange=t.onerror=t.onabort=t.ontimeout=lr,this.xhr=null;var e=this.timer;e&&(clearTimeout(e),this.timer=null),this.requestComplete||t.abort()}delete fr[this.id]}},pr=Xn.XhrPolling,gr={order:["xhr_polling"],bundledImplementations:{web_socket:xi,xhr_polling:class extends cr{constructor(t,e,n){super(t,e,n),this.shortName=pr,n.stream=!1,this.shortName=pr}static isAvailable(){return!(!w.Config.xhrSupported||!w.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(t,e,n,i,r){return vr.createRequest(t,e,n,i,r,this.timeouts,this.logger)}}}},yr={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[Xn.XhrPolling,Xn.WebSocket]};function mr(t,e,n){for(var i=(new TextEncoder).encode(n),r=0;r<i.length;r++)t.setUint8(e+r,i[r])}function wr(t,e,n){return(new TextDecoder).decode(t.buffer.slice(e,e+n))}function br(t){return(new TextEncoder).encode(t).length}var Cr=4294967296,kr=1/Cr,Tr=class{constructor(t,e){this.map=t=>{for(var e={},n=0;n<t;n++)e[this.parse()]=this.parse();return e},this.bin=t=>{var 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=>{var e=wr(this.view,this.offset,t);return this.offset+=t,e},this.array=t=>{for(var e=new Array(t),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=()=>{var t,e,n=this.view.getUint8(this.offset);if(!(128&n))return this.offset++,n;if(128==(240&n))return e=15&n,this.offset++,this.map(e);if(144==(240&n))return e=15&n,this.offset++,this.array(e);if(160==(224&n))return e=31&n,this.offset++,this.str(e);if(!(224&~n))return t=this.view.getInt8(this.offset),this.offset++,t;switch(n){case 192:return this.offset++,null;case 193:return void this.offset++;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return e=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(e);case 197:return e=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(e);case 198:return e=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(e);case 199:return e=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(e);case 200:return e=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(e);case 201:return e=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(e);case 202:return t=this.view.getFloat32(this.offset+1),this.offset+=5,t;case 203:return t=this.view.getFloat64(this.offset+1),this.offset+=9,t;case 204:return t=this.view.getUint8(this.offset+1),this.offset+=2,t;case 205:return t=this.view.getUint16(this.offset+1),this.offset+=3,t;case 206:return t=this.view.getUint32(this.offset+1),this.offset+=5,t;case 207:return t=function(t,e){return e=e||0,t.getUint32(e)*Cr+t.getUint32(e+4)}(this.view,this.offset+1),this.offset+=9,t;case 208:return t=this.view.getInt8(this.offset+1),this.offset+=2,t;case 209:return t=this.view.getInt16(this.offset+1),this.offset+=3,t;case 210:return t=this.view.getInt32(this.offset+1),this.offset+=5,t;case 211:return t=function(t,e){return e=e||0,t.getInt32(e)*Cr+t.getUint32(e+4)}(this.view,this.offset+1),this.offset+=9,t;case 212:return e=1,this.offset++,this.ext(e);case 213:return e=2,this.offset++,this.ext(e);case 214:return e=4,this.offset++,this.ext(e);case 215:return e=8,this.offset++,this.ext(e);case 216:return e=16,this.offset++,this.ext(e);case 217:return e=this.view.getUint8(this.offset+1),this.offset+=2,this.str(e);case 218:return e=this.view.getUint16(this.offset+1),this.offset+=3,this.str(e);case 219:return e=this.view.getUint32(this.offset+1),this.offset+=5,this.str(e);case 220:return e=this.view.getUint16(this.offset+1),this.offset+=3,this.array(e);case 221:return e=this.view.getUint32(this.offset+1),this.offset+=5,this.array(e);case 222:return e=this.view.getUint16(this.offset+1),this.offset+=3,this.map(e);case 223:return e=this.view.getUint32(this.offset+1),this.offset+=5,this.map(e)}throw new Error("Unknown type 0x"+n.toString(16))},this.offset=e||0,this.view=t}};function Sr(t,e){return Object.keys(t).filter(function(n){var i=t[n];return!(e&&null==i||"function"==typeof i&&!i.toJSON)})}function Ar(t,e,n,i){var r=typeof t;if("string"==typeof t){var s=br(t);if(s<32)return e.setUint8(n,160|s),mr(e,n+1,t),1+s;if(s<256)return e.setUint8(n,217),e.setUint8(n+1,s),mr(e,n+2,t),2+s;if(s<65536)return e.setUint8(n,218),e.setUint16(n+1,s),mr(e,n+3,t),3+s;if(s<4294967296)return e.setUint8(n,219),e.setUint32(n+1,s),mr(e,n+5,t),5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(t)&&(t=t.buffer),t instanceof ArrayBuffer){var a=t.byteLength;if(a<256)return e.setUint8(n,196),e.setUint8(n+1,a),new Uint8Array(e.buffer).set(new Uint8Array(t),n+2),2+a;if(a<65536)return e.setUint8(n,197),e.setUint16(n+1,a),new Uint8Array(e.buffer).set(new Uint8Array(t),n+3),3+a;if(a<4294967296)return e.setUint8(n,198),e.setUint32(n+1,a),new Uint8Array(e.buffer).set(new Uint8Array(t),n+5),5+a}if("number"==typeof t){if(Math.floor(t)!==t)return e.setUint8(n,203),e.setFloat64(n+1,t),9;if(t>=0){if(t<128)return e.setUint8(n,t),1;if(t<256)return e.setUint8(n,204),e.setUint8(n+1,t),2;if(t<65536)return e.setUint8(n,205),e.setUint16(n+1,t),3;if(t<4294967296)return e.setUint8(n,206),e.setUint32(n+1,t),5;if(t<0x10000000000000000)return e.setUint8(n,207),function(t,e,n){n<0x10000000000000000?(t.setUint32(e,Math.floor(n*kr)),t.setInt32(e+4,-1&n)):(t.setUint32(e,4294967295),t.setUint32(e+4,4294967295))}(e,n+1,t),9;throw new Error("Number too big 0x"+t.toString(16))}if(t>=-32)return e.setInt8(n,t),1;if(t>=-128)return e.setUint8(n,208),e.setInt8(n+1,t),2;if(t>=-32768)return e.setUint8(n,209),e.setInt16(n+1,t),3;if(t>=-2147483648)return e.setUint8(n,210),e.setInt32(n+1,t),5;if(t>=-0x8000000000000000)return e.setUint8(n,211),function(t,e,n){n<0x8000000000000000?(t.setInt32(e,Math.floor(n*kr)),t.setInt32(e+4,-1&n)):(t.setUint32(e,2147483647),t.setUint32(e+4,2147483647))}(e,n+1,t),9;throw new Error("Number too small -0x"+(-t).toString(16).substr(1))}if("undefined"===r)return i?0:(e.setUint8(n,212),e.setUint8(n+1,0),e.setUint8(n+2,0),3);if(null===t)return i?0:(e.setUint8(n,192),1);if("boolean"===r)return e.setUint8(n,t?195:194),1;if("function"==typeof t.toJSON)return Ar(t.toJSON(),e,n,i);if("object"===r){var o,h,c=0,u=Array.isArray(t);if((o=u?t.length:(h=Sr(t,i)).length)<16?(e.setUint8(n,o|(u?144:128)),c=1):o<65536?(e.setUint8(n,u?220:222),e.setUint16(n+1,o),c=3):o<4294967296&&(e.setUint8(n,u?221:223),e.setUint32(n+1,o),c=5),u)for(var l=0;l<o;l++)c+=Ar(t[l],e,n+c,i);else if(h)for(var d=0;d<o;d++){var f=h[d];c+=Ar(f,e,n+c),c+=Ar(t[f],e,n+c,i)}return c}if("function"===r)return 0;throw new Error("Unknown type "+r)}function Er(t,e){var n=typeof t;if("string"===n){var i=br(t);if(i<32)return 1+i;if(i<256)return 2+i;if(i<65536)return 3+i;if(i<4294967296)return 5+i}if(ArrayBuffer.isView&&ArrayBuffer.isView(t)&&(t=t.buffer),t instanceof ArrayBuffer){var r=t.byteLength;if(r<256)return 2+r;if(r<65536)return 3+r;if(r<4294967296)return 5+r}if("number"==typeof t){if(Math.floor(t)!==t)return 9;if(t>=0){if(t<128)return 1;if(t<256)return 2;if(t<65536)return 3;if(t<4294967296)return 5;if(t<0x10000000000000000)return 9;throw new Error("Number too big 0x"+t.toString(16))}if(t>=-32)return 1;if(t>=-128)return 2;if(t>=-32768)return 3;if(t>=-2147483648)return 5;if(t>=-0x8000000000000000)return 9;throw new Error("Number too small -0x"+t.toString(16).substr(1))}if("boolean"===n)return 1;if(null===t)return e?0:1;if(void 0===t)return e?0:3;if("function"==typeof t.toJSON)return Er(t.toJSON(),e);if("object"===n){var s,a=0;if(Array.isArray(t)){s=t.length;for(var o=0;o<s;o++)a+=Er(t[o],e)}else{var h=Sr(t,e);s=h.length;for(var c=0;c<s;c++){var u=h[c];a+=Er(u)+Er(t[u],e)}}if(s<16)return 1+a;if(s<65536)return 3+a;if(s<4294967296)return 5+a;throw new Error("Array or object too long 0x"+s.toString(16))}if("function"===n)return 0;throw new Error("Unknown type "+n)}var xr={encode:function(t,e){var n=Er(t,e);if(0!==n){var i=new ArrayBuffer(n);return Ar(t,new DataView(i),0,e),i}},decode:function(t){var e=new DataView(t),n=new Tr(e),i=n.parse();if(n.offset!==t.byteLength)throw new Error(t.byteLength-n.offset+" trailing bytes");return i},inspect:function(t){if(void 0===t)return"undefined";var e,n;if(t instanceof ArrayBuffer?(n="ArrayBuffer",e=new DataView(t)):t instanceof DataView&&(n="DataView",e=t),!e)return JSON.stringify(t);for(var i=[],r=0;r<t.byteLength;r++){if(r>20){i.push("...");break}var s=e.getUint8(r).toString(16);1===s.length&&(s="0"+s),i.push(s)}return"<"+n+" "+i.join(" ")+">"},utf8Write:mr,utf8Read:wr,utf8ByteCount:br};function Mr(){return(Mr=o(function*(t,e,n,i,r,s){var a,h=new Headers(i||{}),c=t?t.toUpperCase():_(s)?"GET":"POST",u=new AbortController,l=new Promise(t=>{a=setTimeout(()=>{u.abort(),t({error:new M("Request timed out",null,408)})},e?e.options.timeouts.httpRequestTimeout:Dt.TIMEOUTS.httpRequestTimeout)}),d={method:c,headers:h,body:s,signal:u.signal};w.Config.isWebworker||(d.credentials=h.has("authorization")?"include":"same-origin");var f=o(function*(){try{var t=new URLSearchParams(r||{});t.set("rnd",rt());var e=n+"?"+t,i=yield pt().fetch(e,d);if(clearTimeout(a),204==i.status)return{error:null,statusCode:i.status};var s,o=i.headers.get("Content-Type");s=o&&o.indexOf("application/x-msgpack")>-1?yield i.arrayBuffer():o&&o.indexOf("application/json")>-1?yield i.json():yield i.text();var h=!!o&&-1===o.indexOf("application/x-msgpack"),c=function(t){var e={};return t.forEach((t,n)=>{e[n]=t}),e}(i.headers);if(i.ok)return{error:null,body:s,headers:c,unpacked:h,statusCode:i.status};var u=function(t,e){if(function(t,e){return!!e.get("x-ably-errorcode")}(0,e))return t.error&&x.fromValues(t.error)}(s,i.headers)||new M("Error response received from server: "+i.status+" body was: "+w.Config.inspect(s),null,i.status);return{error:u,body:s,headers:c,unpacked:h,statusCode:i.status}}catch(u){return clearTimeout(a),{error:u}}})();return Promise.race([l,f])})).apply(this,arguments)}var Rr,Pr={XHRRequest:vr,FetchRequest:function(t,e,n,i,r,s){return Mr.apply(this,arguments)}},Or=function(t,e){class n{constructor(t,e,n,i){this.algorithm=t,this.keyLength=e,this.mode=n,this.key=i}}class i{static getDefaultParams(t){var i;if(!t.key)throw new Error("Crypto.getDefaultParams: a key is required");i="string"==typeof t.key?e.toArrayBuffer(e.base64Decode(t.key.replace("_","/").replace("-","+"))):t.key instanceof ArrayBuffer?t.key:e.toArrayBuffer(t.key);var r=t.algorithm||"aes",s=8*i.byteLength,a=t.mode||"cbc",o=new n(r,s,a,i);if(t.keyLength&&t.keyLength!==o.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+t.keyLength+" was specified, but the key actually has length "+o.keyLength);return function(t){if("aes"===t.algorithm&&"cbc"===t.mode){if(128===t.keyLength||256===t.keyLength)return;throw new Error("Unsupported key length "+t.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}(o),o}static generateRandomKey(e){return o(function*(){try{return t.getRandomArrayBuffer((e||256)/8)}catch(t){throw new x("Failed to generate random key: "+t.message,400,5e4,t)}})()}static getCipher(t,e){var i,s=function(t){return t instanceof n}(t)?t:this.getDefaultParams(t);return{cipherParams:s,cipher:new r(s,null!=(i=t.iv)?i:null,e)}}}i.CipherParams=n;class r{constructor(t,n,i){if(this.logger=i,!crypto.subtle)throw isSecureContext?new Error("Crypto operations are not possible since the browser’s SubtleCrypto class is unavailable (reason unknown)."):new Error("Crypto operations are is not possible since the current environment is a non-secure context and hence the browser’s SubtleCrypto class is not available.");this.algorithm=t.algorithm+"-"+String(t.keyLength)+"-"+t.mode,this.webCryptoAlgorithm=t.algorithm+"-"+t.mode,this.key=e.toArrayBuffer(t.key),this.iv=n?e.toArrayBuffer(n):null}concat(t,n){for(var i=new ArrayBuffer(t.byteLength+n.byteLength),r=new DataView(i),s=new DataView(e.toArrayBuffer(t)),a=0;a<s.byteLength;a++)r.setInt8(a,s.getInt8(a));for(var o=new DataView(e.toArrayBuffer(n)),h=0;h<o.byteLength;h++)r.setInt8(s.byteLength+h,o.getInt8(h));return i}encrypt(t){var e=this;return o(function*(){S.logAction(e.logger,S.LOG_MICRO,"CBCCipher.encrypt()","");var n=yield e.getIv(),i=yield crypto.subtle.importKey("raw",e.key,e.webCryptoAlgorithm,!1,["encrypt"]),r=yield crypto.subtle.encrypt({name:e.webCryptoAlgorithm,iv:n},i,t);return e.concat(n,r)})()}decrypt(t){var n=this;return o(function*(){S.logAction(n.logger,S.LOG_MICRO,"CBCCipher.decrypt()","");var i=e.toArrayBuffer(t),r=i.slice(0,16),s=i.slice(16),a=yield crypto.subtle.importKey("raw",n.key,n.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:n.webCryptoAlgorithm,iv:r},a,s)})()}getIv(){var n=this;return o(function*(){if(n.iv){var i=n.iv;return n.iv=null,i}var r=yield t.getRandomArrayBuffer(16);return e.toArrayBuffer(r)})()}}return i}(or,$i);for(var Ir of(w.Crypto=Or,w.BufferUtils=$i,w.Http=Yi,w.Config=or,w.Transports=gr,w.WebStorage=er,[Zn,Pi]))Ir.Crypto=Or,Ir.S=xr;Yi.bundledRequestImplementations=Pr,S.initLogHandlers(),w.Defaults=(Rr=yr,Object.assign(Et,Rr)),w.Config.agent&&(w.Defaults.agent+=" "+w.Config.agent);var jr={ErrorInfo:x,Rest:Zn,Realtime:Pi,msgpack:xr,makeProtocolMessageFromDeserialized:Wn};return"object"==typeof n.exports&&(n.exports=((t,e,n,i)=>{if(e&&"object"==typeof e||"function"==typeof e){var r=function(r){Object.prototype.hasOwnProperty.call(t,r)||r===n||Object.defineProperty(t,r,{get:()=>e[r],enumerable:!(i=Object.getOwnPropertyDescriptor(e,r))||i.enumerable})};for(var s of Object.getOwnPropertyNames(e))r(s)}return t})(n.exports,e)),n.exports},y.exports=g();var m=p(y.exports),w="[Chat]",b="bottom-right",C={primaryColor:"#6366f1",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',borderRadius:"12px",headerBgColor:"#6366f1",userBubbleColor:"#6366f1",agentBubbleColor:"#f3f4f6"},k="/api/chat/ably-token";class T{constructor(t,e){void 0===e&&(e={}),this.ft=null,this.vt=null,this.gt=null,this.yt=null,this.wt=null,this.bt=null,this.Ct="disconnected",this.kt=[],this.Tt=[],this.St=[],this.At=null,this.Et=null,this.xt=!1,this.Mt=null,this.Rt=!1,this._instance=t,this.Pt=h({enabled:!0,position:b,aiMode:!0,preload:!1},e,{theme:h({},C,e.theme)}),this.Ot={isOpen:!1,isVisible:!0,isConnected:!1,isLoading:!1,unreadCount:0,channel:null,messages:[],isTyping:!1,typingSender:null,agentLastReadAt:null},this.It(),this.jt(),console.info(w+" initialized")}get isOpen(){return this.Ot.isOpen}get isConnected(){return this.Ot.isConnected}get isLoading(){return this.Ot.isLoading}get unreadCount(){return this.Ot.unreadCount}get channel(){return this.Ot.channel}open(){var t;this.Ot.isOpen||(this.Ot.isOpen=!0,this._t(),this.Ut(d,{$page_url:null===(t=null==e?void 0:e.location)||void 0===t?void 0:t.href,$trigger:"api"}),this.Ot.channel?this.Nt():this.Dt(),this.Ot.isConnected||this.qt())}close(){if(this.Ot.isOpen){var t=this.Bt();this.Ot.isOpen=!1,this._t(),this.Ut(f,{$time_open_seconds:t,$messages_sent:this.Ot.messages.filter(t=>"user"===t.sender_type).length})}}toggle(){this.Ot.isOpen?this.close():this.open()}show(){this.Ot.isVisible=!0,this._t()}hide(){this.Ot.isVisible=!1,this._t()}sendMessage(t){var e=this;return o(function*(){var n,i,r,s;if(t.trim()){e.Ot.channel||(yield e.Dt());var a=null===(n=e.Ot.channel)||void 0===n?void 0:n.id;if(a){var o={id:"temp-"+Date.now(),channel_id:a,sender_type:"user",sender_id:e._instance.getDistinctId()||null,sender_name:null,sender_avatar_url:null,content:t,content_type:"text",metadata:{},created_at:(new Date).toISOString()};e.Ot.messages.push(o),e._t();try{var h=yield e.Wt("/api/chat/widget/messages",{method:"POST",body:JSON.stringify({channel_id:a,distinct_id:e._instance.getDistinctId(),content:t})}),c=e.Ot.messages.findIndex(t=>t.id===o.id);-1!==c&&(null==h?void 0:h.message)&&(e.Ot.messages[c]=h.message),e.Ut(u,{$channel_id:a,$message_id:null===(i=null==h?void 0:h.message)||void 0===i?void 0:i.id,$content_preview:t.substring(0,100),$sender_type:"user",$ai_mode:null===(s=null===(r=e.Ot.channel)||void 0===r?void 0:r.ai_mode)||void 0===s||s,$word_count:t.split(/\s+/).length}),e._t()}catch(t){console.error(w+" Failed to send message:",t),e.Ot.messages=e.Ot.messages.filter(t=>t.id!==o.id),e._t()}}else console.error(w+" No channel to send message to")}})()}markAsRead(){this.Nt()}Nt(){if(this.Ot.channel&&!this.Rt){var t=this.Ot.messages[this.Ot.messages.length-1];if(t)this.Ot.messages.some(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&!this.Ht(t.created_at))&&(this.Ot.unreadCount=0,this.Rt=!0,this._t(),this.Wt("/api/chat/widget/read",{method:"POST",body:JSON.stringify({channel_id:this.Ot.channel.id,distinct_id:this._instance.getDistinctId(),read_at:t.created_at})}).then(()=>{this.Mt=t.created_at,this.Rt=!1,this._t()}).catch(t=>{console.error(w+" Failed to mark as read:",t),this.Rt=!1,this._t()}))}}Ht(t){return!!this.Mt&&new Date(t)<=new Date(this.Mt)}onMessage(t){return this.kt.push(t),()=>{var e=this.kt.indexOf(t);e>-1&&this.kt.splice(e,1)}}onTyping(t){return this.Tt.push(t),()=>{var e=this.Tt.indexOf(t);e>-1&&this.Tt.splice(e,1)}}onConnectionChange(t){return this.St.push(t),()=>{var e=this.St.indexOf(t);e>-1&&this.St.splice(e,1)}}destroy(){this.Vt(),this.At&&clearTimeout(this.At),this.Et&&clearTimeout(this.Et),this.ft&&this.ft.parentNode&&this.ft.parentNode.removeChild(this.ft),this.kt=[],this.Tt=[],this.St=[],console.info(w+" destroyed")}Dt(){var t=this;return o(function*(){var n;t.Ot.isLoading=!0,t._t();try{var i=yield t.Wt("/api/chat/widget",{method:"POST",body:JSON.stringify({distinct_id:t._instance.getDistinctId(),page_url:null===(n=null==e?void 0:e.location)||void 0===n?void 0:n.href,page_title:null==r?void 0:r.title})});i&&(t.Ot.channel=i.channel,t.Ot.messages=i.messages||[],t.Ot.agentLastReadAt=i.channel.agent_last_read_at||null,t.Mt=i.channel.user_last_read_at||null,0!==i.messages.length&&1!==i.messages.length||t.Ut(c,{$channel_id:i.channel.id,$initiated_by:"user",$ai_mode:i.channel.ai_mode}),t.qt(),t.Ot.isOpen&&t.Nt())}catch(t){console.error(w+" Failed to initialize channel:",t)}finally{t.Ot.isLoading=!1,t._t()}})()}qt(){var t=this;return o(function*(){if(!t.yt&&t.Ot.channel){t.Ct="connecting",t.zt(!1);try{var e=yield t.Wt(k,{method:"POST",body:JSON.stringify({distinct_id:t._instance.getDistinctId(),channel_id:t.Ot.channel.id})});if(!(null==e?void 0:e.tokenRequest))return console.warn(w+" Failed to get Ably token"),void(t.Ct="error");t.yt=new m.Realtime({authCallback:(s=o(function*(e,n){var i;try{var r=yield t.Wt(k,{method:"POST",body:JSON.stringify({distinct_id:t._instance.getDistinctId(),channel_id:null===(i=t.Ot.channel)||void 0===i?void 0:i.id})});(null==r?void 0:r.tokenRequest)?n(null,r.tokenRequest):n("Failed to refresh token",null)}catch(t){n(String(t),null)}}),function(t,e){return s.apply(this,arguments)}),authMethod:"POST"}),yield t.yt.auth.authorize(e.tokenRequest);var n=t._instance.getConfig(),i="chat:"+(n.projectId||t.Lt(n.token||""))+":"+t.Ot.channel.id;t.wt=t.yt.channels.get(i),t.wt.subscribe("message",e=>{var n=e.data;t.Ft(n)});var r=i+":typing";t.bt=t.yt.channels.get(r),t.bt.subscribe("typing",e=>{var n=e.data;t.Jt(n)}),t.wt.subscribe("read",e=>{var n=e.data;t.$t(n)}),t.yt.connection.on("connected",()=>{t.Ct="connected",t.Ot.isConnected=!0,t.zt(!0),console.info(w+" Connected to Ably")}),t.yt.connection.on("disconnected",()=>{t.Ct="disconnected",t.Ot.isConnected=!1,t.zt(!1)}),t.yt.connection.on("failed",()=>{t.Ct="error",t.Ot.isConnected=!1,t.zt(!1)}),t.yt.connect()}catch(e){console.error(w+" Failed to connect to Ably:",e),t.Ct="error"}var s}})()}Vt(){this.wt&&(this.wt.unsubscribe(),this.wt=null),this.bt&&(this.bt.unsubscribe(),this.bt=null),this.yt&&(this.yt.close(),this.yt=null),this.Ct="disconnected",this.Ot.isConnected=!1}Lt(t){return t.split(".")[0]||""}Ft(t){if(!this.Ot.messages.some(e=>e.id===t.id))if("user"!==t.sender_type||t.sender_id!==this._instance.getDistinctId())this.Ot.messages.push(t),"user"!==t.sender_type&&(this.Ot.isOpen?setTimeout(()=>this.Nt(),100):this.Ot.unreadCount++,this.Ut(l,{$channel_id:t.channel_id,$message_id:t.id,$content_preview:t.content.substring(0,100),$sender_type:t.sender_type})),this.Ot.isTyping=!1,this.Ot.typingSender=null,this.kt.forEach(e=>e(t)),this._t();else{var e=this.Ot.messages.findIndex(e=>e.id.startsWith("temp-")&&e.content===t.content&&"user"===e.sender_type);-1!==e&&(this.Ot.messages[e]=t,this._t())}}Jt(t){if("user"!==t.sender_type){var e=t.sender_name||("ai"===t.sender_type?"AI Assistant":"Agent");this.Ot.isTyping=t.is_typing,this.Ot.typingSender=t.is_typing?e:null,this.Tt.forEach(n=>n(t.is_typing,e)),this._t()}}$t(t){"agent"===t.reader_type&&(this.Ot.agentLastReadAt=t.read_at,this._t())}zt(t){this.St.forEach(e=>e(t))}It(){r&&(this.ft=r.createElement("div"),this.ft.id="vtilt-chat-container",this.ft.setAttribute("style",this.Kt()),this.gt=r.createElement("div"),this.gt.id="vtilt-chat-bubble",this.gt.innerHTML=this.Gt(),this.gt.setAttribute("style",this.Qt()),this.ft.appendChild(this.gt),this.vt=r.createElement("div"),this.vt.id="vtilt-chat-widget",this.vt.innerHTML=this.Xt(),this.vt.setAttribute("style",this.Yt()),this.ft.appendChild(this.vt),r.body.appendChild(this.ft))}jt(){var t,e,n,i;null===(t=this.gt)||void 0===t||t.addEventListener("click",()=>this.toggle());var r=null===(e=this.vt)||void 0===e?void 0:e.querySelector(".vtilt-chat-close");null==r||r.addEventListener("click",()=>this.close());var s=null===(n=this.vt)||void 0===n?void 0:n.querySelector(".vtilt-chat-send");null==s||s.addEventListener("click",()=>this.Zt());var a=null===(i=this.vt)||void 0===i?void 0:i.querySelector(".vtilt-chat-input");null==a||a.addEventListener("keypress",t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.Zt())}),null==a||a.addEventListener("input",()=>{this.te()})}te(){this.bt&&(this.xt||(this.xt=!0,this.ee(!0)),this.Et&&clearTimeout(this.Et),this.Et=setTimeout(()=>{this.xt=!1,this.ee(!1)},2e3))}ee(t){if(this.bt)try{this.bt.publish("typing",{sender_type:"user",sender_id:this._instance.getDistinctId(),sender_name:null,is_typing:t})}catch(t){console.error(w+" Failed to send typing indicator:",t)}}Zt(){var t,e=null===(t=this.vt)||void 0===t?void 0:t.querySelector(".vtilt-chat-input");if(e){var n=e.value.trim();n&&(this.xt&&(this.xt=!1,this.ee(!1)),this.Et&&(clearTimeout(this.Et),this.Et=null),this.sendMessage(n),e.value="")}}_t(){if(this.ft&&this.vt&&this.gt){this.ft.style.display=this.Ot.isVisible?"block":"none",this.vt.style.display=this.Ot.isOpen?"flex":"none";var t=this.gt.querySelector(".vtilt-chat-badge");t&&(t.style.display=this.Ot.unreadCount>0?"flex":"none",t.textContent=String(this.Ot.unreadCount)),this.ne();var e=this.vt.querySelector(".vtilt-chat-loader");e&&(e.style.display=this.Ot.isLoading?"flex":"none");var n=this.vt.querySelector(".vtilt-chat-typing");if(n){n.style.display=this.Ot.isTyping?"flex":"none";var i=n.querySelector("span");i&&this.Ot.typingSender&&(i.textContent=this.Ot.typingSender+" is typing...")}}}ne(){var t,e=null===(t=this.vt)||void 0===t?void 0:t.querySelector(".vtilt-chat-messages");if(e){var n=this.Pt.theme||C,i=this.Ot.messages.findIndex(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&!this.Ht(t.created_at)),r=this.Ot.messages.map((t,e)=>{var r="";return e===i&&i>0&&(r+='\n <div style="display: flex; align-items: center; gap: 12px; margin: 8px 0;">\n <div style="flex: 1; height: 1px; background: '+n.primaryColor+'40;"></div>\n <span style="font-size: 11px; font-weight: 500; color: '+n.primaryColor+'; padding: 0 8px;">New messages</span>\n <div style="flex: 1; height: 1px; background: '+n.primaryColor+'40;"></div>\n </div>\n '),r+=this.ie(t)}).join("");e.innerHTML=r,e.scrollTop=e.scrollHeight}}Kt(){var t;return"\n position: fixed;\n bottom: 20px;\n "+("bottom-right"===(this.Pt.position||b)?"right: 20px;":"left: 20px;")+"\n z-index: 999999;\n font-family: "+((null===(t=this.Pt.theme)||void 0===t?void 0:t.fontFamily)||C.fontFamily)+";\n "}Qt(){return"\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: "+(this.Pt.theme||C).primaryColor+";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n transition: transform 0.2s, box-shadow 0.2s;\n position: relative;\n "}Gt(){return'\n <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">\n <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>\n </svg>\n <div class="vtilt-chat-badge" style="\n display: none;\n position: absolute;\n top: -5px;\n right: -5px;\n background: #ef4444;\n color: white;\n font-size: 12px;\n font-weight: 600;\n min-width: 20px;\n height: 20px;\n border-radius: 10px;\n align-items: center;\n justify-content: center;\n ">0</div>\n '}Yt(){return"\n display: none;\n flex-direction: column;\n position: absolute;\n bottom: 80px;\n right: 0;\n width: 380px;\n height: 520px;\n background: white;\n border-radius: "+(this.Pt.theme||C).borderRadius+";\n box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);\n overflow: hidden;\n "}Xt(){var t=this.Pt.theme||C,e=this.Pt.greeting||"How can we help you?";return'\n <div class="vtilt-chat-header" style="\n background: '+t.headerBgColor+';\n color: white;\n padding: 16px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n ">\n <div style="font-weight: 600; font-size: 16px;">'+e+'</div>\n <button class="vtilt-chat-close" style="\n background: none;\n border: none;\n color: white;\n cursor: pointer;\n padding: 4px;\n ">\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n </div>\n \n <div class="vtilt-chat-messages" style="\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n "></div>\n \n <div class="vtilt-chat-loader" style="\n display: none;\n align-items: center;\n justify-content: center;\n padding: 20px;\n ">\n <div style="\n width: 24px;\n height: 24px;\n border: 2px solid #e5e7eb;\n border-top-color: '+t.primaryColor+';\n border-radius: 50%;\n animation: vtilt-spin 0.8s linear infinite;\n "></div>\n </div>\n \n <div class="vtilt-chat-typing" style="\n display: none;\n padding: 8px 16px;\n color: #6b7280;\n font-size: 14px;\n ">\n <span style="animation: vtilt-pulse 1.5s infinite;">Agent is typing...</span>\n </div>\n \n <div class="vtilt-chat-input-container" style="\n padding: 16px;\n border-top: 1px solid #e5e7eb;\n display: flex;\n gap: 8px;\n ">\n <input\n type="text"\n class="vtilt-chat-input"\n placeholder="Type a message..."\n style="\n flex: 1;\n border: 1px solid #e5e7eb;\n border-radius: 8px;\n padding: 10px 14px;\n font-size: 14px;\n outline: none;\n transition: border-color 0.2s;\n "\n />\n <button class="vtilt-chat-send" style="\n background: '+t.primaryColor+';\n color: white;\n border: none;\n border-radius: 8px;\n padding: 10px 16px;\n cursor: pointer;\n font-weight: 500;\n transition: opacity 0.2s;\n ">Send</button>\n </div>\n \n <style>\n @keyframes vtilt-spin {\n to { transform: rotate(360deg); }\n }\n @keyframes vtilt-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n #vtilt-chat-bubble:hover {\n transform: scale(1.05);\n box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);\n }\n .vtilt-chat-input:focus {\n border-color: '+t.primaryColor+" !important;\n }\n .vtilt-chat-send:hover {\n opacity: 0.9;\n }\n </style>\n "}ie(t){var e=this.Pt.theme||C,n="user"===t.sender_type,i="agent"===t.sender_type||"ai"===t.sender_type,r=n&&this.re(t.created_at),s=i&&!this.Ht(t.created_at),a=n?"background: "+e.userBubbleColor+"; color: white; margin-left: auto;":"background: "+e.agentBubbleColor+"; color: #1f2937; margin-right: auto;"+(s&&!this.Rt?" box-shadow: 0 0 0 2px "+e.primaryColor+"40;":""),o="ai"===t.sender_type?"AI Assistant":"agent"===t.sender_type?t.sender_name||"Agent":"",h='<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="color: '+e.primaryColor+';"><path d="M18 7l-1.41-1.41-6.34 6.34 1.41 1.41L18 7zm4.24-1.41L11.66 16.17 7.48 12l-1.41 1.41L11.66 19l12-12-1.42-1.41zM.41 13.41L6 19l1.41-1.41L1.83 12 .41 13.41z"/></svg>',c=s&&!this.Rt?'<span style="font-size: 10px; font-weight: 600; color: '+e.primaryColor+"; background: "+e.primaryColor+'20; padding: 2px 6px; border-radius: 9999px;">NEW</span>':"";return'\n <div style="display: flex; flex-direction: column; '+(n?"align-items: flex-end;":"align-items: flex-start;")+(s&&!this.Rt?" position: relative;":"")+'">\n '+(!n&&o?'<div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">'+o+"</div>":"")+'\n <div style="\n max-width: 80%;\n padding: 10px 14px;\n border-radius: 12px;\n font-size: 14px;\n line-height: 1.4;\n transition: opacity 0.3s, box-shadow 0.3s;\n '+a+(this.Rt&&s?" opacity: 0.7;":"")+'\n ">'+this.se(t.content)+'</div>\n <div style="font-size: 11px; color: #9ca3af; margin-top: 4px; display: flex; align-items: center; gap: 4px;">\n '+this.ae(t.created_at)+"\n "+(n?r?h:'<svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor" style="color: #9ca3af;"><path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/></svg>':c)+"\n </div>\n </div>\n "}re(t){return!!this.Ot.agentLastReadAt&&new Date(t)<=new Date(this.Ot.agentLastReadAt)}Wt(t,e){var n=this;return o(function*(){void 0===e&&(e={});var i=n._instance.getConfig(),r=i.api_host||"",s=i.token||"",a=""+r+t+"?token="+encodeURIComponent(s);try{var o=yield fetch(a,h({},e,{headers:h({"Content-Type":"application/json"},e.headers)}));if(!o.ok)throw new Error("API error: "+o.status);return yield o.json()}catch(t){return console.error(w+" API request failed:",t),null}})()}Ut(t,e){this._instance.capture(t,e)}Bt(){return 0}se(t){if(!r)return t;var e=r.createElement("div");return e.textContent=t,e.innerHTML}ae(t){return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}function S(t,e){return new T(t,e)}s.__VTiltExtensions__=s.__VTiltExtensions__||{},s.__VTiltExtensions__.initChat=S,t.LazyLoadedChat=T,t.default=S,t.initChat=S,Object.defineProperty(t,"__esModule",{value:!0})}({});
|
|
2
|
+
//# sourceMappingURL=chat.js.map
|