@v-tilt/browser 1.12.0 → 1.13.0

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/chat.js CHANGED
@@ -1,2 +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,e&&r&&r.createElement,null==n||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),l=o.value}catch(t){return void n(t)}o.done?e(l):Promise.resolve(l).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,l,"next",t)}function l(t){a(s,i,r,o,l,"throw",t)}o(void 0)})}}function l(){return l=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},l.apply(null,arguments)}var h=/<(?:p|ul|ol|li|h[1-6]|br|div|pre|blockquote)\b/i;function c(t){var e=t;return e=(e=(e=(e=(e=(e=e.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>")).replace(/__(.+?)__/g,"<b>$1</b>")).replace(/\*(.+?)\*/g,"<i>$1</i>")).replace(/(?<!\w)_(.+?)_(?!\w)/g,"<i>$1</i>")).replace(/`([^`]+)`/g,"<code>$1</code>")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>')}var d=new Set(["P","B","STRONG","I","EM","U","UL","OL","LI","BR","A","H1","H2","H3","H4","H5","H6","CODE","PRE","BLOCKQUOTE","DIV","SPAN"]);function u(t,e){for(var n=Array.from(t.children),i=0;i<n.length;){var r=n[i];if("LI"!==r.tagName)u(r,e),i++;else{for(var s=[],a=i;a<n.length&&"LI"===n[a].tagName;)s.push(n[a]),a++;var o=e.createElement("ul");for(var l of(t.insertBefore(o,s[0]),s))o.appendChild(l);i=a}}}function v(t,e,n){if(!t)return"";var i=t.trim();if(!i)return"";if(!n)return i;var r=function(t,e){return"html"!==t&&!h.test(e)}(e,i)?function(t){if(!t||h.test(t))return t;for(var e=t.split("\n"),n=[],i=0;i<e.length;){var r=e[i],s=r.match(/^(#{1,6})\s+(.+)$/);if(s){var a=s[1].length;n.push("<h"+a+">"+c(s[2])+"</h"+a+">"),i++}else if(/^[-*]\s+/.test(r)){for(var o=[];i<e.length&&/^[-*]\s+/.test(e[i]);)o.push("<li>"+c(e[i].replace(/^[-*]\s+/,""))+"</li>"),i++;n.push("<ul>"+o.join("")+"</ul>")}else if(/^\d+\.\s+/.test(r)){for(var l=[];i<e.length&&/^\d+\.\s+/.test(e[i]);)l.push("<li>"+c(e[i].replace(/^\d+\.\s+/,""))+"</li>"),i++;n.push("<ol>"+l.join("")+"</ol>")}else if(""!==r.trim()){for(var d=[];i<e.length&&""!==e[i].trim()&&!/^#{1,6}\s/.test(e[i])&&!/^[-*]\s+/.test(e[i])&&!/^\d+\.\s+/.test(e[i]);)d.push(c(e[i])),i++;n.push("<p>"+d.join("<br>")+"</p>")}else i++}return n.join("")}(i):i,s=n.createElement("div");return s.innerHTML=r,function(t,e){var n=t=>{for(var i of Array.from(t.children))if(d.has(i.tagName)){for(var r of Array.from(i.attributes))"A"===i.tagName&&"href"===r.name||i.removeAttribute(r.name);"A"===i.tagName&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer")),n(i)}else i.replaceWith(e.createTextNode(i.textContent||""))};n(t)}(s,n),u(s,n),s.innerHTML}var f="rich_format",p="markdown";function g(t){return"user"===t.sender_type?function(t){var e;return"html"===t.content_type||(null===(e=t.metadata)||void 0===e?void 0:e[f])===p}(t):"ai"===t.sender_type||"agent"===t.sender_type}var m="x-api-key";function w(t,e,n){void 0===n&&(n={});var{api_host:i,token:r}=t,s=""+(i?i.replace(/\/+$/gm,""):"")+e;if(n.includeTokenQuery&&r){var a=s.includes("?")?"&":"?";s=""+s+a+"token="+r}return s}function y(t){return t.token?{[m]:t.token}:{}}var b="$channel_message",x=Object.defineProperty,k=Object.defineProperties,E=Object.getOwnPropertyDescriptors,T=Object.getOwnPropertySymbols,A=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable,C=(t,e,n)=>e in t?x(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_=(t,e)=>{for(var n in e||(e={}))A.call(e,n)&&C(t,n,e[n]);if(T)for(var n of T(e))S.call(e,n)&&C(t,n,e[n]);return t},O=(t,e)=>k(t,E(e)),M=function(t,e){this[0]=t,this[1]=e},I=class{},j="undefined"!=typeof global?global:"undefined"!=typeof window?window:self;function P(t,e){return(""+t).padStart(e?3:2,"0")}function R(t){return I.Config.logTimestamps?function(e){var n=new Date;t(P(n.getHours())+":"+P(n.getMinutes())+":"+P(n.getSeconds())+"."+P(n.getMilliseconds(),1)+" "+e)}:function(e){t(e)}}var D=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==j?void 0:j.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(R));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)}};D.defaultLogLevel=1,D.LOG_NONE=0,D.LOG_ERROR=1,D.LOG_MAJOR=2,D.LOG_MINOR=3,D.LOG_MICRO=4,D.logAction=(t,e,n,i)=>{D.logActionNoStrip(t,e,n,i)};var B=D,N={};function U(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="+vt(t.cause)),!t.href||t.message&&t.message.indexOf("help.ably.io")>-1||(e+="; see "+t.href+" "),e+="]"}((t,e)=>{for(var n in e)x(t,n,{get:e[n],enumerable:!0})})(N,{Format:()=>ot,allSame:()=>at,allToLowerCase:()=>kt,allToUpperCase:()=>Et,arrChooseN:()=>wt,arrDeleteValue:()=>et,arrEquals:()=>It,arrIntersect:()=>Z,arrIntersectOb:()=>tt,arrPopRandomElement:()=>lt,arrWithoutValue:()=>nt,cheapRandStr:()=>gt,containsValue:()=>Y,copy:()=>L,createMissingPluginError:()=>jt,dataSizeBytes:()=>pt,decodeBody:()=>bt,encodeBody:()=>xt,ensureArray:()=>F,forInOwnNonNullProperties:()=>st,getBackoffCoefficient:()=>Tt,getGlobalObject:()=>Ct,getJitterCoefficient:()=>At,getRetryTime:()=>St,inherits:()=>Q,inspectBody:()=>ft,inspectError:()=>vt,intersect:()=>X,isEmpty:()=>W,isErrorInfoOrPartialErrorInfo:()=>ut,isNil:()=>J,isObject:()=>V,keysArray:()=>it,listenerToAsyncIterator:()=>Bt,matchDerivedChannel:()=>Ot,mixin:()=>q,parseQueryString:()=>dt,prototypicalClone:()=>G,randomString:()=>mt,shallowClone:()=>K,shallowEquals:()=>_t,stringifyValues:()=>ct,throwMissingPluginError:()=>Pt,toBase64:()=>Mt,toQueryString:()=>ht,valuesArray:()=>rt,whenPromiseSettles:()=>yt,withTimeoutAsync:()=>Rt});var z=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 U(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: "+I.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}},H=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 U(this)}static fromValues(e){var{message:n,code:i,statusCode:r}=e;if("string"!=typeof n||!J(i)&&"number"!=typeof i||!J(r)&&"number"!=typeof r)throw new Error("PartialErrorInfo.fromValues(): invalid values: "+I.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 q(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 L(t){return q({},t)}function F(t){return J(t)?[]:Array.isArray(t)?t:[t]}function V(t){return"[object Object]"==Object.prototype.toString.call(t)}function W(t){for(var e in t)return!1;return!0}function J(t){return null==t}function K(t){var e=new Object;for(var n in t)e[n]=t[n];return e}function G(t,e){class n{}n.prototype=t;var i=new n;return e&&q(i,e),i}var Q=function(t,e){I.Config.inherits?I.Config.inherits(t,e):(t.super_=e,t.prototype=G(e.prototype,{constructor:t}))};function Y(t,e){for(var n in t)if(t[n]==e)return!0;return!1}function X(t,e){return Array.isArray(e)?Z(t,e):tt(t,e)}function Z(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 tt(t,e){for(var n=[],i=0;i<t.length;i++){var r=t[i];r in e&&n.push(r)}return n}function et(t,e){var n=t.indexOf(e),i=-1!=n;return i&&t.splice(n,1),i}function nt(t,e){var n=t.slice();return et(n,e),n}function it(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(i);return n}function rt(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(t[i]);return n}function st(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&t[n]&&e(n)}function at(t,e){if(0===t.length)return!0;var n=t[0][e];return t.every(function(t){return t[e]===n})}var ot=(t=>(t.msgpack="msgpack",t.json="json",t))(ot||{});function lt(t){return t.splice((e=t,Math.floor(Math.random()*e.length)),1)[0];var e}function ht(t){var e=[];if(t)for(var n in t)e.push(encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e.length?"?"+e.join("&"):""}function ct(t){return Object.fromEntries(Object.entries(t).map(t=>{var[e,n]=t;return[e,String(n)]}))}function dt(t){for(var e,n=/([^?&=]+)=?([^&]*)/g,i={};e=n.exec(t);)i[decodeURIComponent(e[1])]=decodeURIComponent(e[2]);return i}function ut(t){return"object"==typeof t&&null!==t&&(t instanceof z||t instanceof H)}function vt(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():I.Config.inspect(t)}function ft(t){return I.BufferUtils.isBuffer(t)?t.toString():"string"==typeof t?t:I.Config.inspect(t)}function pt(t){if(I.BufferUtils.isBuffer(t))return I.BufferUtils.byteLength(t);if("string"==typeof t)return I.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 gt(){return String(Math.random()).substr(2)}var mt=function(){var t=o(function*(t){var e=yield I.Config.getRandomArrayBuffer(t);return I.BufferUtils.base64Encode(e)});return function(e){return t.apply(this,arguments)}}();function wt(t,e){for(var n=Math.min(e,t.length),i=t.slice(),r=[],s=0;s<n;s++)r.push(lt(i));return r}function yt(t,e){t.then(t=>{null==e||e(null,t)}).catch(t=>{null==e||e(t)})}function bt(t,e,n){return"msgpack"==n?(e||Pt("MsgPack"),e.decode(t)):JSON.parse(String(t))}function xt(t,e,n){return"msgpack"==n?(e||Pt("MsgPack"),e.encode(t,!0)):JSON.stringify(t)}function kt(t){return t.map(function(t){return t&&t.toLowerCase()})}function Et(t){return t.map(function(t){return t&&t.toUpperCase()})}function Tt(t){return Math.min((t+2)/3,2)}function At(){return 1-.2*Math.random()}function St(t,e){return t*Tt(e)*At()}function Ct(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:self}function _t(t,e){return Object.keys(t).every(n=>t[n]===e[n])&&Object.keys(e).every(n=>e[n]===t[n])}function Ot(t){var e=t.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!e||!e.length||e.length<5)throw new z("regex match failed",400,40010);if(e[2])throw new z("cannot use a derived option with a "+e[2]+" channel",400,40010);return{qualifierParam:e[3]||"",channelName:e[4]}}function Mt(t){var e=I.BufferUtils,n=e.utf8Encode(t);return e.base64Encode(n)}function It(t,e){return t.length===e.length&&t.every(function(t,n){return t===e[n]})}function jt(t){return new z(t+" plugin not provided",40019,400)}function Pt(t){throw jt(t)}function Rt(t,e,n){return Dt.apply(this,arguments)}function Dt(){return(Dt=o(function*(t,e,n){void 0===e&&(e=5e3),void 0===n&&(n="Timeout expired");var i=new z(n,5e4,500);return Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(i),e))])})).apply(this,arguments)}function Bt(t){return n=(t,i,r,s)=>{try{var a=e[t](i),o=(i=a.value)instanceof M,l=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:l})).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 z("Concurrent next() calls are not supported",4e4,400);var r=yield new M(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 Nt="2.17.0",Ut={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:Nt,protocolVersion:5,agent:"ably-js/"+Nt,getPort:function(t,e){return e||t.tls?t.tlsPort:t.port},getHttpScheme:function(t){return t.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:Ht,getEndpointFallbackHosts:qt,getFallbackHosts:Ft,getHosts:function(t){return[t.primaryDomain].concat(Ft(t))},checkHost:Vt,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 B.logAction(i,B.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 B.logAction(i,B.LOG_ERROR,n+"()",o),new Error(o)}a={token:t}}else{if(!e){var l=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 B.logAction(i,B.LOG_ERROR,n+"()",l),new Error(l)}a={key:t}}else a=t;r&&(a=O(_({},a),{plugins:_(_({},r),a.plugins)}));return a},normaliseOptions:function(t,e,n){var i=null!=n?n:B.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.");Jt(t),"function"==typeof t.recover&&!0===t.closeOnUnload&&(B.logAction(i,B.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||Ut.ENDPOINT;t.fallbackHosts||t.restHost||t.realtimeHost||t.port||t.tlsPort||(t.fallbackHosts=qt(t.environment||r));var s=t.environment&&t.environment+".realtime.ably.net",a=t.restHost||t.realtimeHost||s||Ht(r);(t.fallbackHosts||[]).concat(a).forEach(Vt),t.port=t.port||Ut.PORT,t.tlsPort=t.tlsPort||Ut.TLS_PORT,"tls"in t||(t.tls=!0);var o=function(t){var e={};for(var n in Ut.TIMEOUTS)e[n]=t[n]||Ut.TIMEOUTS[n];return e}(t);t.useBinaryProtocol=!!e&&("useBinaryProtocol"in t?I.Config.supportsBinary&&t.useBinaryProtocol:I.Config.preferBinary);var l={};t.clientId&&(l["X-Ably-ClientId"]=I.BufferUtils.base64Encode(I.BufferUtils.utf8Encode(t.clientId)));"idempotentRestPublishing"in t||(t.idempotentRestPublishing=!0);var h=null,c=t.connectivityCheckUrl;if(t.connectivityCheckUrl){var[d,u]=t.connectivityCheckUrl.split("?");h=u?dt(u):{},-1===d.indexOf("://")&&(d="https://"+d),c=d}var v=t.wsConnectivityCheckUrl;v&&-1===v.indexOf("://")&&(v="wss://"+v);return O(_({},t),{primaryDomain:a,maxMessageSize:t.maxMessageSize||Ut.maxMessageSize,timeouts:o,connectivityCheckParams:h,connectivityCheckUrl:c,wsConnectivityCheckUrl:v,headers:l})},defaultGetHeaders:function(t,e){var{format:n,protocolVersion:i=Gt.protocolVersion}=void 0===e?{}:e;return{accept:Kt[null!=n?n:t.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":i.toString(),"Ably-Agent":Wt(t)}},defaultPostHeaders:function(t,e){var{format:n,protocolVersion:i=Gt.protocolVersion}=void 0===e?{}:e,r=Kt[null!=n?n:t.useBinaryProtocol?"msgpack":"json"];return{accept:r,"content-type":r,"X-Ably-Version":i.toString(),"Ably-Agent":Wt(t)}}};function zt(t){return t.includes(".")||t.includes("::")||"localhost"===t}function Ht(t){return zt(t)?t:t.startsWith("nonprod:")?t.replace("nonprod:","")+".realtime.ably-nonprod.net":t+".realtime.ably.net"}function qt(t){return zt(t)?[]:t.startsWith("nonprod:")?Lt(t.replace("nonprod:",""),"ably-realtime-nonprod.com"):Lt(t,"ably-realtime.com")}function Lt(t,e){return["a","b","c","d","e"].map(n=>t+"."+n+".fallback."+e)}function Ft(t){var e=t.fallbackHosts,n=void 0!==t.httpMaxRetryCount?t.httpMaxRetryCount:Ut.httpMaxRetryCount;return e?wt(e,n):[]}function Vt(t){if("string"!=typeof t)throw new z("host must be a string; was a "+typeof t,4e4,400);if(!t.length)throw new z("host must not be zero-length",4e4,400)}function Wt(t){var e=Ut.agent;if(t.agents)for(var n in t.agents)e+=" "+n+"/"+t.agents[n];return e}function Jt(t){if(t.endpoint&&(t.environment||t.restHost||t.realtimeHost))throw new z("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 z("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function $t(t,e,n){var i=n||{};if(i.cipher){t||Pt("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 Kt={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},Gt={protocolVersion:Ut.protocolVersion};var Qt=Ut;var Yt=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){B.logAction(this.logger,B.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)})}},Xt=(t=>(t.Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t))(Xt||{}),Zt=Xt,te=(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))(te||{});var ee=te,ne=Math.pow(2,17);function ie(t){return ut(t)?(t.code||(403===t.statusCode?t.code=40300:(t.code=40170,t.statusCode=401)),t):new z(vt(t),t.code||40170,t.statusCode||401)}function re(t){if(!t)return"";"string"==typeof t&&(t=JSON.parse(t));var e=Object.create(null),n=it(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 se(t,e){if(t.authCallback);else if(t.authUrl);else if(t.key);else if(!t.tokenDetails){var n="authOptions must include valid authentication parameters";throw B.logAction(e,B.LOG_ERROR,"Auth()",n),new Error(n)}}var ae=0;var oe=class{constructor(t,e){if(this.authOptions={},this.client=t,this.tokenParams=e.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,function(t){return t.useTokenAuth||!function(t){return"useTokenAuth"in t&&!t.useTokenAuth}(t)&&(t.authCallback||t.authUrl||t.token||t.tokenDetails)}(e))(function(t){return!t.key&&!t.authCallback&&!t.authUrl})(e)&&B.logAction(this.logger,B.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),se(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 B.logAction(this.logger,B.LOG_ERROR,"Auth()",n),new z(n,40160,401)}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 z("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===ee.Forbidden&&n.client.connection.connectionManager.actOnErrorFromAuthorize(t),t}})()}o(t,e){var n=this;return o(function*(){n.tokenDetails=null,n.t(t,e),se(n.authOptions,n.logger);try{return n.l(!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||L(n.tokenParams),a=n.client;if(r.authCallback)i=r.authCallback;else if(r.authUrl)i=(t,e)=>{var i,s=q({accept:"application/json, text/plain"},r.authHeaders),a=r.authMethod&&"post"===r.authMethod.toLowerCase(),o=r.authUrl.indexOf("?");o>-1&&(i=dt(r.authUrl.slice(o)),r.authUrl=r.authUrl.slice(0,o),a||(r.authParams=q(i,r.authParams)));var l=q({},r.authParams||{},t),h=t=>{var n,i,r=null!=(n=t.body)?n:null,s=null;if(t.error);else{var a=null!=(i=t.headers["content-type"])?i:null;s=Array.isArray(a)?a.join(", "):a}if(t.error)e(t.error,null);else if(t.unpacked)e(null,r);else if(I.BufferUtils.isBuffer(r)&&(r=r.toString()),s){var o=s.indexOf("application/json")>-1,l=s.indexOf("text/plain")>-1||s.indexOf("application/jwt")>-1;if(o||l){if(o){if(r.length>ne)return void e(new z("authUrl response exceeded max permitted length",40170,401),null);try{r=JSON.parse(r)}catch(t){return void e(new z("Unexpected error processing authURL response; err = "+t.message,40170,401),null)}}e(null,r,s)}else e(new z("authUrl responded with unacceptable content-type "+s+", should be either text/plain, application/jwt or application/json",40170,401),null)}else e(new z("authUrl response is missing a content-type header",40170,401),null)};if(a){var c=s||{};c["content-type"]="application/x-www-form-urlencoded";var d=ht(l).slice(1);yt(n.client.http.doUri(Zt.Post,r.authUrl,c,d,i),(t,e)=>h(t||e))}else yt(n.client.http.doUri(Zt.Get,r.authUrl,s||{},null,l),(t,e)=>h(t||e))};else{if(!r.key){throw B.logAction(n.logger,B.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 z("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403)}i=(t,e)=>{yt(n.createTokenRequest(t,r),(t,n)=>e(t,null!=n?n:null))}}"capability"in s&&(s.capability=re(s.capability));return new Promise((t,e)=>{var o=!1,l=n.client.options.timeouts.realtimeRequestTimeout,h=setTimeout(()=>{o=!0;var t="Token request callback timed out after "+l/1e3+" seconds";B.logAction(n.logger,B.LOG_ERROR,"Auth.requestToken()",t),e(new z(t,40170,401))},l);i(s,(i,s,l)=>{if(!o){if(clearTimeout(h),i)return B.logAction(n.logger,B.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+vt(i)),void e(ie(i));if("string"!=typeof s){if("object"!=typeof s||null===s){var c="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof s;return B.logAction(n.logger,B.LOG_ERROR,"Auth.requestToken()",c),void e(new z(c,40170,401))}var d=JSON.stringify(s).length;if(d>ne&&!r.suppressMaxLengthCheck)e(new z("Token request/details object exceeded max permitted stringified size (was "+d+" bytes)",40170,401));else if("issued"in s)t(s);else{if(!("keyName"in s)){var u="Expected token request callback to call back with a token string, token request object, or token details object";return B.logAction(n.logger,B.LOG_ERROR,"Auth.requestToken()",u),void e(new z(u,40170,401))}var v,f,p,g;f=(i,r,s)=>{if(i)return B.logAction(n.logger,B.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+vt(i)),void e(ie(i));s||(r=JSON.parse(r)),t(r)},p="/keys/"+(v=s).keyName+"/requestToken",g=Qt.defaultPostHeaders(n.client.options,{format:"json"}),r.requestHeaders&&q(g,r.requestHeaders),yt(n.client.http.do(Zt.Post,function(t){return a.baseUri(t)+p},g,JSON.stringify(v),null),(t,e)=>t?f(t):f(e.error,e.body,e.unpacked))}}else 0===s.length?e(new z("Token string is empty",40170,401)):s.length>ne?e(new z("Token string exceeded max permitted length (was "+s.length+" bytes)",40170,401)):"undefined"===s||"null"===s?e(new z("Token string was literal null/undefined",40170,401)):"{"!==s[0]||l&&l.indexOf("application/jwt")>-1?t({token:s}):e(new z("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||L(n.tokenParams);var i=e.key;if(!i)throw new z("No key specified",40101,403);var r=i.split(":"),s=r[0],a=r[1];if(!a)throw new z("Invalid key specified",40101,403);if(""===t.clientId)throw new z("clientId can’t be an empty string",40012,400);"capability"in t&&(t.capability=re(t.capability));var o=q({keyName:s},t),l=t.clientId||"",h=t.ttl||"",c=t.capability||"";o.timestamp||(o.timestamp=yield n.h(e&&e.queryTime));var d=o.nonce||(o.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),u=o.timestamp,v=o.keyName+"\n"+h+"\n"+c+"\n"+l+"\n"+u+"\n"+d+"\n";return o.mac=o.mac||((t,e)=>{var n=I.BufferUtils,i=n.utf8Encode(t),r=n.utf8Encode(e),s=n.hmacSha256(i,r);return n.base64Encode(s)})(v,a),o})()}getAuthParams(){var t=this;return o(function*(){if("basic"==t.method)return{key:t.key};var e=yield t.l(!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.l(!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.u(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.u(e.clientId),this.authOptions=e)}l(t){var e=this;return o(function*(){var n=e.tokenDetails;if(n){if(e.p(n.clientId))throw new z("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 n;e.tokenDetails=null}var i=(e.waitingForTokenRequest||(e.waitingForTokenRequest=Yt.create(e.logger))).createPromise();if(null!==e.currentTokenRequestId&&!t)return i;var r,s=e.currentTokenRequestId=ae++,a=null;try{r=yield e.requestToken(e.tokenParams,e.authOptions)}catch(t){a=t}if(e.currentTokenRequestId>s)return 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)})()}u(t){if("string"!=typeof t&&null!==t)throw new z("clientId must be either a string or null",40012,400);if("*"===t)throw new z('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 z(e,40102,401);return B.logAction(this.logger,B.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)}h(t){var e=this;return o(function*(){return e.client.getTimestamp(t||!!e.authOptions.queryTime)})()}};function le(t){var e=[];if(t)for(var n in t)e.push(n+"="+t[n]);return e.join("&")}function he(t,e){return t+(e?"?":"")+le(e)}var ce=class{constructor(t){this.client=t,this.platformHttp=new I.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:B.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}k(t){var e=t.connection,n=e&&e.connectionManager.host;return n?[n].concat(Qt.getFallbackHosts(t.options)):Qt.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 z("http.do called without client",5e4,500)};var l="function"==typeof e?e:function(t){return a.baseUri(t)+e},h=a.T;if(h){if(h.validUntil>Date.now()){var c=yield s.doUri(t,l(h.host),n,i,r);return c.error&&s.platformHttp.shouldFallback(c.error)?(a.T=null,s.do(t,e,n,i,r)):c}a.T=null}var d=s.k(a);if(1===d.length)return s.doUri(t,l(d[0]),n,i,r);var u=null,v=function(){var e=o(function*(e,o){var h=e.shift();u=null!=u?u:new Date;var c=yield s.doUri(t,l(h),n,i,r);return c.error&&s.platformHttp.shouldFallback(c.error)&&e.length?Date.now()-u.getTime()>a.options.timeouts.httpMaxRetryDuration?{error:new z("Timeout for trying fallback hosts retries. Total elapsed time exceeded the "+a.options.timeouts.httpMaxRetryDuration+"ms limit",50003,500)}:v(e,!0):(o&&(a.T={host:h,validUntil:Date.now()+a.options.timeouts.fallbackRetryTimeout}),c)});return function(t,n){return e.apply(this,arguments)}}();return v(d)}catch(t){return{error:new z("Unexpected error in Http.do: "+vt(t),500,5e4)}}})()}doUri(t,e,n,i,r){var s=this;return o(function*(){try{!function(t,e,n,i,r){r.shouldLog(B.LOG_MICRO)&&B.logActionNoStrip(r,B.LOG_MICRO,"Http."+t+"()","Sending; "+he(e,i)+"; Body"+(I.BufferUtils.isBuffer(n)?" (Base64): "+I.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(B.LOG_MICRO)&&function(t,e,n,i,r){t.error?B.logActionNoStrip(r,B.LOG_MICRO,"Http."+e+"()","Received Error; "+he(n,i)+"; Error: "+vt(t.error)):B.logActionNoStrip(r,B.LOG_MICRO,"Http."+e+"()","Received; "+he(n,i)+"; Headers: "+le(t.headers)+"; StatusCode: "+t.statusCode+"; Body"+(I.BufferUtils.isBuffer(t.body)?" (Base64): "+I.BufferUtils.base64Encode(t.body):": "+t.body))}(a,t,e,r,s.logger),a}catch(t){return{error:new z("Unexpected error in Http.doUri: "+vt(t),500,5e4)}}})()}};function de(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(V(i))for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&Array.isArray(i[s])&&de([i],e,s)}var ue=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: "+I.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: "+I.Config.inspect(e));if(J(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: "+I.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||J(e[0])&&J(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:"+I.Config.inspect(e));[a,s]=[i,r]}else"function"==typeof i?s=i:a=i;if(s&&J(a))de([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:"+I.Config.inspect(e));s?de([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){B.logAction(t,B.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(J(s)){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));this.anyOnce.push(a)}else if(Array.isArray(s)){var o=this,l=function(){var t=Array.prototype.slice.call(arguments);if(s.forEach(function(t){o.off(t,l)}),"function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));a.apply(this,t)};s.forEach(function(t){o.on(t,l)})}else{if("string"!=typeof s)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));var h=this.eventsOnce[s]||(this.eventsOnce[s]=[]);if(a){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));h.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)})()}},ve={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},fe=[];Object.keys(ve).forEach(function(t){fe[ve[t]]=t});var pe={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},ge=Object.keys(pe);pe.MODE_ALL=pe.PRESENCE|pe.PUBLISH|pe.SUBSCRIBE|pe.PRESENCE_SUBSCRIBE|pe.ANNOTATION_PUBLISH|pe.ANNOTATION_SUBSCRIBE|pe.OBJECT_SUBSCRIBE|pe.OBJECT_PUBLISH;var me=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function we(){return(we=o(function*(t,e){var{data:n,encoding:i}=yield ye(t.data,t.encoding,e);return t.data=n,t.encoding=i,t})).apply(this,arguments)}function ye(t,e,n){return be.apply(this,arguments)}function be(){return(be=o(function*(t,e,n){var i=n.channelCipher,r=t,s=e?e+"/":"";return I.BufferUtils.isBuffer(r)||(r=I.BufferUtils.utf8Encode(String(r)),s+="utf-8/"),{data:yield i.encrypt(r),encoding:s=s+"cipher+"+i.algorithm}})).apply(this,arguments)}function xe(){return xe=o(function*(t,e){var{data:n,encoding:i}=ke(t.data,t.encoding);return t.data=n,t.encoding=i,null!=e&&e.cipher?function(t,e){return we.apply(this,arguments)}(t,e):t}),xe.apply(this,arguments)}function ke(t,e){if("string"==typeof t||I.BufferUtils.isBuffer(t)||null==t)return{data:t,encoding:e};if(V(t)||Array.isArray(t))return{data:JSON.stringify(t),encoding:e?e+"/json":"json"};throw new z("Data type is unsupported",40013,400)}function Ee(){return(Ee=o(function*(t,e){var{data:n,encoding:i,error:r}=yield Te(t.data,t.encoding,e);if(t.data=n,t.encoding=i,r)throw r})).apply(this,arguments)}function Te(t,e,n){return Ae.apply(this,arguments)}function Ae(){return(Ae=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 l,h=e.split("/"),c=h.length,d="";try{for(;(l=c)>0;){var u=h[--c].match(/([-\w]+)(\+([\w-]+))?/);if(!u)break;switch(d=u[1]){case"base64":a=I.BufferUtils.base64Decode(String(a)),l==h.length&&(s=a);continue;case"utf-8":a=I.BufferUtils.utf8Decode(a);continue;case"json":a=JSON.parse(a);continue;case"cipher":if(null!=r.channelOptions&&r.channelOptions.cipher&&r.channelOptions.channelCipher){var v=u[3],f=r.channelOptions.channelCipher;if(v!=f.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");a=yield f.decrypt(a);continue}throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!r.plugins||!r.plugins.vcdiff)throw new z("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new z("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var p=r.baseEncodedPreviousPayload;"string"==typeof p&&(p=I.BufferUtils.utf8Encode(p));var g=I.BufferUtils.toBuffer(p);a=I.BufferUtils.toBuffer(a),s=a=I.BufferUtils.arrayBufferViewToBuffer(r.plugins.vcdiff.decode(a,g))}catch(t){throw new z("Vcdiff delta decode failed with "+t,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(t){var m=t;i=new z("Error processing the "+d+" encoding, decoder returned ‘"+m.message+"’",m.code||40013,400)}finally{o=l<=0?null:h.slice(0,l).join("/")}}return i?{error:i,data:a,encoding:o}:(r.baseEncodedPreviousPayload=s,{data:a,encoding:o})})).apply(this,arguments)}function Se(){var t=arguments.length>0?"json":"msgpack",{data:e,encoding:n}=Ce(this.data,this.encoding,t);return Object.assign({},this,{encoding:n,data:e})}function Ce(t,e,n){return t&&I.BufferUtils.isBuffer(t)?"msgpack"===n?{data:I.BufferUtils.toBuffer(t),encoding:e}:{data:I.BufferUtils.base64Encode(t),encoding:e?e+"/base64":"base64"}:{data:t,encoding:e}}var _e={encryptData:ye,encodeData:ke,encodeDataForWire:Ce,decodeData:Te};function Oe(t){var e,{id:n,connectionId:i,timestamp:r}=t;switch(t.action){case ve.MESSAGE:e=t.messages;break;case ve.PRESENCE:case ve.SYNC:e=t.presence;break;case ve.ANNOTATION:e=t.annotations;break;case ve.OBJECT:case ve.OBJECT_SYNC:e=t.state;break;default:throw new z("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 Me(t,e){var n="["+e;for(var i in t)"data"===i?"string"==typeof t.data?n+="; data="+t.data:I.BufferUtils.isBuffer(t.data)?n+="; data (buffer)="+I.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 Ie=class{},je=class{constructor(t){var e,n,i,r,s,a,o,l,h,c;this.Platform=I,this.ErrorInfo=z,this.Logger=B,this.Defaults=Qt,this.Utils=N,this.EventEmitter=ue,this.MessageEncoding=_e,this.A=null!=(e=t.plugins)?e:null,this.logger=new B,this.logger.setLog(t.logLevel,t.logHandler),this.S=null!=(i=null==(n=t.plugins)?void 0:n.MsgPack)?i:null;var d=this.options=Qt.normaliseOptions(t,this.S,this.logger);if(d.key){var u=d.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!u){var v="invalid key parameter";throw B.logAction(this.logger,B.LOG_ERROR,"BaseClient()",v),new z(v,40400,404)}d.keyName=u[1],d.keySecret=u[2]}if("clientId"in d){if("string"!=typeof d.clientId&&null!==d.clientId)throw new z("clientId must be either a string or null",40012,400);if("*"===d.clientId)throw new z('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)}this.T=null,this.serverTimeOffset=null,this.http=new ce(this),this.auth=new oe(this,d),this.C=(null==(r=t.plugins)?void 0:r.Rest)?new t.plugins.Rest(this):null,this.O=null!=(a=null==(s=t.plugins)?void 0:s.Crypto)?a:null,this.__FilteredSubscriptions=null!=(l=null==(o=t.plugins)?void 0:o.MessageInteractions)?l:null,this.M=null!=(c=null==(h=t.plugins)?void 0:h.Annotations)?c:null}get rest(){return this.C||Pt("Rest"),this.C}get I(){return this.__FilteredSubscriptions||Pt("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||Pt("Push"),this.j||(this.j=this.push.LocalDevice.load(this)),this.j}baseUri(t){return Qt.getHttpScheme(this.options)+t+":"+Qt.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}};je.Platform=I;var Pe=je,Re=["message.create","message.update","message.delete","meta","message.summary","message.append"];function De(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+=pt(t.data)),e}function Be(){return(Be=o(function*(t,e){return Promise.all(t.map(t=>t.encode(e)))})).apply(this,arguments)}var Ne=class t extends Ie{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 function(t,e){return xe.apply(this,arguments)}(Object.assign(new Ue,e,{action:Re.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 Me(this,"Message")}},Ue=class t extends Ie{toJSON(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return Se.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 Ne,O(_({},n),{action:(i=n.action,Re[i||0]||"unknown")}));try{yield function(t,e){return Ee.apply(this,arguments)}(s,t)}catch(t){B.logAction(e,B.LOG_ERROR,"WireMessage.decode()",vt(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 Me(this,"WireMessage")}},ze=Ne,He=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)}},qe=function(){};function Le(t){var e=t||{},{agent:n}=e;return((t,e)=>{var n={};for(var i in t)A.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&T)for(var i of T(t))e.indexOf(i)<0&&S.call(t,i)&&(n[i]=t[i]);return n})(e,["agent"])}var Fe=class t extends ue{constructor(t,e,n){var i,r,s;super(t.logger),this.P=null,this.R=0,this.retryCount=0,this.history=function(){var t=o(function*(t){var e=this.client.rest.channelMixin;if(t&&t.untilAttach){if("attached"!==this.state)throw new z("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new z("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=>ue.prototype.whenState.call(this,t,this.state),this.name=e,this.channelOptions=$t(null!=(i=t.O)?i:null,this.logger,n),this.client=t,this.D=t.B?new t.B.RealtimePresence(this):null,t.M&&(this.P=new t.M.RealtimeAnnotations(this)),this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new ue(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this.N=!1,this.U={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this.H={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this.q=new ue(this.logger),(null==(r=t.options.plugins)?void 0:r.Push)&&(this.L=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.D||Pt("RealtimePresence"),this.D}get annotations(){return this.P||Pt("Annotations"),this.P}get push(){return this.L||Pt("Push"),this.L}get object(){return this.F||Pt("LiveObjects"),this.F}invalidStateError(){return new z("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&&!V(t.params))return new z("options.params must be an object",4e4,400);if(t&&"modes"in t){if(!Array.isArray(t.modes))return new z("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||!me.includes(String.prototype.toUpperCase.call(n)))return new z("Invalid channel mode: "+n,4e4,400)}}}(t);if(r)throw r;if(e.channelOptions=$t(null!=(n=e.client.O)?n:null,e.logger,t),e.U&&(e.U.channelOptions=e.channelOptions),e.V(t,i))return e.attachImpl(),new Promise((t,n)=>{e.q.once(["attached","update","detached","failed"],function(e){switch(this.event){case"update":case"attached":t();break;default:n(e.reason)}})})})()}V(t,e){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==t?void 0:t.params){var n=Le(t.params),i=Le(e.params);if(Object.keys(n).length!==Object.keys(i).length)return!0;if(!_t(i,n))return!0}return!(!(null==t?void 0:t.modes)||e.modes&&It(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=[ze.fromValues({name:r,data:s})],i=t.length<=2?void 0:t[2];else if(V(r))n=[ze.fromValues(r)],i=t.length<=1?void 0:t[1];else{if(!Array.isArray(r))throw new z("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n=ze.fromValuesArray(r),i=t.length<=1?void 0:t[1]}var a=e.client.options.maxMessageSize,o=yield function(t,e){return Be.apply(this,arguments)}(n,e.channelOptions),l=function(t){for(var e,n=0,i=0;i<t.length;i++)n+=(e=t[i]).size||(e.size=De(e));return n}(o);if(l>a)throw new z("Maximum size of messages that can be published at once exceeded (was "+l+" bytes; limit is "+a+" bytes)",40009,400);e.throwIfUnpublishableState();var h=$e({action:ve.MESSAGE,channel:e.name,messages:o,params:i?ct(i):void 0});return(yield e.sendMessage(h))||{serials:[]}})()}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(t){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.W(!1,null,(t,i)=>t?n(t):e(i))})})()}W(t,e,n){n||(n=t=>{t&&B.logAction(this.logger,B.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 z("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new z("Attach request superseded by a subsequent detach request",9e4,409))}})):n(i.getError())}attachImpl(){var t=$e({action:ve.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&t.encodeModesToFlags(Et(this.channelOptions.modes)),this.N&&t.setFlag("ATTACH_RESUME"),this.H.decodeFailureRecoveryInProgress&&(t.channelSerial=this.H.protocolMessageChannelSerial),this.sendMessage(t).catch(qe)}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 z("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 z("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":i(new z("Detach request superseded by a subsequent attach request",9e4,409))}})})}})()}detachImpl(){var t=$e({action:ve.DETACH,channel:this.name});this.sendMessage(t).catch(qe)}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 z.fromValues(n.invalidStateError());return a&&"object"==typeof a&&!Array.isArray(a)?n.client.I.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.I.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 H("Unable to sync to channel; not attached",4e4)}var t=this.connectionManager;if(!t.activeState())throw t.getError();var e=$e({action:ve.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=$e({action:ve.PRESENCE,channel:e.name,presence:t});yield e.sendMessage(n)})()}sendState(t){var e=this;return o(function*(){var n=$e({action:ve.OBJECT,channel:e.name,state:t});yield e.sendMessage(n)})()}processMessage(t){var e=this;return o(function*(){t.action!==ve.ATTACHED&&t.action!==ve.MESSAGE&&t.action!==ve.PRESENCE&&t.action!==ve.OBJECT&&t.action!==ve.ANNOTATION||e.setChannelSerial(t.channelSerial);var n,i=!1;switch(t.action){case ve.ATTACHED:e.properties.attachSerial=t.channelSerial,e.R=t.getMode(),e.params=t.params||{};var r=t.decodeModesFromFlags();e.modes=r&&kt(r)||void 0;var s=t.hasFlag("RESUMED"),a=t.hasFlag("HAS_PRESENCE"),o=t.hasFlag("HAS_BACKLOG"),l=t.hasFlag("HAS_OBJECTS");if("attached"===e.state){s||(e.D&&e.D.onAttached(a),e.F&&e.F.onAttached(l));var h=new He(e.state,e.state,s,o,t.error);e.q.emit("update",h),s&&!e.channelOptions.updateOnAttached||e.emit("update",h)}else"detaching"===e.state?e.checkPendingState():e.notifyState("attached",t.error,s,a,o,l);break;case ve.DETACHED:var c=t.error?z.fromValues(t.error):new z("Channel detached",90001,404);"detaching"===e.state?e.notifyState("detached",c):"attaching"===e.state?e.notifyState("suspended",c):"attached"!==e.state&&"suspended"!==e.state||e.requestState("attaching",c);break;case ve.SYNC:if(i=!0,n=e.syncChannelSerial=t.channelSerial,!t.presence)break;case ve.PRESENCE:if(!t.presence)break;Oe(t);var d=e.channelOptions;if(e.D){var u=yield Promise.all(t.presence.map(t=>t.decode(d,e.logger)));e.D.setPresence(u,i,n)}break;case ve.OBJECT:case ve.OBJECT_SYNC:if(!e.F||!t.state)return;Oe(t);var v=e.client.connection.connectionManager.getActiveTransportFormat(),f=t.state.map(t=>t.decode(e.client,v));t.action===ve.OBJECT?e.F.handleObjectMessages(f):e.F.handleObjectSyncMessages(f,t.channelSerial);break;case ve.MESSAGE:if("attached"!==e.state)return;Oe(t);var p=t.messages,g=p[0],m=p[p.length-1];if(g.extras&&g.extras.delta&&g.extras.delta.from!==e.H.messageId){var w='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+e.name+'".';B.logAction(e.logger,B.LOG_ERROR,"RealtimeChannel.processMessage()",w),e.J(new z(w,40018,400));break}for(var y=[],b=0;b<p.length;b++){var{decoded:x,err:k}=yield p[b].decodeWithErr(e.U,e.logger);if(y[b]=x,k)switch(k.code){case 40018:return void e.J(k);case 40019:case 40021:return void e.notifyState("failed",k)}}e.H.messageId=m.id,e.H.protocolMessageChannelSerial=t.channelSerial,e.onEvent(y);break;case ve.ANNOTATION:Oe(t);var E=e.channelOptions;if(e.P){var T=yield Promise.all((t.annotations||[]).map(t=>t.decode(E,e.logger)));e.P.$(T)}break;case ve.ERROR:var A=t.error;A&&80016==A.code?e.checkPendingState():e.notifyState("failed",z.fromValues(A))}})()}J(t){this.H.decodeFailureRecoveryInProgress||(this.H.decodeFailureRecoveryInProgress=!0,this.W(!0,t,()=>{this.H.decodeFailureRecoveryInProgress=!1}))}onAttached(){}notifyState(t,e,n,i,r,s){if(this.clearStateTimer(),["detached","suspended","failed"].includes(t)&&(this.properties.channelSerial=null),t!==this.state){this.D&&this.D.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 He(this.state,t,n,r,e),o='Channel state for channel "'+this.name+'"',l=t+(e?"; reason: "+e:"");"failed"===t&&B.logAction(this.logger,B.LOG_ERROR,o,l),"attaching"!==t&&"suspended"!==t&&(this.retryCount=0),"attached"===t&&this.onAttached(),"attached"===t?this.N=!0:"detaching"!==t&&"failed"!==t||(this.N=!1),this.state=t,this.q.emit(t,a),this.emit(t,a)}}requestState(t,e){this.notifyState(t,e),this.checkPendingState()}checkPendingState(){if(this.connectionManager.state.sendEvents)switch(this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync()}}timeoutPendingState(){switch(this.state){case"attaching":var t=new z("Channel attach timed out",90007,408);this.notifyState("suspended",t);break;case"detaching":var e=new z("Channel detach timed out",90007,408);this.notifyState("attached",e);break;default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{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=St(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,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 z("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){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 e.client.rest.channelMixin.getMessage(e,t)})()}updateMessage(t,e,n){var i=this;return o(function*(){return i.sendUpdate(t,"message.update",e,n)})()}deleteMessage(t,e,n){var i=this;return o(function*(){return i.sendUpdate(t,"message.delete",e,n)})()}appendMessage(t,e,n){var i=this;return o(function*(){return 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 z('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=ze.fromValues(O(_({},t),{action:e,version:n})),l=yield o.encode(r.channelOptions),h=$e({action:ve.MESSAGE,channel:r.name,messages:[l],params:i?ct(i):void 0}),c=yield r.sendMessage(h);return{versionSerial:null!=(a=null==(s=null==c?void 0:c.serials)?void 0:s[0])?a:null}})()}getMessageVersions(t,e){var n=this;return o(function*(){return 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 z.fromValues(t.invalidStateError())}})()}},Ve=xt;function We(t){var e=[];if(t)for(var n=0;n<t.length;n++)e.push(t[n].toString());return"[ "+e.join(", ")+" ]"}function Je(t,e,n,i,r,s){return function(t,e,n,i){var r,s,a,o,l;t.error&&(r=z.fromValues(t.error));t.messages&&(s=Ue.fromValuesArray(t.messages));e&&t.presence&&(a=e.WirePresenceMessage.fromValuesArray(t.presence));n&&t.annotations&&(o=n.WireAnnotation.fromValuesArray(t.annotations));i&&t.state&&(l=i.WireObjectMessage.fromValuesArray(t.state,N,_e));return Object.assign(new Ge,O(_({},t),{presence:a,messages:s,annotations:o,state:l,error:r}))}(bt(t,e,s),n,i,r)}function $e(t){return Object.assign(new Ge,t)}function Ke(t,e,n,i){var r="[ProtocolMessage";void 0!==t.action&&(r+="; action="+fe[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="+We(Ue.fromValuesArray(t.messages))),t.presence&&e&&(r+="; presence="+We(e.WirePresenceMessage.fromValuesArray(t.presence))),t.annotations&&n&&(r+="; annotations="+We(n.WireAnnotation.fromValuesArray(t.annotations))),t.state&&i&&(r+="; state="+We(i.WireObjectMessage.fromValuesArray(t.state,N,_e))),t.error&&(r+="; error="+z.fromValues(t.error).toString()),t.auth&&t.auth.accessToken&&(r+="; token="+t.auth.accessToken),t.flags&&(r+="; flags="+ge.filter(t.hasFlag).join(",")),t.params){var l="";st(t.params,function(e){l.length>0&&(l+="; "),l+=e+"="+t.params[e]}),l.length>0&&(r+="; params=["+l+"]")}return r+="]"}var Ge=class{constructor(){this.hasFlag=t=>(this.flags&pe[t])>0}setFlag(t){return this.flags=this.flags|pe[t]}getMode(){return(this.flags||0)&pe.MODE_ALL}encodeModesToFlags(t){t.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){var t=[];return me.forEach(e=>{this.hasFlag(e)&&t.push(e)}),t.length>0?t:void 0}},Qe=class extends ue{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){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 l=0;l<r.length;l++){var h=r[l],c=null==n?void 0:n[l];h.callback(e,c)}0==i.length&&this.emit("idle")}completeAllMessages(t){this.completeMessages("all",t)}resetSendAttempted(){for(var t of this.messages)t.sendAttempted=!1}clear(){this.messages=[],this.emit("idle")}},Ye=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&&[ve.MESSAGE,ve.PRESENCE,ve.ANNOTATION,ve.OBJECT].includes(n)}},Xe=class extends ue{constructor(t){super(t.logger),this.transport=t,this.messageQueue=new Qe(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){this.messageQueue.completeMessages({serial:t,count:e},null,n)}onNack(t,e,n){B.logAction(this.logger,B.LOG_ERROR,"Protocol.onNack()","serial = "+t+"; count = "+e+"; err = "+vt(n)),n||(n=new z("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(B.LOG_MICRO)&&B.logActionNoStrip(this.logger,B.LOG_MICRO,"Protocol.send()","sending msg; "+Ke(t.message,this.transport.connectionManager.realtime.B,this.transport.connectionManager.realtime.M,this.transport.connectionManager.realtime.K)),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()})}},Ze=class{constructor(t,e,n,i){this.previous=t,this.current=e,n&&(this.retryIn=n),i&&(this.reason=i)}},tn={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001};var en,nn,rn={disconnected:()=>z.fromValues({statusCode:400,code:tn.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>z.fromValues({statusCode:400,code:tn.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>z.fromValues({statusCode:400,code:tn.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>z.fromValues({statusCode:400,code:tn.CLOSING,message:"Connection closing"}),closed:()=>z.fromValues({statusCode:400,code:tn.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>z.fromValues({statusCode:500,code:tn.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>z.fromValues({statusCode:500,code:tn.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},sn=$e({action:ve.CLOSE}),an=$e({action:ve.DISCONNECT}),on=class extends ue{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",rn.closed())}disconnect(t){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",t||rn.disconnected())}fail(t){this.isConnected&&this.requestDisconnect(),this.finish("failed",t||rn.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(B.LOG_MICRO)&&B.logActionNoStrip(this.logger,B.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+Ke(t,this.connectionManager.realtime.B,this.connectionManager.realtime.M,this.connectionManager.realtime.K)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),t.action){case ve.HEARTBEAT:B.logActionNoStrip(this.logger,B.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",t.id);break;case ve.CONNECTED:this.onConnect(t),this.emit("connected",t.error,t.connectionId,t.connectionDetails,t);break;case ve.CLOSED:this.onClose(t);break;case ve.DISCONNECTED:this.onDisconnect(t);break;case ve.ACK:this.emit("ack",t.msgSerial,t.count,t.res);break;case ve.NACK:this.emit("nack",t.msgSerial,t.count,t.error);break;case ve.SYNC:this.connectionManager.onChannelMessage(t,this);break;case ve.ACTIVATE:break;case ve.AUTH:yt(this.auth.authorize(),t=>{t&&B.logAction(this.logger,B.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+vt(t))});break;case ve.ERROR:if(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;this.finish("disconnected",e)}onFatalError(t){var e=t&&t.error;this.finish("failed",e)}onClose(t){var e=t&&t.error;this.finish("closed",e)}requestClose(){this.send(sn)}requestDisconnect(){this.send(an)}ping(t){var e={action:ve.HEARTBEAT};t&&(e.id=t),this.send($e(e))}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";B.logAction(this.logger,B.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new z(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})},l=e.options.timeouts.realtimeRequestTimeout;return s=setTimeout(()=>{a.off(["preconnect","disconnected","failed"]),a.dispose(),o.call({event:"disconnected"},new z("Timeout waiting for transport to indicate itself viable",5e4,500))},l),a.on(["failed","disconnected"],o),a.on("preconnect",function(){clearTimeout(s),a.off(["failed","disconnected"],o),r(null,a)}),a.connect(),a}static isAvailable(){throw new z("isAvailable not implemented for transport",5e4,500)}};(nn=en||(en={})).WebSocket="web_socket",nn.Comet="comet",nn.XhrPolling="xhr_polling";var ln="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,hn=()=>{var t;return void 0!==I.WebStorage&&(null==(t=I.WebStorage)?void 0:t.localSupported)},cn=()=>{var t;return void 0!==I.WebStorage&&(null==(t=I.WebStorage)?void 0:t.sessionSupported)},dn=function(){},un="ably-transport-preference";function vn(t){try{return JSON.parse(t)}catch(t){return null}}var fn=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?L(t):{},n=this.options;switch(this.mode){case"resume":e.resume=this.connectionKey;break;case"recover":var i=vn(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=Qt.protocolVersion,e.agent=Wt(this.options),void 0!==n.transportParams&&q(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+="]"}},pn=class t extends ue{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 Qe(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=X(e.transports||Qt.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(en.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(en.XhrPolling)?this.baseTransport=en.XhrPolling:this.transports.includes(en.Comet)&&(this.baseTransport=en.Comet),this.domains=Qt.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,!this.transports.length){var r="no requested transports available";throw B.logAction(this.logger,B.LOG_ERROR,"realtime.ConnectionManager()",r),new Error(r)}var s=I.Config.addEventListener;s&&(cn()&&"function"==typeof e.recover&&s("beforeunload",this.persistConnection.bind(this)),!0===e.closeOnUnload&&s("beforeunload",()=>{this.requestState({state:"closing"})}),s("online",()=>{var t;this.state==this.states.disconnected||this.state==this.states.suspended?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&&this.disconnectAllTransports()}))}static supportedTransports(t){var e={supportedTransports:{}};return this.initTransports(t,e),e.supportedTransports}static initTransports(t,e){var n=_(_({},I.Transports.bundledImplementations),t);[en.WebSocket,...I.Transports.order].forEach(t=>{var i=n[t];i&&i.isAvailable()&&(e.supportedTransports[t]=i)})}initTransports(){t.initTransports(this.realtime.G,this)}createTransportParams(t,e){return new fn(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();this.sessionRecoveryName(),n&&"function"==typeof e?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){var i=vn(this.options.recover);i&&(this.msgSerial=i.msgSerial)}t(n)})}tryATransport(t,e,n){this.proposedTransport=on.tryConnect(this.supportedTransports[e],this,this.realtime.auth,t,(i,r)=>{var s,a=this.state;if(a==this.states.closing||a==this.states.closed||a==this.states.failed)return r&&r.close(),void n(!0);i?!oe.isTokenErr(i.error)||this.errorReason&&oe.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(tn).includes(s.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:i.error}),n(!0))):(this.errorReason=i.error,yt(this.realtime.auth.o(null,null),i=>{i?this.actOnErrorFromAuthorize(i):this.tryATransport(t,e,n)})):(this.setTransportPending(r,t),n(null,r))})}setTransportPending(t,e){var n=e.mode;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){t&&B.logAction(this.logger,B.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+t),this.persistTransportPreference(e);var r=this.state,s=this.states.connected.state;if(r.state==this.states.closing.state||r.state==this.states.closed.state||r.state==this.states.failed.state)return e.disconnect(),!1;if(delete this.pendingTransport,!e.isConnected)return!1;var a=this.activeProtocol;this.activeProtocol=new Xe(e),this.host=e.params.host;var o=i.connectionKey;if(o&&this.connectionKey!=o&&this.setConnection(n,i,!!t),this.onConnectionDetailsUpdate(i,e),I.Config.nextTick(()=>{e.on("connected",(t,n,i)=>{this.onConnectionDetailsUpdate(i,e),this.emit("update",new Ze(s,s,null,t))})}),r.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new Ze(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&&B.logAction(this.logger,B.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 l="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+e.shortName+"; stack = "+(new Error).stack;B.logAction(this.logger,B.LOG_ERROR,"ConnectionManager.activateTransport()",l)}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(n&&n.message,r&&(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&&oe.isTokenErr(n)?"disconnected":e;this.notifyState({state:o,error:n})}else;}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(t,e,n){var i=this.connectionId;(i&&i!==t||!i&&n)&&(this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId,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(){this.lastActivity&&this.connectionId&&(Date.now()-this.lastActivity>this.connectionStateTtl+this.maxIdleInterval&&(this.clearConnection(),this.states.connecting.failState="suspended"))}persistConnection(){if(cn()){var t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:ln.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=H.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,e;return null==(e=(t=rn)[this.state.state])?void 0:e.call(t)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(t){var e=t.current+(t.reason?"; reason: "+t.reason:"");"failed"===t.current&&B.logAction(this.logger,B.LOG_ERROR,"Connection state",e);var n=this.state=this.states[t.current];t.reason&&(this.errorReason=t.reason,this.realtime.connection.errorReason=t.reason),(n.terminal||"suspended"===n.state)&&this.clearConnection(),this.emit("connectionstate",t)}startTransitionTimer(t){this.transitionTimer&&clearTimeout(this.transitionTimer),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,this.notifyState({state:t.failState}))},t.retryDelay)}cancelTransitionTimer(){this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,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(()=>{this.retryTimer=null,this.requestState({state:"connecting"})},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{this.checkWsConnectivity().then(()=>{this.wsCheckResult=!0}).catch(()=>{this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&yt(this.realtime.http.checkConnectivity(),(t,e)=>{!t&&e||(this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new z("Unable to connect (network unreachable)",80003,404)}))})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(t){this.webSocketGiveUpTimer=setTimeout(()=>{var e,n;this.wsCheckResult||this.baseTransport&&(this.abandonedWebSocket=!0,null==(e=this.proposedTransport)||e.dispose(),null==(n=this.pendingTransport)||n.dispose(),this.connectBase(t,++this.connectCounter))},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&&oe.isTokenErr(t.error)&&!(this.errorReason&&oe.isTokenErr(this.errorReason)));if(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=St(s.retryDelay,this.disconnectedRetryCount));var o=new Ze(this.state.state,s.state,a,t.error||(null==(n=(e=rn)[s.state])?void 0:n.call(e)));if(r){var l=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},h=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;h&&h<1e3?setTimeout(l,1e3-h):I.Config.nextTick(l)}else"disconnected"!==i&&"suspended"!==i||this.startRetryTimer(a);("disconnected"===i&&!r||"suspended"===i||s.terminal)&&I.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=i||this.activeProtocol||B.logAction(this.logger,B.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(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 Ze(this.state.state,r.state,null,t.error||(null==(n=(e=rn)[r.state])?void 0:n.call(e)));this.enactStateChange(s),"connecting"==i&&I.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=vn(t.options.recover);n&&this.realtime.channels.recoverChannels(n.channelSerials)}e===this.connectCounter&&this.connectImpl(t,e)})};if(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&&oe.isTokenErr(this.errorReason)?yt(t.o(null,null),i):yt(t.l(!1),i)}}}connectImpl(t,e){if(this.state.state===this.states.connecting.state){var n=this.getTransportPreference();n&&n===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(this.disconnectAllTransports(),this.connectWs(t,++this.connectCounter))}).catch(dn),n&&n===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(t,e):this.connectWs(t,e)}}connectWs(t,e){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){this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,t,!1,e,()=>!0):this.notifyState({state:"disconnected",error:new z("No transports left to try",8e4,404)})}tryTransportWithFallbacks(t,e,n,i,r){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||h():e&&e.dispose())},l=a.shift();if(l){e.host=l;var h=()=>{a.length?this.realtime.http.checkConnectivity?yt(this.realtime.http.checkConnectivity(),(n,l)=>{i===this.connectCounter&&r()&&(n?s(n):l?(e.host=lt(a),this.tryATransport(e,t,o)):s(new z("Unable to connect (network unreachable)",80003,404)))}):s(new H("Internal error: Http.checkConnectivity not set",null,500)):s(new z("Unable to connect (and no more fallback hosts to try)",80003,404))};if(this.forceFallbackHost&&a.length)return this.forceFallbackHost=!1,void h();this.tryATransport(e,t,o)}else s(new z("Unable to connect (no available host)",80003,404))}closeImpl(){this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&this.pendingTransport.close(),this.activeProtocol&&this.activeProtocol.getTransport().close(),this.notifyState({state:"closed"})}onAuthUpdated(t,e){var n;switch(this.state.state){case"connected":var i=null==(n=this.activeProtocol)?void 0:n.getTransport();i&&i.onAuthUpdated&&i.onAuthUpdated(t);var r=$e({action:ve.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":this.disconnectAllTransports();default: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(){this.connectCounter++,this.pendingTransport&&this.pendingTransport.disconnect(),delete this.pendingTransport,this.proposedTransport&&this.proposedTransport.disconnect(),delete this.pendingTransport,this.activeProtocol&&this.activeProtocol.getTransport().disconnect()}send(t,e,n){n=n||dn;var i=this.state;if(i.sendEvents)this.sendImpl(new Ye(t,n));else if(e&&i.queueEvents)this.logger.shouldLog(B.LOG_MICRO),this.queue(t,n);else{var r="rejecting event, queueEvent was "+e+", state was "+i.state;n(this.errorReason||new z(r,9e4,400))}}sendImpl(t){var e=t.message;t.ackRequired&&!t.sendAttempted&&(e.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(t){B.logAction(this.logger,B.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+t.stack)}}queue(t,e){this.queuedMessages.push(new Ye(t,e))}sendQueuedMessages(){for(var t;t=this.queuedMessages.shift();)this.sendImpl(t)}queuePendingMessages(t){t&&t.length&&this.queuedMessages.prepend(t)}failQueuedMessages(t){var e=this.queuedMessages.count();e>0&&(B.logAction(this.logger,B.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+e+" queued messages, err = "+vt(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=>{B.logAction(this.logger,B.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 z("Unable to ping service; not connected",4e4,400);var n=null==(e=t.activeProtocol)?void 0:e.getTransport();if(!n)throw t.getStateError();var i=Date.now(),r=gt();return Rt(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||hn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.get)?void 0:e.call(t,un))}persistTransportPreference(t){var e,n;this.transportPreference=t.shortName,hn()&&(null==(n=null==(e=I.WebStorage)?void 0:e.set)||n.call(e,un,t.shortName))}unpersistTransportPreference(){var t,e;this.transportPreference=null,hn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.remove)||e.call(t,un))}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===ee.Forbidden){var e="Client configured authentication provider returned 403; failing the connection";B.logAction(this.logger,B.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",e),this.notifyState({state:"failed",error:new z(e,80019,403,t)})}else{this.notifyState({state:this.state.failState,error:new z("Client configured authentication provider request failed",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 B.logAction(this.logger,B.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||Qt.wsConnectivityCheckUrl,e=new I.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 cn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.getSession)?void 0:e.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var e,n;return cn()&&(null==(n=null==(e=I.WebStorage)?void 0:e.setSession)?void 0:n.call(e,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,e;return cn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.removeSession)?void 0:e.call(t,this.sessionRecoveryName()))}},gn=class extends ue{constructor(t,e){super(t.logger),this.whenState=t=>ue.prototype.whenState.call(this,t,this.state),this.ably=t,this.connectionManager=new pn(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;I.Config.nextTick(()=>{this.emit(e,t)})}),this.connectionManager.on("update",t=>{I.Config.nextTick(()=>{this.emit("update",t)})})}connect(){this.connectionManager.requestState({state:"connecting"})}ping(){var t=this;return o(function*(){return t.connectionManager.ping()})()}close(){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()}},mn=class t extends Pe{constructor(e){var n,i,r,s;if(super(Qt.objectifyOptions(e,!1,"BaseRealtime",B.defaultLogger)),"string"==typeof EdgeRuntime)throw new z('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.G=t.transportImplementationsFromPlugins(this.options.plugins),this.B=null!=(i=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?i:null,this.K=null!=(s=null==(r=this.options.plugins)?void 0:r.LiveObjects)?s:null,this.connection=new gn(this,this.options),this.Y=new yn(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(t){var e={};return(null==t?void 0:t.WebSocketTransport)&&(e[en.WebSocket]=t.WebSocketTransport),(null==t?void 0:t.XHRPolling)&&(e[en.XhrPolling]=t.XHRPolling),e}get channels(){return this.Y}get clientId(){return this.auth.clientId}connect(){this.connection.connect()}close(){this.connection.close()}};mn.EventEmitter=ue;var wn=mn,yn=class extends ue{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 it(this.all,!0)){var n=this.all[e];n.properties.channelSerial&&(t[e]=n.properties.channelSerial)}return t}recoverChannels(t){for(var e of it(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):B.logAction(e.logger,B.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n)}else B.logAction(e.logger,B.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.W(!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.V(e,n.channelOptions))throw new z("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 Fe(this.realtime,t,e);return n}getDerived(t,e,n){if(e.filter){var i=Mt(e.filter),r=Ot(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]}}},bn=wn,xn=Uint8Array,kn=Uint32Array,En=Math.pow,Tn=new kn(8),An=[],Sn=new kn(64);function Cn(t){return(t-(0|t))*En(2,32)|0}for(var _n,On,Mn=2,In=0;In<64;){for(_n=!0,On=2;On<=Mn/2;On++)Mn%On===0&&(_n=!1);_n&&(In<8&&(Tn[In]=Cn(En(Mn,.5))),An[In]=Cn(En(Mn,1/3)),In++),Mn++}var jn=!!new xn(new kn([1]).buffer)[0];function Pn(t){return jn?t>>>24|(t>>>16&255)<<8|(65280&t)<<8|t<<24:t}function Rn(t,e){return t>>>e|t<<32-e}function Dn(t){var e,n=Tn.slice(),i=t.length,r=8*i,s=512-(r+64)%512-1+r+65,a=new xn(s/8),o=new kn(a.buffer);a.set(t,0),a[i]=128,o[o.length-1]=Pn(r);for(var l=0;l<s/32;l+=16){var h=n.slice();for(e=0;e<64;e++){var c;if(e<16)c=Pn(o[l+e]);else{var d=Sn[e-15],u=Sn[e-2];c=Sn[e-7]+Sn[e-16]+(Rn(d,7)^Rn(d,18)^d>>>3)+(Rn(u,17)^Rn(u,19)^u>>>10)}Sn[e]=c|=0;for(var v=(Rn(h[4],6)^Rn(h[4],11)^Rn(h[4],25))+(h[4]&h[5]^~h[4]&h[6])+h[7]+c+An[e],f=(Rn(h[0],2)^Rn(h[0],13)^Rn(h[0],22))+(h[0]&h[1]^h[2]&(h[0]^h[1])),p=7;p>0;p--)h[p]=h[p-1];h[0]=v+f|0,h[4]=h[4]+v|0}for(e=0;e<8;e++)n[e]=n[e]+h[e]|0}return new xn(new kn(n.map(function(t){return Pn(t)})).buffer)}var Bn,Nn=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(t){for(var e,n,i,r,s="",a=this.base64CharSet,o=t.byteLength,l=o%3,h=o-l,c=0;c<h;c+=3)e=(258048&(r=t[c]<<16|t[c+1]<<8|t[c+2]))>>12,n=(4032&r)>>6,i=63&r,s+=a[(16515072&r)>>18]+a[e]+a[n]+a[i];return 1==l?(e=(3&(r=t[h]))<<4,s+=a[(252&r)>>2]+a[e]+"=="):2==l&&(e=(1008&(r=t[h]<<8|t[h+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&&I.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(I.Config.TextEncoder){var e=(new I.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=Dn(this.toBuffer(t));return this.toArrayBuffer(e)}hmacSha256(t,e){var n=function(t,e){if(t.length>64&&(t=Dn(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(Dn(a),64),Dn(o)}(this.toBuffer(e),this.toBuffer(t));return this.toArrayBuffer(n)}},Un=(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))(Un||{}),zn=Un;function Hn(){return new z("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var qn=(Bn=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)||Qt.connectivityCheckUrl,i=null!=(e=null==t?void 0:t.options.connectivityCheckParams)?e:null,r=!(null==t?void 0:t.options.connectivityCheckUrl),s=_(_({},qn.bundledRequestImplementations),null==t?void 0:t.A),a=s.XHRRequest,l=s.FetchRequest,h=!(!a&&!l);if(!h)throw Hn();I.Config.xhrSupported&&a?(this.supportsAuthHeaders=!0,this.Request=function(){var e=o(function*(e,n,i,r,s){return new Promise(o=>{var l,h=a.createRequest(n,i,r,s,zn.REQ_SEND,null!=(l=t&&t.options.timeouts)?l:null,this.logger,e);h.once("complete",(t,e,n,i,r)=>o({error:t,body:e,headers:n,unpacked:i,statusCode:r})),h.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,e,s=yield this.doUri(Zt.Get,n,null,null,i);return r?!s.error&&"yes"==(null==(t=s.body)?void 0:t.replace(/\n/,"")):!s.error&&((e=s.statusCode)>=200&&e<400)})):I.Config.fetchSupported&&l?(this.supportsAuthHeaders=!0,this.Request=function(){var e=o(function*(e,n,i,r,s){return l(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,e=yield this.doUri(Zt.Get,n,null,null,null);return!e.error&&"yes"==(null==(t=e.body)?void 0:t.replace(/\n/,""))})):this.Request=o(function*(){return{error:h?new H("no supported HTTP transports available",null,400):Hn()}})}get logger(){var t,e;return null!=(e=null==(t=this.client)?void 0:t.logger)?e:B.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 H("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}},Bn.methods=[Zt.Get,Zt.Delete,Zt.Post,Zt.Put,Zt.Patch],Bn.methodsWithoutBody=[Zt.Get,Zt.Delete],Bn.methodsWithBody=[Zt.Post,Zt.Put,Zt.Patch],Bn),Ln=qn,Fn="ablyjs-storage-test",Vn="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,Wn=new class{constructor(){try{Vn.sessionStorage.setItem(Fn,Fn),Vn.sessionStorage.removeItem(Fn),this.sessionSupported=!0}catch(t){this.sessionSupported=!1}try{Vn.localStorage.setItem(Fn,Fn),Vn.localStorage.removeItem(Fn),this.localSupported=!0}catch(t){this.localSupported=!1}}get(t){return this.X(t,!1)}getSession(t){return this.X(t,!0)}remove(t){return this.Z(t,!1)}removeSession(t){return this.Z(t,!0)}set(t,e,n){return this.tt(t,e,n,!1)}setSession(t,e,n){return this.tt(t,e,n,!0)}tt(t,e,n,i){var r={value:e};return n&&(r.expires=Date.now()+n),this.storageInterface(i).setItem(t,JSON.stringify(r))}X(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}Z(t,e){return this.storageInterface(e).removeItem(t)}storageInterface(t){return t?Vn.sessionStorage:Vn.localStorage}},Jn=Ct(),$n="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||$n||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var Kn,Gn,Qn={agent:"browser",logTimestamps:!0,userAgent:Jn.navigator&&Jn.navigator.userAgent.toString(),currentUrl:Jn.location&&Jn.location.href,binaryType:"arraybuffer",WebSocket:Jn.WebSocket,fetchSupported:!!Jn.fetch,xhrSupported:Jn.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:(Gn=Jn.location,!Jn.WebSocket||!Gn||!Gn.origin||Gn.origin.indexOf("http")>-1),useProtocolHeartbeats:!0,supportsBinary:!!Jn.TextDecoder,preferBinary:!1,ArrayBuffer:Jn.ArrayBuffer,atob:Jn.atob,nextTick:"function"==typeof Jn.queueMicrotask?t=>Jn.queueMicrotask(t):t=>Promise.resolve().then(t),addEventListener:Jn.addEventListener,inspect:JSON.stringify,stringByteSize:function(t){return Jn.TextDecoder&&(new Jn.TextEncoder).encode(t).length||t.length},TextEncoder:Jn.TextEncoder,TextDecoder:Jn.TextDecoder,getRandomArrayBuffer:(Kn=o(function*(t){var e=new Uint8Array(t);return Jn.crypto.getRandomValues(e),e.buffer}),function(t){return Kn.apply(this,arguments)}),isWebworker:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,push:{platform:"browser",formFactor:"desktop",storage:Wn}},Yn=Qn;en.XhrPolling;var Xn=en.WebSocket;var Zn=class extends on{constructor(t,e,n){super(t,e,n),this.shortName=Xn,n.heartbeats=I.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!I.Config.WebSocket}createWebSocket(t,e){return this.uri=t+ht(e),new I.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){on.prototype.connect.call(this);var t=this,e=this.params,n=e.options,i=(n.tls?"wss://":"ws://")+this.wsHost+":"+Qt.getPort(n)+"/";yt(this.auth.getAuthParams(),function(n,r){if(!t.isDisposed){for(var s in r)" "+s+": "+r[s]+";";if(n)t.disconnect(n);else{var a=e.getConnectParams(r);try{var o=t.wsConnection=t.createWebSocket(i,a);o.binaryType=I.Config.binaryType,o.onopen=function(){t.onWsOpen()},o.onclose=function(e){t.onWsClose(e)},o.onmessage=function(e){t.onWsData(e.data)},o.onerror=function(e){t.onWsError(e)},o.on&&o.on("ping",function(){t.onActivity()})}catch(e){B.logAction(t.logger,B.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(Ve(t,this.connectionManager.realtime.S,this.params.format))}catch(t){var n="Exception from ws connection when trying to send: "+vt(t);B.logAction(this.logger,B.LOG_ERROR,"WebSocketTransport.send()",n),this.finish("disconnected",new z(n,5e4,500))}else B.logAction(this.logger,B.LOG_ERROR,"WebSocketTransport.send()","No socket connection")}onWsData(t){try{this.onProtocolMessage(Je(t,this.connectionManager.realtime.S,this.connectionManager.realtime.B,this.connectionManager.realtime.M,this.connectionManager.realtime.K,this.format))}catch(t){B.logAction(this.logger,B.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+t.stack)}}onWsOpen(){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){var i=new z("Websocket closed",80003,400);this.finish("disconnected",i)}else{var r=new z("Unclean disconnection of WebSocket ; code = "+n,80003,400);this.finish("disconnected",r)}this.emit("disposed")}onWsError(t){I.Config.nextTick(()=>{this.disconnect(Error(t.message))})}dispose(){this.isDisposed=!0;var t=this.wsConnection;t&&(t.onmessage=function(){},delete this.wsConnection,I.Config.nextTick(()=>{if(!t)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");t.close()}))}},ti={order:["xhr_polling"],bundledImplementations:{}},ei={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[en.XhrPolling,en.WebSocket]};function ni(t,e,n,i,r,s){return ii.apply(this,arguments)}function ii(){return(ii=o(function*(t,e,n,i,r,s){var a,l=new Headers(i||{}),h=t?t.toUpperCase():J(s)?"GET":"POST",c=new AbortController,d=new Promise(t=>{a=setTimeout(()=>{c.abort(),t({error:new H("Request timed out",null,408)})},e?e.options.timeouts.httpRequestTimeout:Qt.TIMEOUTS.httpRequestTimeout)}),u={method:h,headers:l,body:s,signal:c.signal};I.Config.isWebworker||(u.credentials=l.has("authorization")?"include":"same-origin");var v=o(function*(){try{var t=new URLSearchParams(r||{});t.set("rnd",gt());var e=n+"?"+t,i=yield Ct().fetch(e,u);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 l=!!o&&-1===o.indexOf("application/x-msgpack"),h=function(t){var e={};return t.forEach((t,n)=>{e[n]=t}),e}(i.headers);if(i.ok)return{error:null,body:s,headers:h,unpacked:l,statusCode:i.status};var c=function(t,e){if(function(t,e){return!!e.get("x-ably-errorcode")}(0,e))return t.error&&z.fromValues(t.error)}(s,i.headers)||new H("Error response received from server: "+i.status+" body was: "+I.Config.inspect(s),null,i.status);return{error:c,body:s,headers:h,unpacked:l,statusCode:i.status}}catch(c){return clearTimeout(a),{error:c}}})();return Promise.race([d,v])})).apply(this,arguments)}var ri;I.BufferUtils=Nn,I.Http=Ln,I.Config=Yn,I.Transports=ti,I.WebStorage=Wn,Ln.bundledRequestImplementations={},B.initLogHandlers(),I.Defaults=(ri=ei,Object.assign(Ut,ri)),I.Config.agent&&(I.Defaults.agent+=" "+I.Config.agent);class si{constructor(){this.et=new Map}register(t){this.et.has(t.type)||this.et.set(t.type,t)}get(t){return this.et.get(t)}getAll(){return Array.from(this.et.values())}getToolDefinitions(){var t={};for(var e of this.et.values())t[e.type]={description:e.toolDescription,parameters:e.parameters};return t}}function ai(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var oi={type:"collect_email",toolDescription:"ALWAYS use this tool instead of asking for email in plain text. Renders an interactive form to collect the user's name and email. Use whenever the user wants follow-up, a demo, a meeting, pricing info, or shows buying intent. NEVER ask for name or email via plain text.",parameters:{prompt:{type:"string",description:"Message to show above the input fields"}},render(t,e){var n="string"==typeof t.prompt?t.prompt:"What's your name and email?",i=e.primaryColor,r="w-"+Date.now();return'\n <div class="vtilt-widget" data-vtilt-widget-type="collect_email" data-vtilt-widget-id="'+ai(r)+'" data-vtilt-msg-id="'+ai(e.messageId)+'">\n <p style="margin: 0 0 10px 0; font-size: 14px; color: #333;">'+ai(n)+'</p>\n <div style="display: flex; flex-direction: column; gap: 8px;">\n <input type="text" placeholder="Your name" class="vtilt-widget-input" data-vtilt-widget-field="name"\n style="width: 100%; box-sizing: border-box; padding: 10px 12px; border: 1px solid #E5E5E5; border-radius: 12px; font-size: 14px;"\n />\n <div style="display: flex; gap: 8px; align-items: center;">\n <input type="email" placeholder="your@email.com" class="vtilt-widget-input" data-vtilt-widget-field="email"\n style="flex: 1; min-width: 0; padding: 10px 12px; border: 1px solid #E5E5E5; border-radius: 12px; font-size: 14px;"\n />\n <button type="button" data-vtilt-widget-action="submit" data-vtilt-widget-type="collect_email" data-vtilt-widget-id="'+ai(r)+'"\n style="padding: 10px 16px; background: transparent; color: '+i+"; border: 2px solid "+i+'; border-radius: 12px; font-size: 14px; font-weight: 600; cursor: pointer; white-space: nowrap;"\n >Submit</button>\n </div>\n </div>\n </div>\n '},onAction:(t,e,n)=>o(function*(){if("submit"!==t)return{};var i="string"==typeof e.email?e.email.trim():"";if(!i||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))return{};var r=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),s=n.token?{"x-api-key":n.token}:{};try{var a=yield fetch(r,{method:"POST",headers:l({"Content-Type":"application/json"},s),body:JSON.stringify({widget_type:"collect_email",action:"submit",data:{email:i,name:"string"==typeof e.name?e.name.trim():""},channel_id:n.channelId,distinct_id:n.distinctId,message_id:n.messageId})});return{success:!!(yield a.json()).success}}catch(t){return{}}})()};function li(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var hi={type:"escalate_to_human",toolDescription:"Offer to connect the user with a human agent. Use when the user explicitly asks to speak with a person, when you cannot adequately help them, or when the conversation requires human judgment (billing, complaints, complex issues).",parameters:{prompt:{type:"string",description:"Message to show above the connect button"}},render(t,e){var n="string"==typeof t.prompt?t.prompt:"Would you like me to connect you with a team member?",i=e.primaryColor,r="w-esc-"+Date.now();return'\n <div class="vtilt-widget" data-vtilt-widget-type="escalate_to_human" data-vtilt-widget-id="'+li(r)+'" data-vtilt-msg-id="'+li(e.messageId)+'">\n <p style="margin: 0 0 10px 0; font-size: 14px; color: #333;">'+li(n)+'</p>\n <button type="button" data-vtilt-widget-action="escalate" data-vtilt-widget-type="escalate_to_human" data-vtilt-widget-id="'+li(r)+'"\n style="padding: 10px 20px; background: transparent; color: '+i+"; border: 2px solid "+i+'; border-radius: 12px; font-size: 14px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px;"\n ><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="'+i+'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>Connect with a person</button>\n </div>\n '},onAction:(t,e,n)=>o(function*(){if("escalate"!==t)return{};var e=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),i=n.token?{"x-api-key":n.token}:{};try{var r=yield fetch(e,{method:"POST",headers:l({"Content-Type":"application/json"},i),body:JSON.stringify({widget_type:"escalate_to_human",action:"escalate",data:{},channel_id:n.channelId,distinct_id:n.distinctId,message_id:n.messageId})});return{success:!!(yield r.json()).success}}catch(t){return{}}})()},ci="#vtilt-chat-widget",di="\n "+ci+" .vtilt-md {\n max-width: 100%;\n overflow-wrap: anywhere;\n word-break: break-word;\n font-size: inherit;\n line-height: 1.45;\n }\n "+ci+" .vtilt-md * {\n box-sizing: border-box;\n }\n "+ci+" .vtilt-md :is(p, h1, h2, h3, h4, h5, h6, ul, ol, blockquote, pre) {\n margin: 0;\n }\n "+ci+" .vtilt-md p { margin: 0 0 0.5em 0; }\n "+ci+" .vtilt-md p:last-child { margin-bottom: 0; }\n "+ci+" .vtilt-md :is(b, strong) { font-weight: 600; }\n "+ci+" .vtilt-md :is(i, em) { font-style: italic; }\n "+ci+" .vtilt-md u { text-decoration: underline; }\n "+ci+" .vtilt-md :is(h1, h2, h3, h4, h5, h6) {\n font-size: 1em;\n font-weight: 600;\n margin: 0.65em 0 0.35em 0;\n line-height: 1.3;\n }\n "+ci+" .vtilt-md :is(h1, h2, h3):first-child { margin-top: 0.15em; }\n\n /* Lists — flex rows + ::before bullets (beats host list-item / ::marker resets) */\n "+ci+" .vtilt-md :is(ul, ol) {\n list-style: none !important;\n margin: 0.5em 0 !important;\n padding: 0 0 0 0.35em !important;\n }\n "+ci+" .vtilt-md li {\n display: flex !important;\n flex-direction: row !important;\n flex-wrap: wrap !important;\n align-items: flex-start !important;\n gap: 0.35em !important;\n margin: 0.2em 0 !important;\n padding: 0 !important;\n line-height: 1.45;\n list-style: none !important;\n list-style-type: none !important;\n }\n "+ci+' .vtilt-md li::marker {\n content: "" !important;\n font-size: 0 !important;\n color: transparent !important;\n }\n '+ci+" .vtilt-md li::-webkit-list-marker {\n display: none !important;\n }\n "+ci+' .vtilt-md ul > li::before {\n content: "•" !important;\n display: inline-block !important;\n position: static !important;\n flex: 0 0 auto;\n line-height: 1.45;\n }\n '+ci+' .vtilt-md ul ul > li::before {\n content: "◦" !important;\n }\n '+ci+" .vtilt-md ol { counter-reset: vtilt-ol; }\n "+ci+" .vtilt-md ol > li { counter-increment: vtilt-ol; }\n "+ci+' .vtilt-md ol > li::before {\n content: counter(vtilt-ol) "." !important;\n display: inline-block !important;\n position: static !important;\n flex: 0 0 auto;\n min-width: 1.1em;\n line-height: 1.45;\n }\n '+ci+" .vtilt-md ol ol { counter-reset: vtilt-ol; }\n "+ci+" .vtilt-md li > :is(ul, ol) {\n flex: 1 0 100% !important;\n width: 100% !important;\n margin: 0.25em 0 0 0 !important;\n padding-left: 0.75em !important;\n }\n\n "+ci+" .vtilt-md code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n font-size: 0.9em;\n background: rgba(0, 0, 0, 0.06);\n padding: 0.1em 0.35em;\n border-radius: 4px;\n }\n "+ci+" .vtilt-md pre {\n margin: 0.5em 0;\n padding: 0.5em 0.65em;\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.06);\n overflow-x: auto;\n white-space: pre-wrap;\n }\n "+ci+" .vtilt-md pre code { background: none; padding: 0; }\n "+ci+" .vtilt-md blockquote {\n margin: 0.5em 0;\n padding-left: 0.75em;\n border-left: 3px solid rgba(0, 0, 0, 0.15);\n }\n "+ci+" .vtilt-md a { color: inherit; text-decoration: underline; }\n "+ci+" .vtilt-md br { line-height: inherit; }\n\n /* Widget visitor bubble (brand color) */\n "+ci+" .vtilt-user-md code { background: rgba(255, 255, 255, 0.2); }\n "+ci+" .vtilt-user-md pre { background: rgba(255, 255, 255, 0.15); }\n "+ci+" .vtilt-user-md pre code { background: none; }\n "+ci+" .vtilt-user-md blockquote { border-left-color: rgba(255, 255, 255, 0.35); }\n";var ui={none:0,error:1,warn:2,info:3,debug:4},vi="[vTilt]",fi=new Set(["none","error","warn","info","debug"]);function pi(){return"undefined"!=typeof console}function gi(t){var e=t.length>0&&"string"==typeof t[0]?t[0]:"",n=e?t.slice(1):t;return[e?vi+":"+e:vi,...n]}var mi="warn",wi=!1;var yi=null;function bi(){return yi||(yi={setLevel(t,e){void 0===e&&(e=!1),mi=t,e&&(wi=!0)},setLevelFromRemote(t){wi||t&&fi.has(t)&&(mi=t)},getLevel:()=>mi,isLockedByInit:()=>wi,debug(){if(!(ui[mi]<ui.debug)&&pi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...gi(e))}},info(){if(!(ui[mi]<ui.info)&&pi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...gi(e))}},warn(){if(!(ui[mi]<ui.warn)&&pi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.warn(...gi(e))}},error(){if(!(ui[mi]<ui.error)&&pi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.error(...gi(e))}}}),yi}var xi="/api/chat/widget/channels",ki=t=>"/api/chat/widget/channels/"+t+"/messages",Ei=t=>"/api/chat/widget/channels/"+t+"/read",Ti="/api/chat/token/widget";function Ai(t,e,n){return Si.apply(this,arguments)}function Si(){return(Si=o(function*(t,e,n){void 0===n&&(n={});var i=t.getConfig(),r=w(i,e);try{var s=yield fetch(r,l({},n,{headers:l({"Content-Type":"application/json"},y(i),n.headers)}));if(!s.ok)throw new Error("API error: "+s.status);return yield s.json()}catch(t){return bi().error("chat","API request failed:",t),null}})).apply(this,arguments)}var Ci="vtilt-bubble-pos";function _i(t,e,n){var i=t.getBoundingClientRect(),r=i.left-e,s=i.top-n,a=window.innerWidth-t.offsetWidth-r,o=-r,l=window.innerHeight-t.offsetHeight-s,h=-s;return{x:Math.min(Math.max(e,o),a),y:Math.min(Math.max(n,h),l)}}function Oi(t,e,n){t.style.transform="translate3d("+e+"px, "+n+"px, 0)"}function Mi(t,e){var n,i=null!==(n=null==e?void 0:e.handle)&&void 0!==n?n:t,r=0,s=0,a=0,o=0,l=0,h=0,c=!1,d=!1,u=function(){try{var t=localStorage.getItem(Ci);if(!t)return null;var e=JSON.parse(t);if("number"==typeof e.x&&"number"==typeof e.y)return e}catch(t){}return null}();if(u){r=u.x,s=u.y;var v=t.style.transition;t.style.transition="none",Oi(t,r,s);var f=_i(t,r,s);r=f.x,s=f.y,Oi(t,r,s),t.offsetHeight,t.style.transition=v}i.style.cursor="grab",i.style.touchAction="none";var p=e=>{0===e.button&&(c=!0,d=!1,a=e.clientX,o=e.clientY,l=r,h=s,i.setPointerCapture(e.pointerId),i.style.cursor="grabbing",t.style.transition="none")},g=e=>{if(c){var n=e.clientX-a,i=e.clientY-o;if(!(!d&&Math.abs(n)<5&&Math.abs(i)<5)){d=!0;var u={x:l+n,y:h+i},v=_i(t,u.x,u.y);r=v.x,s=v.y,Oi(t,r,s)}}},m=()=>{c&&(c=!1,i.style.cursor="grab",t.style.transition="",d&&function(t){try{localStorage.setItem(Ci,JSON.stringify(t))}catch(t){}}({x:r,y:s}))},w=t=>{d&&(t.stopPropagation(),t.preventDefault(),d=!1)},y=()=>{var e=_i(t,r,s);r=e.x,s=e.y,Oi(t,r,s)};return i.addEventListener("pointerdown",p),i.addEventListener("pointermove",g),i.addEventListener("pointerup",m),i.addEventListener("pointercancel",m),i.addEventListener("click",w,!0),window.addEventListener("resize",y),{destroy(){i.removeEventListener("pointerdown",p),i.removeEventListener("pointermove",g),i.removeEventListener("pointerup",m),i.removeEventListener("pointercancel",m),i.removeEventListener("click",w,!0),window.removeEventListener("resize",y)}}}var Ii="chat",ji=/<!--vtilt:widget:([\s\S]*?)-->/g,Pi="bottom-right",Ri={primaryColor:"#7B68EE",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',borderRadius:"16px"};class Di{constructor(t,e){var n;void 0===e&&(e={}),this.nt=null,this.it=null,this.rt=null,this.st=null,this.ot=Ri,this.lt=null,this.ht=null,this.ct=null,this.dt=null,this.ut=null,this.vt="disconnected",this.ft=null,this.gt=null,this.wt=null,this.yt=[],this.bt=[],this.xt=[],this.kt=null,this.Et=!1,this.Tt=null,this.At=!1,this.St=new si,this.Ct=!1,this._t="",this.Ot="",this.Mt=!1,this.It=0,this._instance=t,this.jt=l({enabled:!0,position:Pi,aiMode:!0,preload:!1},e,{theme:l({},Ri,e.theme)}),this.Pt={isOpen:!1,isVisible:!1!==(null===(n=this.jt.bubble)||void 0===n?void 0:n.visible),isConnected:!1,isLoading:!1,unreadCount:0,currentView:"list",channels:[],channel:null,messages:[],isTyping:!1,typingSender:null,typingSenderType:null,agentLastReadAt:null},this.St.register(oi),this.St.register(hi),this.Rt(),this.Dt(),this.getChannels(),this.Bt()}get isOpen(){return this.Pt.isOpen}get isConnected(){return this.Pt.isConnected}get isLoading(){return this.Pt.isLoading}get unreadCount(){return this.Pt.unreadCount}get channel(){return this.Pt.channel}get channels(){return this.Pt.channels}get currentView(){return this.Pt.currentView}get Nt(){return this.jt.theme||Ri}get Ut(){return this._instance.getDistinctId()||""}zt(t,e,n){var i,r=this._instance.getRemoteConfig(),s=null==r?void 0:r.chatTracking;if("user"===t.sender_type){if(!1===(null==s?void 0:s.trackUserMessages))return}else if(("ai"===t.sender_type||"agent"===t.sender_type)&&!1===(null==s?void 0:s.trackAgentMessages))return;this._instance.capture(b,{$channel_type:"chat",$conversation_id:e,$message_id:t.id,$direction:"user"===t.sender_type?"inbound":"outbound",$sender_type:t.sender_type,$content_preview:(null!==(i=t.content)&&void 0!==i?i:"").slice(0,100),$ai_mode:n})}open(){var t,e;this.Pt.isOpen||(this.Pt.isVisible=!0,this.Pt.isOpen=!0,this.Ht(!0),this.qt(),this.it&&(this.Lt(),this.it.classList.remove("vtilt-closing"),this.it.classList.add("vtilt-opening")),null===(e=(t=this.jt).onWidgetOpen)||void 0===e||e.call(t),this.Bt(),0===this.Pt.channels.length&&this.getChannels())}close(){var t,e,n;if(this.Pt.isOpen){var i=this.Ft();this.Pt.isOpen=!1,this.Ct||!1!==(null===(t=this.jt.bubble)||void 0===t?void 0:t.visible)||(this.Pt.isVisible=!1),this.Ht(!1),this.it&&(this.it.classList.remove("vtilt-opening"),this.it.classList.remove("vtilt-closing")),this.qt();var r=this.Pt.messages.filter(t=>"user"===t.sender_type).length;null===(n=(e=this.jt).onWidgetClose)||void 0===n||n.call(e,{timeOpenSeconds:i,messagesSent:r}),this.Vt()}}toggle(){this.Pt.isOpen?this.close():this.open()}show(){this.Ct=!0,this.Pt.isVisible=!0,this.qt()}hide(){this.Ct=!1,this.Pt.isVisible=!1,this.qt()}getChannels(){var t=this;return o(function*(){t.Pt.isLoading=!0,t.qt();try{var e=yield Ai(t._instance,xi+"?distinct_id="+encodeURIComponent(t.Ut),{method:"GET"});e&&(t.Pt.channels=e.channels||[],t.Pt.unreadCount=t.Pt.channels.reduce((t,e)=>t+(e.unread_count||0),0))}catch(t){bi().error(Ii,"failed to fetch channels:",t)}finally{t.Pt.isLoading=!1,t.qt()}})()}selectChannel(t){var e=this;return o(function*(){yield e.Vt(),e.wt=t,e.Pt.isLoading=!0,e.qt();try{var n=yield Ai(e._instance,xi+"/"+t+"?distinct_id="+encodeURIComponent(e.Ut),{method:"GET"});n&&(e.Pt.channel=n.channel,e.Pt.messages=n.messages||[],e.Pt.currentView="conversation",e.Pt.agentLastReadAt=n.channel.agent_last_read_at||null,e.Tt=n.channel.user_last_read_at||null,e.Pt.unreadCount=e.Wt(),yield e.Jt(n.channel.id),e.Pt.isOpen&&e.$t())}catch(t){bi().error(Ii,"failed to select channel:",t)}finally{e.wt=null,e.Pt.isLoading=!1,e.qt()}})()}createChannel(){var t=this;return o(function*(){var n,i,s;yield t.Vt(),t.Pt.isLoading=!0,t.qt();try{var a=yield Ai(t._instance,xi,{method:"POST",body:JSON.stringify({distinct_id:t.Ut,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})});if(a){t.Pt.channel=a.channel,t.Pt.messages=a.messages||[],t.Pt.currentView="conversation",t.Pt.agentLastReadAt=a.channel.agent_last_read_at||null,t.Tt=a.channel.user_last_read_at||null,t.Pt.unreadCount=t.Wt();var o={id:a.channel.id,status:a.channel.status,ai_mode:a.channel.ai_mode,last_message_at:a.channel.last_message_at,last_message_preview:a.channel.last_message_preview,last_message_sender:a.channel.last_message_sender,unread_count:t.Pt.unreadCount,user_last_read_at:a.channel.user_last_read_at,created_at:a.channel.created_at};t.Pt.channels.some(t=>t.id===a.channel.id)||t.Pt.channels.unshift(o),null===(s=(i=t.jt).onConversationStart)||void 0===s||s.call(i,{channelId:a.channel.id,aiMode:a.channel.ai_mode}),yield t.Jt(a.channel.id)}}catch(t){bi().error(Ii,"failed to create channel:",t)}finally{t.wt=null,t.Pt.isLoading=!1,t.qt()}})()}goToChannelList(){var t=this;return o(function*(){if(yield t.Vt(),t.wt=null,t.gt=null,yield t.Kt(),t.Pt.channel){var e=t.Pt.channels.findIndex(e=>{var n;return e.id===(null===(n=t.Pt.channel)||void 0===n?void 0:n.id)});-1!==e&&(t.Pt.channels[e]=l({},t.Pt.channels[e],{last_message_at:t.Pt.messages.length>0?t.Pt.messages[t.Pt.messages.length-1].created_at:t.Pt.channels[e].last_message_at,last_message_preview:t.Pt.messages.length>0?t.Gt(t.Pt.messages[t.Pt.messages.length-1]):t.Pt.channels[e].last_message_preview,last_message_sender:t.Pt.messages.length>0?t.Pt.messages[t.Pt.messages.length-1].sender_type:t.Pt.channels[e].last_message_sender,unread_count:0}))}t.Pt.channel=null,t.Pt.messages=[],t.Pt.currentView="list",t.Pt.isTyping=!1,t.Pt.typingSender=null,t.Pt.typingSenderType=null,t.qt()})()}sendMessage(t,e){var n=this;return o(function*(){var i,r,s,a,o,h,c=function(t,e){var n,i=function(t){return"string"==typeof t?{raw:t,format:"text"}:"markdown"in t?{raw:t.markdown,format:"markdown"}:"html"in t?{raw:t.html,format:"html"}:"text"in t?{raw:t.text,format:"text"}:null}(t);if(!i)return null;var r="string"==typeof t?null!==(n=null==e?void 0:e.format)&&void 0!==n?n:"text":i.format,s=i.raw.trim();return s?"html"===r?{content:s,content_type:"html",metadata:{}}:"markdown"===r?{content:s,content_type:"text",metadata:{[f]:p}}:{content:s,content_type:"text",metadata:{}}:null}(t,e);if(c){var{content:d,content_type:u,metadata:v}=c;!1!==(null==e?void 0:e.open)&&n.open();var g=null==e?void 0:e.channel;if("new"===g?yield n.createChannel():g&&(yield n.selectChannel(g)),n.Pt.channel&&"conversation"===n.Pt.currentView){var m=null===(i=n.Pt.channel)||void 0===i?void 0:i.id;if(m){var b={id:"temp-"+Date.now(),channel_id:m,sender_type:"user",sender_id:n.Ut||null,sender_name:null,sender_avatar_url:null,content:d,content_type:u,metadata:v,created_at:(new Date).toISOString()};n.Pt.messages.push(b),n.qt();try{var x=n._instance.getConfig(),k=w(x,ki(m)),E=yield fetch(k,{method:"POST",headers:l({"Content-Type":"application/json"},y(x)),body:JSON.stringify({channel_id:m,distinct_id:n.Ut,content:d,content_type:u,metadata:v})});if(!E.ok)throw new Error("API error: "+E.status);if((E.headers.get("content-type")||"").includes("text/plain"))yield n.Qt(E,b,m);else{var T=yield E.json(),A=n.Pt.messages.findIndex(t=>t.id===b.id);-1!==A&&(null==T?void 0:T.message)&&(n.Pt.messages[A]=T.message),(null===(r=null==T?void 0:T.message)||void 0===r?void 0:r.id)&&(null===(a=(s=n.jt).onMessageSent)||void 0===a||a.call(s,{channelId:m,messageId:T.message.id})),(null==T?void 0:T.message)&&n.zt(T.message,m,null!==(h=null===(o=n.Pt.channel)||void 0===o?void 0:o.ai_mode)&&void 0!==h&&h),n.qt()}}catch(t){bi().error(Ii,"failed to send message:",t),n.Pt.messages=n.Pt.messages.filter(t=>t.id!==b.id),n.qt()}}else bi().error(Ii,"no channel to send message to")}else bi().error(Ii,"cannot send message: not in conversation view")}else bi().warn(Ii,"sendMessage: message is empty")})()}markAsRead(){this.$t()}Yt(t){var e=this;return o(function*(){try{var n=e._instance.getConfig(),i=w(n,ki(t)),r=yield fetch(i,{method:"POST",headers:l({"Content-Type":"application/json"},y(n)),body:JSON.stringify({channel_id:t,distinct_id:e.Ut,widget_action_trigger:!0})});if(!r.ok)return;if((r.headers.get("content-type")||"").includes("text/plain")){var s={id:"silent-"+Date.now(),channel_id:t,sender_type:"user",sender_id:e.Ut||null,sender_name:null,sender_avatar_url:null,content:"",content_type:"text",metadata:{},created_at:(new Date).toISOString()};yield e.Qt(r,s,t)}}catch(t){}})()}$t(){var t;if(this.Pt.channel&&!this.At){var e=this.Pt.messages[this.Pt.messages.length-1];if(e){var n=this.Pt.messages.some(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&!this.Xt(t.created_at)),i=this.Pt.channels.find(t=>{var e;return t.id===(null===(e=this.Pt.channel)||void 0===e?void 0:e.id)}),r=(null!==(t=null==i?void 0:i.unread_count)&&void 0!==t?t:0)>0;(n||r)&&(this.Pt.unreadCount=0,this.At=!0,this.qt(),Ai(this._instance,Ei(this.Pt.channel.id),{method:"POST",body:JSON.stringify({channel_id:this.Pt.channel.id,distinct_id:this.Ut,read_at:e.created_at})}).then(t=>{t&&(this.Tt=e.created_at,i&&(i.unread_count=0)),this.Pt.unreadCount=this.Pt.channels.reduce((t,e)=>t+(e.unread_count||0),0),this.At=!1,this.qt()}).catch(()=>{this.At=!1,this.qt()}))}}}Xt(t){return!!this.Tt&&new Date(t)<=new Date(this.Tt)}Wt(){return this.Pt.channel&&this.Tt?this.Pt.messages.filter(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&new Date(t.created_at)>new Date(this.Tt)).length:0}onMessage(t){return this.yt.push(t),()=>{var e=this.yt.indexOf(t);e>-1&&this.yt.splice(e,1)}}onTyping(t){return this.bt.push(t),()=>{var e=this.bt.indexOf(t);e>-1&&this.bt.splice(e,1)}}onConnectionChange(t){return this.xt.push(t),()=>{var e=this.xt.indexOf(t);e>-1&&this.xt.splice(e,1)}}destroy(){var t,e,n;this.Zt(),this.kt&&clearTimeout(this.kt),this.Ht(!1),null===(t=this.st)||void 0===t||t.destroy(),this.st=null,null===(e=this.lt)||void 0===e||e.call(this),this.lt=null,(null===(n=this.nt)||void 0===n?void 0:n.parentNode)&&this.nt.parentNode.removeChild(this.nt),this.yt=[],this.bt=[],this.xt=[]}Bt(){var t=this;return o(function*(){if(!t.ht){t.vt="connecting",t.te(!1);try{var e=yield Ai(t._instance,Ti,{method:"POST",body:JSON.stringify({distinct_id:t.Ut})});if(!(null==e?void 0:e.tokenRequest))return bi().warn(Ii,"failed to get Ably token"),void(t.vt="error");t.ft=e.project_id,t.ht=new bn({plugins:{WebSocketTransport:Zn,FetchRequest:ni},authCallback:(i=o(function*(e,n){var i,r,s;try{var a=null!==(r=null!==(i=t.wt)&&void 0!==i?i:t.gt)&&void 0!==r?r:null===(s=t.Pt.channel)||void 0===s?void 0:s.id,o=yield Ai(t._instance,Ti,{method:"POST",body:JSON.stringify(l({distinct_id:t.Ut},a&&{channel_id:a}))});(null==o?void 0:o.tokenRequest)?n(null,o.tokenRequest):n("Failed to refresh token",null)}catch(t){n(String(t),null)}}),function(t,e){return i.apply(this,arguments)}),authMethod:"POST"}),yield t.ht.auth.authorize(e.tokenRequest),t.ht.connection.on("connected",()=>{t.vt="connected",t.Pt.isConnected=!0,t.te(!0)}),t.ht.connection.on("disconnected",()=>{t.vt="disconnected",t.Pt.isConnected=!1,t.te(!1)}),t.ht.connection.on("failed",()=>{t.vt="error",t.Pt.isConnected=!1,t.te(!1)}),t.ht.connect();var n="chat:"+t.ft+":notifications";t.ct=t.ht.channels.get(n),t.ct.subscribe("notification",e=>{t.ee(e.data)})}catch(e){bi().error(Ii,"failed to connect to Ably:",e),t.vt="error"}var i}})()}Kt(t){var e=this;return o(function*(){if(!e.ht)return!1;try{var n=yield Ai(e._instance,Ti,{method:"POST",body:JSON.stringify(l({distinct_id:e.Ut},t&&{channel_id:t}))});return(null==n?void 0:n.tokenRequest)?(yield e.ht.auth.authorize(n.tokenRequest),e.gt=null!=t?t:null,!0):(bi().warn(Ii,"failed to refresh Ably token",null!=t?t:"(list)"),!1)}catch(t){return bi().error(Ii,"failed to refresh Ably token:",t),!1}})()}Jt(t){var e=this;return o(function*(){if(yield e.Bt(),e.ht&&e.ft)if(yield e.Kt(t)){var n="chat:"+e.ft+":"+t;try{e.dt=e.ht.channels.get(n),yield e.dt.attach(),e.dt.subscribe("message",t=>{e.ne(t.data)}),e.dt.subscribe("read",t=>{e.ie(t.data)}),e.ut=e.ht.channels.get(n+":typing"),yield e.ut.attach(),e.ut.subscribe("typing",t=>{e.re(t.data)})}catch(t){bi().error(Ii,"failed to attach chat/typing channels:",t),yield e.Vt(),e.gt=null}}else bi().warn(Ii,"skipping channel subscribe — no Ably capability for",t)})()}Vt(){var t=this;return o(function*(){var e=t.ht,n=t.dt,i=t.ut;t.dt=null,t.ut=null,t.gt=null;var r=function(){var t=o(function*(t){if(t&&e){var n=t.name;t.unsubscribe();try{yield t.detach()}catch(t){}e.channels.release(n)}});return function(e){return t.apply(this,arguments)}}();yield Promise.all([r(n),r(i)])})()}Zt(){var t=this;return o(function*(){yield t.Vt(),t.ct&&(t.ct.unsubscribe(),t.ct=null),t.ht&&(t.ht.close(),t.ht=null),t.ft=null,t.vt="disconnected",t.Pt.isConnected=!1})()}ee(t){var e,n,i,{type:r,channel_id:s,data:a}=t;if("new_channel"!==r){if("channel_updated"===r&&a){var o=this.Pt.channels.findIndex(t=>t.id===s);if(-1!==o){var h=l({},this.Pt.channels[o]);if(void 0!==a.last_message_at&&(h.last_message_at=a.last_message_at),void 0!==a.last_message_preview&&(h.last_message_preview=a.last_message_preview),void 0!==a.last_message_sender&&(h.last_message_sender=a.last_message_sender),void 0!==a.user_unread_count)this.Pt.isOpen&&(null===(e=this.Pt.channel)||void 0===e?void 0:e.id)===s||(h.unread_count=a.user_unread_count);void 0!==a.status&&(h.status=a.status),void 0!==a.ai_mode&&(h.ai_mode=a.ai_mode),this.Pt.channels[o]=h,this.Pt.channels.sort((t,e)=>{var n=t.last_message_at||t.created_at,i=e.last_message_at||e.created_at;return new Date(i).getTime()-new Date(n).getTime()}),this.Pt.unreadCount=this.Pt.channels.reduce((t,e)=>t+(e.unread_count||0),0)}(null===(n=this.Pt.channel)||void 0===n?void 0:n.id)===s&&"closed"===a.status&&(this.Pt.channel=l({},this.Pt.channel,{status:"closed"})),this.qt()}if("channel_closed"===r){var c=this.Pt.channels.findIndex(t=>t.id===s);-1!==c&&(this.Pt.channels[c]=l({},this.Pt.channels[c],{status:"closed"})),(null===(i=this.Pt.channel)||void 0===i?void 0:i.id)===s&&(this.Pt.channel=l({},this.Pt.channel,{status:"closed"})),this.qt()}}else this.getChannels()}ne(t){var e,n,i,r,s,a;if("ai"===t.sender_type){var o=this.Pt.messages.findIndex(t=>t.id.startsWith("temp-ai-"));if(-1!==o){var l=null!==(e=this.Pt.messages[o].metadata)&&void 0!==e?e:{};this.Pt.messages[o]=t,!(null!==(n=this.Pt.messages[o].metadata)&&void 0!==n?n:{}).widgets&&l.et&&(this.Pt.messages[o].metadata.et=l.et)}else{if(this.Pt.messages.some(e=>e.id===t.id))return;this.Pt.messages.push(t)}}else{if(this.Pt.messages.some(e=>e.id===t.id))return;if("user"===t.sender_type&&t.sender_id===this.Ut){var h=this.Pt.messages.findIndex(e=>e.id.startsWith("temp-")&&e.content===t.content&&e.content_type===t.content_type&&"user"===e.sender_type);return void(-1!==h&&(this.Pt.messages[h]=t,this.qt()))}this.Pt.messages.push(t)}if("ai"===t.sender_type||"agent"===t.sender_type){if(this.Pt.isOpen)setTimeout(()=>this.$t(),100);else{this.Pt.unreadCount++;var c=this.Pt.channels.find(e=>e.id===t.channel_id);c&&(c.unread_count=(c.unread_count||0)+1)}null===(r=(i=this.jt).onMessageReceived)||void 0===r||r.call(i,{channelId:t.channel_id,messageId:t.id,senderType:t.sender_type}),this.zt(t,t.channel_id,null!==(a=null===(s=this.Pt.channel)||void 0===s?void 0:s.ai_mode)&&void 0!==a&&a)}this.Pt.isTyping=!1,this.Pt.typingSender=null,this.Pt.typingSenderType=null,this.yt.forEach(e=>e(t)),this.qt()}re(t){if("user"!==t.sender_type){this.Pt.isTyping=t.is_typing,this.Pt.typingSenderType=t.is_typing?t.sender_type:null;var e="ai"===t.sender_type?null:t.sender_name||("agent"===t.sender_type?"Agent":null);this.Pt.typingSender=t.is_typing?e:null,this.bt.forEach(n=>n(t.is_typing,e||"")),this.qt()}}ie(t){"agent"===t.reader_type&&(this.Pt.agentLastReadAt=t.read_at,this.qt())}te(t){this.xt.forEach(e=>e(t))}Rt(){var t,n,i,s;if(r){var a=this.Nt;this.ot={primaryColor:null!==(t=a.primaryColor)&&void 0!==t?t:Ri.primaryColor,fontFamily:null!==(n=a.fontFamily)&&void 0!==n?n:Ri.fontFamily,borderRadius:null!==(i=a.borderRadius)&&void 0!==i?i:Ri.borderRadius};var o,l,h=this.jt.position||Pi;this.nt=r.createElement("div"),this.nt.id="vtilt-chat-container",this.nt.setAttribute("style",function(t,e){return void 0===e&&(e="bottom-right"),"\n position: fixed;\n bottom: 20px;\n "+("bottom-right"===e?"right: 20px;":"left: 20px;")+"\n z-index: 999999;\n font-family: "+t.fontFamily+";\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n "}(this.ot,h)),this._t=this.nt.getAttribute("style")||"",this.rt=r.createElement("div"),this.rt.id="vtilt-chat-bubble",this.rt.innerHTML='\n <svg width="28" height="28" viewBox="0 0 28 28" fill="white">\n <path d="M14 3C7.925 3 3 7.262 3 12.5c0 2.56 1.166 4.884 3.063 6.606L4.5 24l5.25-2.625C11.1 21.79 12.52 22 14 22c6.075 0 11-4.262 11-9.5S20.075 3 14 3z"/>\n </svg>\n <div class="vtilt-chat-badge" style="\n display: none;\n position: absolute;\n top: -4px;\n right: -4px;\n background: #E53935;\n color: white;\n font-size: 11px;\n font-weight: 700;\n min-width: 20px;\n height: 20px;\n border-radius: 10px;\n align-items: center;\n justify-content: center;\n padding: 0 6px;\n box-sizing: border-box;\n border: 2px solid white;\n ">0</div>\n ',this.rt.setAttribute("style",(o=this.ot,"\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: "+(l=o.primaryColor)+";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 16px "+l+"66;\n transition: transform 0.2s ease, box-shadow 0.2s ease;\n position: relative;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n ")),this.nt.appendChild(this.rt),this.it=r.createElement("div"),this.it.id="vtilt-chat-widget",this.it.innerHTML=function(t){var e=t.primaryColor;return'\n <div class="vtilt-chat-header" style="\n background: #ffffff;\n border-bottom: 1px solid #E5E5E5;\n padding: 18px 16px;\n padding-top: max(18px, env(safe-area-inset-top, 18px));\n display: flex;\n align-items: center;\n justify-content: space-between;\n min-height: 60px;\n box-sizing: border-box;\n flex-shrink: 0;\n ">\n <div style="font-weight: 600; font-size: 17px; color: #000000;">Messages</div>\n <button class="vtilt-chat-close" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n </div>\n \n <div class="vtilt-chat-content" style="\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n min-height: 0;\n background: #ffffff;\n ">\n </div>\n \n <div class="vtilt-chat-loader" style="\n display: none;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(255, 255, 255, 0.95);\n align-items: center;\n justify-content: center;\n z-index: 10;\n ">\n <div style="\n width: 32px;\n height: 32px;\n border: 3px solid #E5E5E5;\n border-top-color: '+e+';\n border-radius: 50%;\n animation: vtilt-spin 0.8s linear infinite;\n "></div>\n </div>\n \n <style>\n @keyframes vtilt-spin { to { transform: rotate(360deg); } }\n @keyframes vtilt-open {\n from { opacity: 0; transform: scale(0.4); }\n to { opacity: 1; transform: scale(1); }\n }\n \n #vtilt-chat-bubble { transition: transform 0.15s ease, box-shadow 0.15s ease; }\n #vtilt-chat-bubble:hover { transform: scale(1.05); box-shadow: 0 6px 20px '+e+"73; }\n #vtilt-chat-bubble:active { transform: scale(0.95); }\n .vtilt-draggable #vtilt-chat-bubble:hover,\n .vtilt-draggable #vtilt-chat-bubble:active { transform: none; }\n \n /* transform-origin is set in JS by _constrainWidgetToViewport() to match widget position */\n #vtilt-chat-widget.vtilt-opening { animation: vtilt-open 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards; }\n \n .vtilt-chat-content { transition: opacity 0.15s ease; }\n \n .vtilt-chat-close:hover { color: #000 !important; background: #F0F0F0 !important; }\n .vtilt-chat-back:hover { color: #000 !important; background: #F0F0F0 !important; }\n \n .vtilt-chat-input-container > div:first-child:focus-within { \n border-color: "+e+" !important; \n box-shadow: 0 0 0 2px "+e+"20 !important; \n }\n .vtilt-chat-input { \n -webkit-text-size-adjust: 100%; \n }\n .vtilt-chat-input:focus { \n outline: none !important; \n }\n .vtilt-chat-input::placeholder { \n color: #999999; \n }\n .vtilt-chat-input::-webkit-scrollbar { \n width: 4px; \n }\n .vtilt-chat-input::-webkit-scrollbar-track { \n background: transparent; \n }\n .vtilt-chat-input::-webkit-scrollbar-thumb { \n background: rgba(0, 0, 0, 0.2); \n border-radius: 2px; \n }\n .vtilt-chat-input::-webkit-scrollbar-thumb:hover { \n background: rgba(0, 0, 0, 0.3); \n }\n /* Firefox scrollbar */\n .vtilt-chat-input { \n scrollbar-width: thin; \n scrollbar-color: rgba(0, 0, 0, 0.2) transparent; \n }\n .vtilt-chat-attach:hover,\n .vtilt-chat-emoji:hover,\n .vtilt-chat-gif:hover,\n .vtilt-chat-mic:hover {\n color: #333333 !important;\n }\n .vtilt-chat-attach:active,\n .vtilt-chat-emoji:active,\n .vtilt-chat-gif:active,\n .vtilt-chat-mic:active {\n color: #000000 !important;\n }\n .vtilt-chat-send:not(:disabled):hover {\n opacity: 0.9 !important;\n transform: scale(1.05);\n }\n .vtilt-chat-send:not(:disabled):active {\n opacity: 0.8 !important;\n transform: scale(0.95);\n }\n .vtilt-chat-send:disabled {\n cursor: not-allowed !important;\n }\n \n .vtilt-chat-send { transition: opacity 0.1s ease; }\n\n "+di+"\n \n /* Widget styles */\n .vtilt-widget { margin-top: 10px; }\n .vtilt-widget-input { font-family: inherit; }\n .vtilt-widget-input:focus { outline: none; border-color: #999; }\n \n .vtilt-chat-new-channel { transition: opacity 0.1s ease; }\n .vtilt-chat-new-channel:hover { opacity: 0.9; }\n .vtilt-chat-new-channel:active { opacity: 0.8; }\n \n .vtilt-channel-item { transition: background 0.1s ease; cursor: pointer; }\n .vtilt-channel-item:hover { background: #F5F5F5 !important; }\n .vtilt-channel-item:active { background: #EBEBEB !important; }\n \n @keyframes vtilt-slide-up {\n from { opacity: 0; transform: translateY(100%); }\n to { opacity: 1; transform: translateY(0); }\n }\n\n @media (max-width: 480px) {\n #vtilt-chat-bubble { width: 56px !important; height: 56px !important; }\n #vtilt-chat-bubble svg { width: 24px !important; height: 24px !important; }\n #vtilt-chat-widget.vtilt-opening {\n animation: vtilt-slide-up 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards !important;\n transform-origin: bottom center !important;\n }\n }\n \n @media (prefers-reduced-motion: reduce) {\n * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }\n }\n </style>\n "}(this.ot),this.it.setAttribute("style","\n display: none;\n flex-direction: column;\n position: absolute;\n bottom: 0;\n right: 0;\n width: 380px;\n max-width: calc(100vw - 40px);\n height: 600px;\n max-height: calc(100vh - 40px);\n max-height: calc(100dvh - 40px);\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 5px 40px rgba(0, 0, 0, 0.16);\n overflow: hidden;\n "),this.nt.appendChild(this.it),r.body.appendChild(this.nt),(null===(s=this.jt.bubble)||void 0===s?void 0:s.draggable)&&this.nt&&this.rt&&(this.nt.classList.add("vtilt-draggable"),this.st=Mi(this.nt,{handle:this.rt}));var c=()=>{this.Pt.isOpen&&(this.se()?(this.ae(),this.Ht(!0)):(this.oe(),this.Ht(!1),this.Lt()),this.nt&&this.it&&this.rt&&(this.nt.style.display=this.Pt.isVisible?"block":"none",this.it.style.display=this.Pt.isOpen?"flex":"none",this.rt.style.display=this.Pt.isOpen?"none":"flex"))},d=e;d&&(d.addEventListener("resize",c),this.lt=()=>d.removeEventListener("resize",c))}}Dt(){var t,e,n,i,r;null===(t=this.rt)||void 0===t||t.addEventListener("click",()=>this.toggle()),null===(n=null===(e=this.it)||void 0===e?void 0:e.querySelector(".vtilt-chat-close"))||void 0===n||n.addEventListener("click",()=>this.close()),null===(i=this.it)||void 0===i||i.addEventListener("click",t=>{var e,n,i,r=null===(n=null===(e=t.target)||void 0===e?void 0:e.closest)||void 0===n?void 0:n.call(e,"[data-vtilt-widget-action]");if(r){var s=r.getAttribute("data-vtilt-widget-type"),a=r.getAttribute("data-vtilt-widget-action");if(s&&a){var o=r;if(!o.disabled){t.preventDefault(),t.stopPropagation();var l=this.St.get(s);if(l){var h=r.closest(".vtilt-widget"),c={};h&&h.querySelectorAll("[data-vtilt-widget-field]").forEach(t=>{var e=t.getAttribute("data-vtilt-widget-field");e&&(c[e]=t.value)});var d=this.le(),u=null==h?void 0:h.closest("[data-vtilt-msg-id]");d.messageId=null!==(i=null==u?void 0:u.getAttribute("data-vtilt-msg-id"))&&void 0!==i?i:"",o.disabled=!0,o.style.opacity="0.6",l.onAction(a,c,d).then(t=>{t.success?(this.he(d.messageId,s,c),this.qt(),"escalate_to_human"!==s&&this.Yt(d.channelId)):this.qt()}).catch(()=>{this.qt()})}}}}}),null===(r=this.it)||void 0===r||r.addEventListener("keydown",t=>{var e=t;if("Enter"===e.key){var n=e.target;if("email"===(null==n?void 0:n.type)){t.preventDefault();var i=n.closest(".vtilt-widget"),r=null==i?void 0:i.querySelector("[data-vtilt-widget-action]");null==r||r.click()}}})}he(t,e,n){var i,r,s;if(t){var a=this.Pt.messages.find(e=>e.id===t);if(a){var o=null!==(i=a.metadata)&&void 0!==i?i:{},h=(null!==(s=null!==(r=o.et)&&void 0!==r?r:o.widgets)&&void 0!==s?s:[]).map(t=>{if(t.type!==e)return t;var i=l({},t,{submitted:!0});return n.email&&(i.submittedEmail=String(n.email).trim()),n.name&&(i.submittedName=String(n.name).trim()),i});a.metadata.widgets=h,o.et&&(a.metadata.et=h)}}}ce(){this.ut&&(this.Et||(this.Et=!0,this.de(!0)),this.kt&&clearTimeout(this.kt),this.kt=setTimeout(()=>{this.Et=!1,this.de(!1)},2e3))}de(t){this.ut&&this.ut.publish("typing",{sender_type:"user",sender_id:this.Ut,sender_name:null,is_typing:t}).catch(t=>{bi().warn(Ii,"failed to publish typing indicator:",t)})}ue(){var t,e,n=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-input");if(n){var i=n.value.trim();if(i){this.Et&&(this.Et=!1,this.de(!1)),this.kt&&(clearTimeout(this.kt),this.kt=null),this.sendMessage(i),n.value="",n.style.height="auto",n.style.height="60px",n.focus();var r=null===(e=this.it)||void 0===e?void 0:e.querySelector(".vtilt-chat-send");r&&(r.disabled=!0,r.style.background="#E5E5E5",r.style.color="#999999",r.style.cursor="not-allowed",r.style.opacity="0.6")}}}qt(){var t;if(this.nt&&this.it&&this.rt){this.Pt.isOpen&&this.se()?this.ae():(this.oe(),this.Pt.isOpen&&(this.nt.style.minWidth="60px",this.nt.style.minHeight="60px",requestAnimationFrame(()=>this.Lt()))),this.nt.style.display=this.Pt.isVisible?"block":"none",this.it.style.display=this.Pt.isOpen?"flex":"none",this.rt.style.display=this.Pt.isOpen?"none":"flex",this.Pt.isOpen||(this.nt.style.minWidth="",this.nt.style.minHeight="");var e=this.rt.querySelector(".vtilt-chat-badge");e&&(e.style.display=this.Pt.unreadCount>0?"flex":"none",e.textContent=String(this.Pt.unreadCount));var n=this.it.querySelector(".vtilt-chat-content");if(n)if("list"===this.Pt.currentView)n.innerHTML=this.ve(),this.fe();else n.querySelector(".vtilt-chat-input")||(n.innerHTML=this.pe(),this.ge()),this.me();this.we();var i=this.it.querySelector(".vtilt-chat-loader");i&&(i.style.display=this.Pt.isLoading?"flex":"none");var s=this.it.querySelector(".vtilt-chat-typing");if(s){s.style.display=this.Pt.isTyping&&"conversation"===this.Pt.currentView?"flex":"none";var a=s.querySelector(".vtilt-chat-typing-text");a&&this.Pt.isTyping&&("ai"===this.Pt.typingSenderType?a.textContent="AI is thinking...":this.Pt.typingSender?a.textContent=this.Pt.typingSender+" is typing...":a.textContent="Agent is typing...")}if("conversation"===this.Pt.currentView){var o="closed"===(null===(t=this.Pt.channel)||void 0===t?void 0:t.status),l=this.it.querySelector(".vtilt-chat-input-container"),h=this.it.querySelector(".vtilt-chat-closed-banner");if(o){if(l&&(l.style.display="none"),!h&&r){var c=r.createElement("div");c.className="vtilt-chat-closed-banner",c.style.cssText="padding: 12px 16px; padding-bottom: max(12px, env(safe-area-inset-bottom, 12px)); border-top: 1px solid #E5E5E5; text-align: center; background: #FAFAFA; flex-shrink: 0;",c.innerHTML='<span style="font-size: 14px; color: #888;">This conversation has been closed.</span>';var d=this.it.querySelector(".vtilt-chat-content");(null==d?void 0:d.parentNode)&&d.parentNode.appendChild(c)}}else l&&(l.style.display=""),h&&h.remove()}}}se(){return!!e&&e.innerWidth<=480}ae(){this.nt&&this.it&&(this.Mt||(this.Ot=this.nt.style.transform),this.nt.setAttribute("style","\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n font-family: "+this.ot.fontFamily+";\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n transform: none;\n "),this.it.setAttribute("style","\n flex-direction: column;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n background: #ffffff;\n border-radius: 0;\n box-shadow: none;\n overflow: hidden;\n "),this.Mt=!0)}oe(){this.Mt&&this.nt&&this.it&&(this.nt.setAttribute("style",this._t),this.Ot&&(this.nt.style.transform=this.Ot),this.it.setAttribute("style","\n display: none;\n flex-direction: column;\n position: absolute;\n bottom: 0;\n right: 0;\n width: 380px;\n max-width: calc(100vw - 40px);\n height: 600px;\n max-height: calc(100vh - 40px);\n max-height: calc(100dvh - 40px);\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 5px 40px rgba(0, 0, 0, 0.16);\n overflow: hidden;\n "),this.Mt=!1)}Ht(t){var n;if(this.se()&&r){var i=r.documentElement;t?(this.It=null!==(n=null==e?void 0:e.scrollY)&&void 0!==n?n:0,i.style.setProperty("overflow","hidden","important"),r.body.style.setProperty("overflow","hidden","important"),r.body.style.setProperty("position","fixed","important"),r.body.style.setProperty("width","100%","important"),r.body.style.top="-"+this.It+"px"):(i.style.removeProperty("overflow"),r.body.style.removeProperty("overflow"),r.body.style.removeProperty("position"),r.body.style.removeProperty("width"),r.body.style.top="",null==e||e.scrollTo(0,this.It))}}Lt(){if(this.nt&&this.it&&this.Pt.isOpen&&e&&!this.se()){var t=this.nt.getBoundingClientRect(),n="0",i="auto",r="0",s="auto",a=t.width-380,o=t.height-600,l=t.right-380,h=t.bottom-600;l<20&&(s=(a=20-t.left)+"px",r="auto"),h<20&&(i=(o=20-t.top)+"px",n="auto"),this.it.style.left=s,this.it.style.right=r,this.it.style.top=i,this.it.style.bottom=n;var c=t.width-a,d=t.height-o;this.it.style.transformOrigin=c+"px "+d+"px",this.it.style.maxWidth="",this.it.style.maxHeight=""}}we(){var t,e,n=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-header");if(n){var i=this.Nt.primaryColor;if("list"===this.Pt.currentView)n.style.cssText="\n background: #ffffff;\n border-bottom: 1px solid #E5E5E5;\n padding: 18px 16px;\n padding-top: max(18px, env(safe-area-inset-top, 18px));\n display: flex;\n align-items: center;\n justify-content: space-between;\n min-height: 60px;\n box-sizing: border-box;\n flex-shrink: 0;\n ",n.innerHTML='\n <div style="font-weight: 600; font-size: 17px; color: #000000;">Messages</div>\n <button class="vtilt-chat-close" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n ';else{var r=null===(e=this.Pt.channel)||void 0===e?void 0:e.ai_mode;n.style.cssText="\n background: #ffffff;\n border-bottom: 1px solid #E5E5E5;\n padding: 12px 16px;\n padding-top: max(12px, env(safe-area-inset-top, 12px));\n display: flex;\n align-items: center;\n gap: 12px;\n min-height: 60px;\n box-sizing: border-box;\n flex-shrink: 0;\n ",n.innerHTML='\n <button class="vtilt-chat-back" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin-left: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M15 18l-6-6 6-6"></path>\n </svg>\n </button>\n <div style="\n width: 44px;\n height: 44px;\n border-radius: 50%;\n background: '+(r?i:"#DEDEDE")+';\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n ">\n '+(r?'<svg width="22" height="22" viewBox="0 0 24 24" fill="white"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"/></svg>':'<svg width="22" height="22" viewBox="0 0 24 24" fill="#666"><path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"/></svg>')+'\n </div>\n <div style="flex: 1; min-width: 0;">\n <div style="font-weight: 600; font-size: 16px; color: #000000;">'+(r?"AI Assistant":"Support")+'</div>\n <div style="font-size: 13px; color: #16A34A; display: flex; align-items: center; gap: 5px; margin-top: 1px;">\n <span style="width: 7px; height: 7px; background: #16A34A; border-radius: 50%;"></span>\n Online\n </div>\n </div>\n <button class="vtilt-chat-close" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin-right: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n '}var s=n.querySelector(".vtilt-chat-close");null==s||s.addEventListener("click",()=>this.close());var a=n.querySelector(".vtilt-chat-back");null==a||a.addEventListener("click",()=>this.goToChannelList())}}ve(){var t=this.Nt.primaryColor,e=this.jt.greeting||"Hi! How can we help you today?";return 0!==this.Pt.channels.length||this.Pt.isLoading?'\n <div style="flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch;">\n '+this.Pt.channels.map(t=>this.ye(t)).join("")+'\n </div>\n <div style="\n padding: 16px;\n padding-bottom: max(16px, env(safe-area-inset-bottom, 16px));\n border-top: 1px solid #E5E5E5;\n ">\n <button class="vtilt-chat-new-channel" style="\n width: 100%;\n background: '+t+";\n color: white;\n border: none;\n border-radius: 100px;\n padding: 14px 24px;\n cursor: pointer;\n font-weight: 500;\n font-size: 15px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n box-shadow: 0 2px 8px "+t+'4D;\n ">\n Send us a message\n <svg width="18" height="18" viewBox="0 0 24 24" fill="white">\n <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>\n </svg>\n </button>\n </div>\n ':'\n <div style="\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 48px 24px;\n text-align: center;\n ">\n <div style="\n width: 72px;\n height: 72px;\n margin-bottom: 24px;\n background: '+t+';\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n ">\n <svg width="36" height="36" viewBox="0 0 24 24" fill="white">\n <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n </svg>\n </div>\n <div style="font-size: 18px; font-weight: 600; color: #000000; margin-bottom: 12px; line-height: 1.4; max-width: 280px;">'+this.be(e)+'</div>\n <div style="font-size: 14px; color: #666666; margin-bottom: 28px;">Start a conversation with us</div>\n <button class="vtilt-chat-new-channel" style="\n background: '+t+";\n color: white;\n border: none;\n border-radius: 100px;\n padding: 14px 28px;\n cursor: pointer;\n font-weight: 500;\n font-size: 15px;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n display: flex;\n align-items: center;\n gap: 10px;\n box-shadow: 0 2px 8px "+t+'4D;\n ">\n Send us a message\n <svg width="18" height="18" viewBox="0 0 24 24" fill="white">\n <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>\n </svg>\n </button>\n </div>\n '}ye(t){var e=t.unread_count>0,n=this.xe(t.last_message_at||t.created_at),i=t.last_message_preview||"No messages yet",r=this.Nt.primaryColor,s="user"===t.last_message_sender?"You: ":"";return'\n <div class="vtilt-channel-item" data-channel-id="'+t.id+'" style="\n padding: 14px 16px;\n cursor: pointer;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n display: flex;\n align-items: center;\n gap: 12px;\n background: white;\n border-bottom: 1px solid #EEEEEE;\n ">\n <div style="\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: '+(t.ai_mode?r:"#DEDEDE")+';\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n ">\n '+(t.ai_mode?'<svg width="24" height="24" viewBox="0 0 24 24" fill="white"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"/></svg>':'<svg width="24" height="24" viewBox="0 0 24 24" fill="#666"><path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"/></svg>')+'\n </div>\n <div style="flex: 1; min-width: 0;">\n <div style="display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 4px;">\n <div style="font-weight: '+(e?"600":"500")+'; font-size: 15px; color: #000000; line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">\n '+(t.ai_mode?"AI Assistant":"Support")+'\n </div>\n <div style="font-size: 13px; color: #888888; white-space: nowrap; flex-shrink: 0;">'+n+'</div>\n </div>\n <div style="display: flex; justify-content: space-between; align-items: center; gap: 8px;">\n <div style="\n font-size: 14px;\n color: '+(e?"#333333":"#888888")+';\n font-weight: 400;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n flex: 1;\n min-width: 0;\n line-height: 1.4;\n ">'+s+this.be(i)+("closed"===t.status?" · Closed":"")+"</div>\n "+(e?'<div style="\n min-width: 20px;\n height: 20px;\n padding: 0 6px;\n background: '+r+';\n border-radius: 10px;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 12px;\n font-weight: 600;\n color: #FFFFFF;\n line-height: 1;\n ">'+(t.unread_count>99?"99+":t.unread_count)+"</div>":"")+"\n </div>\n </div>\n </div>\n "}pe(){return'\n <div class="vtilt-chat-messages" style="\n flex: 1;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n padding: 20px 16px 24px 16px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-height: 0;\n background: #FAFAFA;\n "></div>\n \n <div class="vtilt-chat-typing" style="\n display: none;\n padding: 12px 16px;\n background: #FAFAFA;\n align-items: center;\n ">\n <div style="\n display: flex;\n align-items: center;\n gap: 6px;\n ">\n <span style="width: 7px; height: 7px; background: #999; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0s;"></span>\n <span style="width: 7px; height: 7px; background: #999; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0.2s;"></span>\n <span style="width: 7px; height: 7px; background: #999; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0.4s;"></span>\n <span class="vtilt-chat-typing-text" style="\n font-size: 12px;\n color: #666;\n font-weight: 500;\n white-space: nowrap;\n margin-left: 2px;\n ">Agent is typing...</span>\n </div>\n </div>\n <style>\n @keyframes vtilt-typing { 0%, 60%, 100% { opacity: 0.35; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-2px); } }\n </style>\n \n <div class="vtilt-chat-input-container" style="\n padding: 8px 12px;\n padding-bottom: max(8px, env(safe-area-inset-bottom, 8px));\n border-top: 1px solid #E5E5E5;\n flex-shrink: 0;\n background: #ffffff;\n ">\n <div style="\n position: relative;\n border: 1px solid #DDDDDD;\n border-radius: 12px;\n background: #ffffff;\n overflow: hidden;\n ">\n <textarea\n class="vtilt-chat-input"\n placeholder="Message..."\n autocomplete="off"\n autocorrect="on"\n autocapitalize="sentences"\n rows="1"\n style="\n width: 100%;\n box-sizing: border-box;\n border: none;\n border-radius: 0;\n padding: 12px 12px 36px 12px;\n font-size: 16px;\n line-height: 1.4;\n outline: none;\n background: transparent;\n -webkit-appearance: none;\n appearance: none;\n color: #000000;\n transition: none;\n resize: none;\n overflow-y: auto;\n overflow-x: hidden;\n min-height: 60px;\n max-height: 120px;\n font-family: inherit;\n "\n ></textarea>\n <div style="\n position: absolute;\n left: 0;\n bottom: 0;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 0 8px 10px;\n pointer-events: none;\n z-index: 1;\n ">\n <button\n class="vtilt-chat-attach"\n style="\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n pointer-events: auto;\n color: #666666;\n transition: color 0.15s ease;\n "\n title="Attach file"\n >\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>\n </svg>\n </button>\n <button\n class="vtilt-chat-mic"\n style="\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n pointer-events: auto;\n color: #666666;\n transition: color 0.15s ease;\n "\n title="Voice message"\n >\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"></path>\n <path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>\n <line x1="12" y1="19" x2="12" y2="23"></line>\n <line x1="8" y1="23" x2="16" y2="23"></line>\n </svg>\n </button>\n </div>\n <button class="vtilt-chat-send" disabled style="\n position: absolute;\n right: 0;\n bottom: 0;\n background: #E5E5E5;\n color: #999999;\n border: none;\n border-radius: 50%;\n padding: 0;\n width: 32px;\n height: 32px;\n margin: 6px 8px 6px 6px;\n cursor: not-allowed;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n z-index: 2;\n transition: background-color 0.15s ease, color 0.15s ease, transform 0.1s ease, cursor 0.15s ease;\n opacity: 0.6;\n ">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">\n <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>\n </svg>\n </button>\n </div>\n </div>\n '}fe(){var t,e,n,i;null===(e=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-new-channel"))||void 0===e||e.addEventListener("click",()=>this.createChannel()),null===(i=null===(n=this.it)||void 0===n?void 0:n.querySelectorAll(".vtilt-channel-item"))||void 0===i||i.forEach(t=>{t.addEventListener("click",()=>{var e=t.getAttribute("data-channel-id");e&&this.selectChannel(e)})})}ge(){var t,e,n,i,r,s,a,o,l,h,c=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-send");null==c||c.addEventListener("click",()=>{c.disabled||this.ue()});var d=null===(e=this.it)||void 0===e?void 0:e.querySelector(".vtilt-chat-input");null===(i=null===(n=this.it)||void 0===n?void 0:n.querySelector(".vtilt-chat-attach"))||void 0===i||i.addEventListener("click",t=>{t.preventDefault(),alert("File attachments coming soon!")}),null===(s=null===(r=this.it)||void 0===r?void 0:r.querySelector(".vtilt-chat-emoji"))||void 0===s||s.addEventListener("click",t=>{t.preventDefault(),bi().debug(Ii,"emoji clicked (not implemented)")}),null===(o=null===(a=this.it)||void 0===a?void 0:a.querySelector(".vtilt-chat-gif"))||void 0===o||o.addEventListener("click",t=>{t.preventDefault(),bi().debug(Ii,"GIF clicked (not implemented)")}),null===(h=null===(l=this.it)||void 0===l?void 0:l.querySelector(".vtilt-chat-mic"))||void 0===h||h.addEventListener("click",t=>{t.preventDefault(),alert("Voice messages coming soon!")});var u=()=>{if(d){d.style.height="auto";var t=d.scrollHeight;d.style.height=Math.min(Math.max(t,60),120)+"px"}},v=this.Nt.primaryColor,f=()=>{var t,e=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-send");if(e&&d){var n=d.value.trim().length>0;e.disabled=!n,n?(e.style.background=v||"#E5E5E5",e.style.color="white",e.style.cursor="pointer",e.style.opacity="1"):(e.style.background="#E5E5E5",e.style.color="#999999",e.style.cursor="not-allowed",e.style.opacity="0.6")}};null==d||d.addEventListener("input",()=>{u(),this.ce(),f()}),null==d||d.addEventListener("keydown",t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.ue())}),d&&(u(),f())}xe(t){var e=new Date(t),n=(new Date).getTime()-e.getTime(),i=Math.floor(n/6e4),r=Math.floor(n/36e5),s=Math.floor(n/864e5);return i<1?"Just now":i<60?i+"m ago":r<24?r+"h ago":s<7?s+"d ago":e.toLocaleDateString()}me(){var t,e=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-messages");if(e){var n=this.Nt.primaryColor,i=this.Pt.messages.findIndex(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&!this.Xt(t.created_at)),r=this.Pt.messages.map((t,e)=>(e===i&&i>0?'<div style="display:flex;align-items:center;gap:12px;margin:12px 0"><div style="flex:1;height:1px;background:#DDD"></div><span style="font-size:12px;font-weight:600;color:'+n+'">New</span><div style="flex:1;height:1px;background:#DDD"></div></div>':"")+this.ke(t)).join("");e.innerHTML=r,e.scrollTop=e.scrollHeight}}ke(t){var e="user"===t.sender_type,n="ai"===t.sender_type,i=e&&this.Ee(t.created_at),r=this.Nt.primaryColor;if(e)return'\n <div class="vtilt-msg" style="\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n ">\n <div style="\n max-width: 80%;\n padding: 12px 16px;\n background: '+r+";\n color: white;\n border-radius: 20px 20px 4px 20px;\n font-size: 15px;\n line-height: 1.45;\n word-wrap: break-word;\n overflow-wrap: break-word;\n white-space: "+(g(t)?"normal":"pre-wrap")+';\n ">'+this.Te(t)+'</div>\n <div style="font-size: 12px; color: #888888; margin-top: 6px; display: flex; align-items: center; gap: 4px;">\n '+this.Ae(t.created_at)+"\n "+(i?'<svg width="14" height="14" viewBox="0 0 24 24" fill="'+r+'"><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>':"")+"\n </div>\n </div>\n ";var s=n?"AI Assistant":t.sender_name||"Support";return'\n <div class="vtilt-msg" style="\n display: flex;\n gap: 10px;\n align-items: flex-end;\n ">\n <div style="\n width: 32px;\n height: 32px;\n border-radius: 50%;\n background: '+(n?r:"#DEDEDE")+';\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n ">\n '+(n?'<svg width="16" height="16" viewBox="0 0 24 24" fill="white"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"/></svg>':'<svg width="16" height="16" viewBox="0 0 24 24" fill="#666"><path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"/></svg>')+'\n </div>\n <div style="flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: flex-start;">\n <div style="\n max-width: 85%;\n padding: 12px 16px;\n background: #ffffff;\n color: #000000;\n border-radius: 20px 20px 20px 4px;\n font-size: 15px;\n line-height: 1.45;\n word-wrap: break-word;\n overflow-wrap: break-word;\n ">'+this.Te(t)+this.Se(t)+'</div>\n <div style="font-size: 12px; color: #888888; margin-top: 6px; margin-left: 4px;">\n '+s+" · "+this.Ae(t.created_at)+"\n </div>\n </div>\n </div>\n "}Ee(t){return!!this.Pt.agentLastReadAt&&new Date(t)<=new Date(this.Pt.agentLastReadAt)}Qt(t,e,n){var i=this;return o(function*(){var r,s,a,o,l,h={id:"temp-ai-"+Date.now(),channel_id:n,sender_type:"ai",sender_id:null,sender_name:"AI Assistant",sender_avatar_url:null,content:"",content_type:"text",metadata:{},created_at:(new Date).toISOString()};i.Pt.messages.push(h),i.qt();var c=null===(r=t.body)||void 0===r?void 0:r.getReader();if(!c)return bi().error(Ii,"no response body reader available"),void i.Ce(h.id);var d=new TextDecoder,u="",v=null;try{for(;;){var{done:f,value:p}=yield c.read();if(f)break;var g=d.decode(p,{stream:!0});u+=g,v||(v=setTimeout(()=>{var t=i.Pt.messages.findIndex(t=>t.id===h.id);-1!==t&&(i.Pt.messages[t].content=u.replace(/<[^>]*$/,""),i.qt()),v=null},50))}var m=i.Pt.messages.findIndex(t=>t.id===h.id);if(-1!==m){var w=i._e(u);i.Pt.messages[m].content=u,w.length>0&&(i.Pt.messages[m].metadata.et=w),i.qt()}null===(a=(s=i.jt).onMessageSent)||void 0===a||a.call(s,{channelId:n,messageId:e.id}),i.zt(e,n,null===(l=null===(o=i.Pt.channel)||void 0===o?void 0:o.ai_mode)||void 0===l||l)}catch(t){bi().error(Ii,"failed to handle streaming response:",t),i.Ce(h.id)}finally{c.releaseLock(),v&&clearTimeout(v)}})()}Ce(t){this.Pt.messages=this.Pt.messages.filter(e=>e.id!==t),this.qt()}Ft(){return 0}Te(t){var e,n=null!==(e=t.content)&&void 0!==e?e:"";return g(t)?'<div class="vtilt-md'+("user"===t.sender_type?" vtilt-user-md":"")+'">'+this.Oe(n,t.content_type)+"</div>":this.be(n)}Oe(t,e){return void 0===e&&(e="text"),v(t.replace(ji,"").trim(),e,null!=r?r:null)}Se(t){var e,n=null!==(e=t.metadata)&&void 0!==e?e:{},i=n.et;if(i&&0!==i.length||(i=n.widgets),i&&0!==i.length||!t.content||(i=this._e(t.content)),!i||0===i.length)return"";var r=this.le();return r.messageId=t.id,i.map(t=>{if(t.submitted){if("collect_email"===t.type){var e=t.submittedEmail?String(t.submittedEmail).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):"",n=t.submittedName?String(t.submittedName).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):"";return'<div class="vtilt-widget"><p style="margin:0; font-size:13px; color:#16a34a;">'+(n?"&#10003; Thanks, "+n+"! We'll follow up at "+e+".":e?"&#10003; Thanks! We'll follow up at "+e+".":"&#10003; Thanks!")+"</p></div>"}return"escalate_to_human"===t.type?'<div class="vtilt-widget"><p style="margin:0; font-size:13px; color:#16a34a;">&#10003; A team member has been notified. They\'ll join shortly.</p></div>':'<div class="vtilt-widget"><p style="margin:0; font-size:13px; color:#16a34a;">&#10003; Done</p></div>'}var i=this.St.get(t.type);return i?i.render(t.params,r):""}).join("")}le(){var t,e,n=this._instance.getConfig();return{channelId:null!==(e=null===(t=this.Pt.channel)||void 0===t?void 0:t.id)&&void 0!==e?e:"",distinctId:this.Ut,primaryColor:this.Nt.primaryColor||"#7B68EE",apiBase:n.api_host||"",token:n.token||"",messageId:"",buildEndpointUrl:t=>w(this._instance.getConfig(),t)}}_e(t){for(var e,n,i=[],r=new RegExp(ji.source,"g");null!==(n=r.exec(t));)try{var s=JSON.parse(n[1]);s.type&&i.push({type:s.type,params:null!==(e=s.params)&&void 0!==e?e:{}})}catch(t){}return i}registerWidget(t){this.St.register(t)}be(t){if(!r)return t;var e=r.createElement("div");return e.textContent=t,e.innerHTML}Gt(t){var e,n,i,r,s=(i=t.content||"",void 0===r&&(r=100),i.replace(/\n?<!--vtilt:widget:[\s\S]*?-->/g,"").replace(/<[^>]*>/g,"").trim().substring(0,r));if(s)return s;var a=null!==(e=t.metadata)&&void 0!==e?e:{},o=null!==(n=a.et)&&void 0!==n?n:a.widgets;return o&&o.length>0?o.map(t=>"collect_email"===t.type?t.submitted&&t.submittedEmail?"Contact collected: "+(t.submittedName?t.submittedName+" ("+t.submittedEmail+")":t.submittedEmail):"Asked for contact info":"escalate_to_human"===t.type?t.submitted?"Escalated to human agent":"Offered human escalation":t.type.replace(/_/g," ")).join(", "):""}Ae(t){if(null==t||""===t)return"";var e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}function Bi(t,e){return new Di(t,e)}s.__VTiltExtensions__=s.__VTiltExtensions__||{},s.__VTiltExtensions__.initChat=Bi,t.LazyLoadedChat=Di,t.default=Bi,t.initChat=Bi,Object.defineProperty(t,"__esModule",{value:!0})}({});
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,e&&r&&r.createElement,null==n||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),l=o.value}catch(t){return void n(t)}o.done?e(l):Promise.resolve(l).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,l,"next",t)}function l(t){a(s,i,r,o,l,"throw",t)}o(void 0)})}}function l(){return l=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},l.apply(null,arguments)}var h=/<(?:p|ul|ol|li|h[1-6]|br|div|pre|blockquote)\b/i;function c(t){var e=t;return e=(e=(e=(e=(e=(e=e.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>")).replace(/__(.+?)__/g,"<b>$1</b>")).replace(/\*(.+?)\*/g,"<i>$1</i>")).replace(/(?<!\w)_(.+?)_(?!\w)/g,"<i>$1</i>")).replace(/`([^`]+)`/g,"<code>$1</code>")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>')}var d=new Set(["P","B","STRONG","I","EM","U","UL","OL","LI","BR","A","H1","H2","H3","H4","H5","H6","CODE","PRE","BLOCKQUOTE","DIV","SPAN"]);function u(t,e){for(var n=Array.from(t.children),i=0;i<n.length;){var r=n[i];if("LI"!==r.tagName)u(r,e),i++;else{for(var s=[],a=i;a<n.length&&"LI"===n[a].tagName;)s.push(n[a]),a++;var o=e.createElement("ul");for(var l of(t.insertBefore(o,s[0]),s))o.appendChild(l);i=a}}}function v(t,e,n){if(!t)return"";var i=t.trim();if(!i)return"";if(!n)return i;var r=function(t,e){return"html"!==t&&!h.test(e)}(e,i)?function(t){if(!t||h.test(t))return t;for(var e=t.split("\n"),n=[],i=0;i<e.length;){var r=e[i],s=r.match(/^(#{1,6})\s+(.+)$/);if(s){var a=s[1].length;n.push("<h"+a+">"+c(s[2])+"</h"+a+">"),i++}else if(/^[-*]\s+/.test(r)){for(var o=[];i<e.length&&/^[-*]\s+/.test(e[i]);)o.push("<li>"+c(e[i].replace(/^[-*]\s+/,""))+"</li>"),i++;n.push("<ul>"+o.join("")+"</ul>")}else if(/^\d+\.\s+/.test(r)){for(var l=[];i<e.length&&/^\d+\.\s+/.test(e[i]);)l.push("<li>"+c(e[i].replace(/^\d+\.\s+/,""))+"</li>"),i++;n.push("<ol>"+l.join("")+"</ol>")}else if(""!==r.trim()){for(var d=[];i<e.length&&""!==e[i].trim()&&!/^#{1,6}\s/.test(e[i])&&!/^[-*]\s+/.test(e[i])&&!/^\d+\.\s+/.test(e[i]);)d.push(c(e[i])),i++;n.push("<p>"+d.join("<br>")+"</p>")}else i++}return n.join("")}(i):i,s=n.createElement("div");return s.innerHTML=r,function(t,e){var n=t=>{for(var i of Array.from(t.children))if(d.has(i.tagName)){for(var r of Array.from(i.attributes))"A"===i.tagName&&"href"===r.name||i.removeAttribute(r.name);"A"===i.tagName&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer")),n(i)}else i.replaceWith(e.createTextNode(i.textContent||""))};n(t)}(s,n),u(s,n),s.innerHTML}var p="rich_format",f="markdown";function g(t){return"user"===t.sender_type?function(t){var e;return"html"===t.content_type||(null===(e=t.metadata)||void 0===e?void 0:e[p])===f}(t):"ai"===t.sender_type||"agent"===t.sender_type}var m="x-api-key";function w(t,e,n){void 0===n&&(n={});var{api_host:i,token:r}=t,s=""+(i?i.replace(/\/+$/gm,""):"")+e;if(n.includeTokenQuery&&r){var a=s.includes("?")?"&":"?";s=""+s+a+"token="+r}return s}function y(t){return t.token?{[m]:t.token}:{}}var b="$channel_message",x=Object.defineProperty,k=Object.defineProperties,E=Object.getOwnPropertyDescriptors,A=Object.getOwnPropertySymbols,T=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable,_=(t,e,n)=>e in t?x(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,C=(t,e)=>{for(var n in e||(e={}))T.call(e,n)&&_(t,n,e[n]);if(A)for(var n of A(e))S.call(e,n)&&_(t,n,e[n]);return t},M=(t,e)=>k(t,E(e)),O=function(t,e){this[0]=t,this[1]=e},I=class{},B="undefined"!=typeof global?global:"undefined"!=typeof window?window:self;function j(t,e){return(""+t).padStart(e?3:2,"0")}function P(t){return I.Config.logTimestamps?function(e){var n=new Date;t(j(n.getHours())+":"+j(n.getMinutes())+":"+j(n.getSeconds())+"."+j(n.getMilliseconds(),1)+" "+e)}:function(e){t(e)}}var N=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(P));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)}};N.defaultLogLevel=1,N.LOG_NONE=0,N.LOG_ERROR=1,N.LOG_MAJOR=2,N.LOG_MINOR=3,N.LOG_MICRO=4,N.logAction=(t,e,n,i)=>{N.logActionNoStrip(t,e,n,i)};var D=N,R={};function U(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="+vt(t.cause)),!t.href||t.message&&t.message.indexOf("help.ably.io")>-1||(e+="; see "+t.href+" "),e+="]"}((t,e)=>{for(var n in e)x(t,n,{get:e[n],enumerable:!0})})(R,{Format:()=>ot,allSame:()=>at,allToLowerCase:()=>kt,allToUpperCase:()=>Et,arrChooseN:()=>wt,arrDeleteValue:()=>et,arrEquals:()=>It,arrIntersect:()=>Z,arrIntersectOb:()=>tt,arrPopRandomElement:()=>lt,arrWithoutValue:()=>nt,cheapRandStr:()=>gt,containsValue:()=>Y,copy:()=>q,createMissingPluginError:()=>Bt,dataSizeBytes:()=>ft,decodeBody:()=>bt,encodeBody:()=>xt,ensureArray:()=>F,forInOwnNonNullProperties:()=>st,getBackoffCoefficient:()=>At,getGlobalObject:()=>_t,getJitterCoefficient:()=>Tt,getRetryTime:()=>St,inherits:()=>Q,inspectBody:()=>pt,inspectError:()=>vt,intersect:()=>X,isEmpty:()=>W,isErrorInfoOrPartialErrorInfo:()=>ut,isNil:()=>J,isObject:()=>V,keysArray:()=>it,listenerToAsyncIterator:()=>Dt,matchDerivedChannel:()=>Mt,mixin:()=>L,parseQueryString:()=>dt,prototypicalClone:()=>G,randomString:()=>mt,shallowClone:()=>K,shallowEquals:()=>Ct,stringifyValues:()=>ct,throwMissingPluginError:()=>jt,toBase64:()=>Ot,toQueryString:()=>ht,valuesArray:()=>rt,whenPromiseSettles:()=>yt,withTimeoutAsync:()=>Pt});var z=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 U(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: "+I.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}},H=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 U(this)}static fromValues(e){var{message:n,code:i,statusCode:r}=e;if("string"!=typeof n||!J(i)&&"number"!=typeof i||!J(r)&&"number"!=typeof r)throw new Error("PartialErrorInfo.fromValues(): invalid values: "+I.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 L(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 q(t){return L({},t)}function F(t){return J(t)?[]:Array.isArray(t)?t:[t]}function V(t){return"[object Object]"==Object.prototype.toString.call(t)}function W(t){for(var e in t)return!1;return!0}function J(t){return null==t}function K(t){var e=new Object;for(var n in t)e[n]=t[n];return e}function G(t,e){class n{}n.prototype=t;var i=new n;return e&&L(i,e),i}var Q=function(t,e){I.Config.inherits?I.Config.inherits(t,e):(t.super_=e,t.prototype=G(e.prototype,{constructor:t}))};function Y(t,e){for(var n in t)if(t[n]==e)return!0;return!1}function X(t,e){return Array.isArray(e)?Z(t,e):tt(t,e)}function Z(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 tt(t,e){for(var n=[],i=0;i<t.length;i++){var r=t[i];r in e&&n.push(r)}return n}function et(t,e){var n=t.indexOf(e),i=-1!=n;return i&&t.splice(n,1),i}function nt(t,e){var n=t.slice();return et(n,e),n}function it(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(i);return n}function rt(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(t[i]);return n}function st(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&t[n]&&e(n)}function at(t,e){if(0===t.length)return!0;var n=t[0][e];return t.every(function(t){return t[e]===n})}var ot=(t=>(t.msgpack="msgpack",t.json="json",t))(ot||{});function lt(t){return t.splice((e=t,Math.floor(Math.random()*e.length)),1)[0];var e}function ht(t){var e=[];if(t)for(var n in t)e.push(encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e.length?"?"+e.join("&"):""}function ct(t){return Object.fromEntries(Object.entries(t).map(t=>{var[e,n]=t;return[e,String(n)]}))}function dt(t){for(var e,n=/([^?&=]+)=?([^&]*)/g,i={};e=n.exec(t);)i[decodeURIComponent(e[1])]=decodeURIComponent(e[2]);return i}function ut(t){return"object"==typeof t&&null!==t&&(t instanceof z||t instanceof H)}function vt(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():I.Config.inspect(t)}function pt(t){return I.BufferUtils.isBuffer(t)?t.toString():"string"==typeof t?t:I.Config.inspect(t)}function ft(t){if(I.BufferUtils.isBuffer(t))return I.BufferUtils.byteLength(t);if("string"==typeof t)return I.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 gt(){return String(Math.random()).substr(2)}var mt=function(){var t=o(function*(t){var e=yield I.Config.getRandomArrayBuffer(t);return I.BufferUtils.base64Encode(e)});return function(e){return t.apply(this,arguments)}}();function wt(t,e){for(var n=Math.min(e,t.length),i=t.slice(),r=[],s=0;s<n;s++)r.push(lt(i));return r}function yt(t,e){t.then(t=>{null==e||e(null,t)}).catch(t=>{null==e||e(t)})}function bt(t,e,n){return"msgpack"==n?(e||jt("MsgPack"),e.decode(t)):JSON.parse(String(t))}function xt(t,e,n){return"msgpack"==n?(e||jt("MsgPack"),e.encode(t,!0)):JSON.stringify(t)}function kt(t){return t.map(function(t){return t&&t.toLowerCase()})}function Et(t){return t.map(function(t){return t&&t.toUpperCase()})}function At(t){return Math.min((t+2)/3,2)}function Tt(){return 1-.2*Math.random()}function St(t,e){return t*At(e)*Tt()}function _t(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:self}function Ct(t,e){return Object.keys(t).every(n=>t[n]===e[n])&&Object.keys(e).every(n=>e[n]===t[n])}function Mt(t){var e=t.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!e||!e.length||e.length<5)throw new z("regex match failed",400,40010);if(e[2])throw new z("cannot use a derived option with a "+e[2]+" channel",400,40010);return{qualifierParam:e[3]||"",channelName:e[4]}}function Ot(t){var e=I.BufferUtils,n=e.utf8Encode(t);return e.base64Encode(n)}function It(t,e){return t.length===e.length&&t.every(function(t,n){return t===e[n]})}function Bt(t){return new z(t+" plugin not provided",40019,400)}function jt(t){throw Bt(t)}function Pt(t,e,n){return Nt.apply(this,arguments)}function Nt(){return(Nt=o(function*(t,e,n){void 0===e&&(e=5e3),void 0===n&&(n="Timeout expired");var i=new z(n,5e4,500);return Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(i),e))])})).apply(this,arguments)}function Dt(t){return n=(t,i,r,s)=>{try{var a=e[t](i),o=(i=a.value)instanceof O,l=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:l})).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 z("Concurrent next() calls are not supported",4e4,400);var r=yield new O(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 Rt="2.17.0",Ut={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:Rt,protocolVersion:5,agent:"ably-js/"+Rt,getPort:function(t,e){return e||t.tls?t.tlsPort:t.port},getHttpScheme:function(t){return t.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:Ht,getEndpointFallbackHosts:Lt,getFallbackHosts:Ft,getHosts:function(t){return[t.primaryDomain].concat(Ft(t))},checkHost:Vt,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 D.logAction(i,D.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 D.logAction(i,D.LOG_ERROR,n+"()",o),new Error(o)}a={token:t}}else{if(!e){var l=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 D.logAction(i,D.LOG_ERROR,n+"()",l),new Error(l)}a={key:t}}else a=t;r&&(a=M(C({},a),{plugins:C(C({},r),a.plugins)}));return a},normaliseOptions:function(t,e,n){var i=null!=n?n:D.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.");Jt(t),"function"==typeof t.recover&&!0===t.closeOnUnload&&(D.logAction(i,D.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||Ut.ENDPOINT;t.fallbackHosts||t.restHost||t.realtimeHost||t.port||t.tlsPort||(t.fallbackHosts=Lt(t.environment||r));var s=t.environment&&t.environment+".realtime.ably.net",a=t.restHost||t.realtimeHost||s||Ht(r);(t.fallbackHosts||[]).concat(a).forEach(Vt),t.port=t.port||Ut.PORT,t.tlsPort=t.tlsPort||Ut.TLS_PORT,"tls"in t||(t.tls=!0);var o=function(t){var e={};for(var n in Ut.TIMEOUTS)e[n]=t[n]||Ut.TIMEOUTS[n];return e}(t);t.useBinaryProtocol=!!e&&("useBinaryProtocol"in t?I.Config.supportsBinary&&t.useBinaryProtocol:I.Config.preferBinary);var l={};t.clientId&&(l["X-Ably-ClientId"]=I.BufferUtils.base64Encode(I.BufferUtils.utf8Encode(t.clientId)));"idempotentRestPublishing"in t||(t.idempotentRestPublishing=!0);var h=null,c=t.connectivityCheckUrl;if(t.connectivityCheckUrl){var[d,u]=t.connectivityCheckUrl.split("?");h=u?dt(u):{},-1===d.indexOf("://")&&(d="https://"+d),c=d}var v=t.wsConnectivityCheckUrl;v&&-1===v.indexOf("://")&&(v="wss://"+v);return M(C({},t),{primaryDomain:a,maxMessageSize:t.maxMessageSize||Ut.maxMessageSize,timeouts:o,connectivityCheckParams:h,connectivityCheckUrl:c,wsConnectivityCheckUrl:v,headers:l})},defaultGetHeaders:function(t,e){var{format:n,protocolVersion:i=Gt.protocolVersion}=void 0===e?{}:e;return{accept:Kt[null!=n?n:t.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":i.toString(),"Ably-Agent":Wt(t)}},defaultPostHeaders:function(t,e){var{format:n,protocolVersion:i=Gt.protocolVersion}=void 0===e?{}:e,r=Kt[null!=n?n:t.useBinaryProtocol?"msgpack":"json"];return{accept:r,"content-type":r,"X-Ably-Version":i.toString(),"Ably-Agent":Wt(t)}}};function zt(t){return t.includes(".")||t.includes("::")||"localhost"===t}function Ht(t){return zt(t)?t:t.startsWith("nonprod:")?t.replace("nonprod:","")+".realtime.ably-nonprod.net":t+".realtime.ably.net"}function Lt(t){return zt(t)?[]:t.startsWith("nonprod:")?qt(t.replace("nonprod:",""),"ably-realtime-nonprod.com"):qt(t,"ably-realtime.com")}function qt(t,e){return["a","b","c","d","e"].map(n=>t+"."+n+".fallback."+e)}function Ft(t){var e=t.fallbackHosts,n=void 0!==t.httpMaxRetryCount?t.httpMaxRetryCount:Ut.httpMaxRetryCount;return e?wt(e,n):[]}function Vt(t){if("string"!=typeof t)throw new z("host must be a string; was a "+typeof t,4e4,400);if(!t.length)throw new z("host must not be zero-length",4e4,400)}function Wt(t){var e=Ut.agent;if(t.agents)for(var n in t.agents)e+=" "+n+"/"+t.agents[n];return e}function Jt(t){if(t.endpoint&&(t.environment||t.restHost||t.realtimeHost))throw new z("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 z("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function $t(t,e,n){var i=n||{};if(i.cipher){t||jt("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 Kt={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},Gt={protocolVersion:Ut.protocolVersion};var Qt=Ut;var Yt=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){D.logAction(this.logger,D.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)})}},Xt=(t=>(t.Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t))(Xt||{}),Zt=Xt,te=(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))(te||{});var ee=te,ne=Math.pow(2,17);function ie(t){return ut(t)?(t.code||(403===t.statusCode?t.code=40300:(t.code=40170,t.statusCode=401)),t):new z(vt(t),t.code||40170,t.statusCode||401)}function re(t){if(!t)return"";"string"==typeof t&&(t=JSON.parse(t));var e=Object.create(null),n=it(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 se(t,e){if(t.authCallback);else if(t.authUrl);else if(t.key);else if(!t.tokenDetails){var n="authOptions must include valid authentication parameters";throw D.logAction(e,D.LOG_ERROR,"Auth()",n),new Error(n)}}var ae=0;var oe=class{constructor(t,e){if(this.authOptions={},this.client=t,this.tokenParams=e.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,function(t){return t.useTokenAuth||!function(t){return"useTokenAuth"in t&&!t.useTokenAuth}(t)&&(t.authCallback||t.authUrl||t.token||t.tokenDetails)}(e))(function(t){return!t.key&&!t.authCallback&&!t.authUrl})(e)&&D.logAction(this.logger,D.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),se(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 D.logAction(this.logger,D.LOG_ERROR,"Auth()",n),new z(n,40160,401)}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 z("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===ee.Forbidden&&n.client.connection.connectionManager.actOnErrorFromAuthorize(t),t}})()}o(t,e){var n=this;return o(function*(){n.tokenDetails=null,n.t(t,e),se(n.authOptions,n.logger);try{return n.l(!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||q(n.tokenParams),a=n.client;if(r.authCallback)i=r.authCallback;else if(r.authUrl)i=(t,e)=>{var i,s=L({accept:"application/json, text/plain"},r.authHeaders),a=r.authMethod&&"post"===r.authMethod.toLowerCase(),o=r.authUrl.indexOf("?");o>-1&&(i=dt(r.authUrl.slice(o)),r.authUrl=r.authUrl.slice(0,o),a||(r.authParams=L(i,r.authParams)));var l=L({},r.authParams||{},t),h=t=>{var n,i,r=null!=(n=t.body)?n:null,s=null;if(t.error);else{var a=null!=(i=t.headers["content-type"])?i:null;s=Array.isArray(a)?a.join(", "):a}if(t.error)e(t.error,null);else if(t.unpacked)e(null,r);else if(I.BufferUtils.isBuffer(r)&&(r=r.toString()),s){var o=s.indexOf("application/json")>-1,l=s.indexOf("text/plain")>-1||s.indexOf("application/jwt")>-1;if(o||l){if(o){if(r.length>ne)return void e(new z("authUrl response exceeded max permitted length",40170,401),null);try{r=JSON.parse(r)}catch(t){return void e(new z("Unexpected error processing authURL response; err = "+t.message,40170,401),null)}}e(null,r,s)}else e(new z("authUrl responded with unacceptable content-type "+s+", should be either text/plain, application/jwt or application/json",40170,401),null)}else e(new z("authUrl response is missing a content-type header",40170,401),null)};if(a){var c=s||{};c["content-type"]="application/x-www-form-urlencoded";var d=ht(l).slice(1);yt(n.client.http.doUri(Zt.Post,r.authUrl,c,d,i),(t,e)=>h(t||e))}else yt(n.client.http.doUri(Zt.Get,r.authUrl,s||{},null,l),(t,e)=>h(t||e))};else{if(!r.key){throw D.logAction(n.logger,D.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 z("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403)}i=(t,e)=>{yt(n.createTokenRequest(t,r),(t,n)=>e(t,null!=n?n:null))}}"capability"in s&&(s.capability=re(s.capability));return new Promise((t,e)=>{var o=!1,l=n.client.options.timeouts.realtimeRequestTimeout,h=setTimeout(()=>{o=!0;var t="Token request callback timed out after "+l/1e3+" seconds";D.logAction(n.logger,D.LOG_ERROR,"Auth.requestToken()",t),e(new z(t,40170,401))},l);i(s,(i,s,l)=>{if(!o){if(clearTimeout(h),i)return D.logAction(n.logger,D.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+vt(i)),void e(ie(i));if("string"!=typeof s){if("object"!=typeof s||null===s){var c="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof s;return D.logAction(n.logger,D.LOG_ERROR,"Auth.requestToken()",c),void e(new z(c,40170,401))}var d=JSON.stringify(s).length;if(d>ne&&!r.suppressMaxLengthCheck)e(new z("Token request/details object exceeded max permitted stringified size (was "+d+" bytes)",40170,401));else if("issued"in s)t(s);else{if(!("keyName"in s)){var u="Expected token request callback to call back with a token string, token request object, or token details object";return D.logAction(n.logger,D.LOG_ERROR,"Auth.requestToken()",u),void e(new z(u,40170,401))}var v,p,f,g;p=(i,r,s)=>{if(i)return D.logAction(n.logger,D.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+vt(i)),void e(ie(i));s||(r=JSON.parse(r)),t(r)},f="/keys/"+(v=s).keyName+"/requestToken",g=Qt.defaultPostHeaders(n.client.options,{format:"json"}),r.requestHeaders&&L(g,r.requestHeaders),yt(n.client.http.do(Zt.Post,function(t){return a.baseUri(t)+f},g,JSON.stringify(v),null),(t,e)=>t?p(t):p(e.error,e.body,e.unpacked))}}else 0===s.length?e(new z("Token string is empty",40170,401)):s.length>ne?e(new z("Token string exceeded max permitted length (was "+s.length+" bytes)",40170,401)):"undefined"===s||"null"===s?e(new z("Token string was literal null/undefined",40170,401)):"{"!==s[0]||l&&l.indexOf("application/jwt")>-1?t({token:s}):e(new z("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||q(n.tokenParams);var i=e.key;if(!i)throw new z("No key specified",40101,403);var r=i.split(":"),s=r[0],a=r[1];if(!a)throw new z("Invalid key specified",40101,403);if(""===t.clientId)throw new z("clientId can’t be an empty string",40012,400);"capability"in t&&(t.capability=re(t.capability));var o=L({keyName:s},t),l=t.clientId||"",h=t.ttl||"",c=t.capability||"";o.timestamp||(o.timestamp=yield n.h(e&&e.queryTime));var d=o.nonce||(o.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),u=o.timestamp,v=o.keyName+"\n"+h+"\n"+c+"\n"+l+"\n"+u+"\n"+d+"\n";return o.mac=o.mac||((t,e)=>{var n=I.BufferUtils,i=n.utf8Encode(t),r=n.utf8Encode(e),s=n.hmacSha256(i,r);return n.base64Encode(s)})(v,a),o})()}getAuthParams(){var t=this;return o(function*(){if("basic"==t.method)return{key:t.key};var e=yield t.l(!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.l(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Ot(e.token)}})()}i(t){this.method="basic",this.key=t.key,this.basicKey=Ot(t.key),this.authOptions=t||{},"clientId"in t&&this.u(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.u(e.clientId),this.authOptions=e)}l(t){var e=this;return o(function*(){var n=e.tokenDetails;if(n){if(e.p(n.clientId))throw new z("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 n;e.tokenDetails=null}var i=(e.waitingForTokenRequest||(e.waitingForTokenRequest=Yt.create(e.logger))).createPromise();if(null!==e.currentTokenRequestId&&!t)return i;var r,s=e.currentTokenRequestId=ae++,a=null;try{r=yield e.requestToken(e.tokenParams,e.authOptions)}catch(t){a=t}if(e.currentTokenRequestId>s)return 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)})()}u(t){if("string"!=typeof t&&null!==t)throw new z("clientId must be either a string or null",40012,400);if("*"===t)throw new z('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 z(e,40102,401);return D.logAction(this.logger,D.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)}h(t){var e=this;return o(function*(){return e.client.getTimestamp(t||!!e.authOptions.queryTime)})()}};function le(t){var e=[];if(t)for(var n in t)e.push(n+"="+t[n]);return e.join("&")}function he(t,e){return t+(e?"?":"")+le(e)}var ce=class{constructor(t){this.client=t,this.platformHttp=new I.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:D.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}k(t){var e=t.connection,n=e&&e.connectionManager.host;return n?[n].concat(Qt.getFallbackHosts(t.options)):Qt.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 z("http.do called without client",5e4,500)};var l="function"==typeof e?e:function(t){return a.baseUri(t)+e},h=a.A;if(h){if(h.validUntil>Date.now()){var c=yield s.doUri(t,l(h.host),n,i,r);return c.error&&s.platformHttp.shouldFallback(c.error)?(a.A=null,s.do(t,e,n,i,r)):c}a.A=null}var d=s.k(a);if(1===d.length)return s.doUri(t,l(d[0]),n,i,r);var u=null,v=function(){var e=o(function*(e,o){var h=e.shift();u=null!=u?u:new Date;var c=yield s.doUri(t,l(h),n,i,r);return c.error&&s.platformHttp.shouldFallback(c.error)&&e.length?Date.now()-u.getTime()>a.options.timeouts.httpMaxRetryDuration?{error:new z("Timeout for trying fallback hosts retries. Total elapsed time exceeded the "+a.options.timeouts.httpMaxRetryDuration+"ms limit",50003,500)}:v(e,!0):(o&&(a.A={host:h,validUntil:Date.now()+a.options.timeouts.fallbackRetryTimeout}),c)});return function(t,n){return e.apply(this,arguments)}}();return v(d)}catch(t){return{error:new z("Unexpected error in Http.do: "+vt(t),500,5e4)}}})()}doUri(t,e,n,i,r){var s=this;return o(function*(){try{!function(t,e,n,i,r){r.shouldLog(D.LOG_MICRO)&&D.logActionNoStrip(r,D.LOG_MICRO,"Http."+t+"()","Sending; "+he(e,i)+"; Body"+(I.BufferUtils.isBuffer(n)?" (Base64): "+I.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(D.LOG_MICRO)&&function(t,e,n,i,r){t.error?D.logActionNoStrip(r,D.LOG_MICRO,"Http."+e+"()","Received Error; "+he(n,i)+"; Error: "+vt(t.error)):D.logActionNoStrip(r,D.LOG_MICRO,"Http."+e+"()","Received; "+he(n,i)+"; Headers: "+le(t.headers)+"; StatusCode: "+t.statusCode+"; Body"+(I.BufferUtils.isBuffer(t.body)?" (Base64): "+I.BufferUtils.base64Encode(t.body):": "+t.body))}(a,t,e,r,s.logger),a}catch(t){return{error:new z("Unexpected error in Http.doUri: "+vt(t),500,5e4)}}})()}};function de(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(V(i))for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&Array.isArray(i[s])&&de([i],e,s)}var ue=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: "+I.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: "+I.Config.inspect(e));if(J(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: "+I.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||J(e[0])&&J(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:"+I.Config.inspect(e));[a,s]=[i,r]}else"function"==typeof i?s=i:a=i;if(s&&J(a))de([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:"+I.Config.inspect(e));s?de([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){D.logAction(t,D.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(J(s)){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));this.anyOnce.push(a)}else if(Array.isArray(s)){var o=this,l=function(){var t=Array.prototype.slice.call(arguments);if(s.forEach(function(t){o.off(t,l)}),"function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));a.apply(this,t)};s.forEach(function(t){o.on(t,l)})}else{if("string"!=typeof s)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));var h=this.eventsOnce[s]||(this.eventsOnce[s]=[]);if(a){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+I.Config.inspect(e));h.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)})()}},ve={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},pe=[];Object.keys(ve).forEach(function(t){pe[ve[t]]=t});var fe={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},ge=Object.keys(fe);fe.MODE_ALL=fe.PRESENCE|fe.PUBLISH|fe.SUBSCRIBE|fe.PRESENCE_SUBSCRIBE|fe.ANNOTATION_PUBLISH|fe.ANNOTATION_SUBSCRIBE|fe.OBJECT_SUBSCRIBE|fe.OBJECT_PUBLISH;var me=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function we(){return(we=o(function*(t,e){var{data:n,encoding:i}=yield ye(t.data,t.encoding,e);return t.data=n,t.encoding=i,t})).apply(this,arguments)}function ye(t,e,n){return be.apply(this,arguments)}function be(){return(be=o(function*(t,e,n){var i=n.channelCipher,r=t,s=e?e+"/":"";return I.BufferUtils.isBuffer(r)||(r=I.BufferUtils.utf8Encode(String(r)),s+="utf-8/"),{data:yield i.encrypt(r),encoding:s=s+"cipher+"+i.algorithm}})).apply(this,arguments)}function xe(){return xe=o(function*(t,e){var{data:n,encoding:i}=ke(t.data,t.encoding);return t.data=n,t.encoding=i,null!=e&&e.cipher?function(t,e){return we.apply(this,arguments)}(t,e):t}),xe.apply(this,arguments)}function ke(t,e){if("string"==typeof t||I.BufferUtils.isBuffer(t)||null==t)return{data:t,encoding:e};if(V(t)||Array.isArray(t))return{data:JSON.stringify(t),encoding:e?e+"/json":"json"};throw new z("Data type is unsupported",40013,400)}function Ee(){return(Ee=o(function*(t,e){var{data:n,encoding:i,error:r}=yield Ae(t.data,t.encoding,e);if(t.data=n,t.encoding=i,r)throw r})).apply(this,arguments)}function Ae(t,e,n){return Te.apply(this,arguments)}function Te(){return(Te=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 l,h=e.split("/"),c=h.length,d="";try{for(;(l=c)>0;){var u=h[--c].match(/([-\w]+)(\+([\w-]+))?/);if(!u)break;switch(d=u[1]){case"base64":a=I.BufferUtils.base64Decode(String(a)),l==h.length&&(s=a);continue;case"utf-8":a=I.BufferUtils.utf8Decode(a);continue;case"json":a=JSON.parse(a);continue;case"cipher":if(null!=r.channelOptions&&r.channelOptions.cipher&&r.channelOptions.channelCipher){var v=u[3],p=r.channelOptions.channelCipher;if(v!=p.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");a=yield p.decrypt(a);continue}throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!r.plugins||!r.plugins.vcdiff)throw new z("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new z("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var f=r.baseEncodedPreviousPayload;"string"==typeof f&&(f=I.BufferUtils.utf8Encode(f));var g=I.BufferUtils.toBuffer(f);a=I.BufferUtils.toBuffer(a),s=a=I.BufferUtils.arrayBufferViewToBuffer(r.plugins.vcdiff.decode(a,g))}catch(t){throw new z("Vcdiff delta decode failed with "+t,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(t){var m=t;i=new z("Error processing the "+d+" encoding, decoder returned ‘"+m.message+"’",m.code||40013,400)}finally{o=l<=0?null:h.slice(0,l).join("/")}}return i?{error:i,data:a,encoding:o}:(r.baseEncodedPreviousPayload=s,{data:a,encoding:o})})).apply(this,arguments)}function Se(){var t=arguments.length>0?"json":"msgpack",{data:e,encoding:n}=_e(this.data,this.encoding,t);return Object.assign({},this,{encoding:n,data:e})}function _e(t,e,n){return t&&I.BufferUtils.isBuffer(t)?"msgpack"===n?{data:I.BufferUtils.toBuffer(t),encoding:e}:{data:I.BufferUtils.base64Encode(t),encoding:e?e+"/base64":"base64"}:{data:t,encoding:e}}var Ce={encryptData:ye,encodeData:ke,encodeDataForWire:_e,decodeData:Ae};function Me(t){var e,{id:n,connectionId:i,timestamp:r}=t;switch(t.action){case ve.MESSAGE:e=t.messages;break;case ve.PRESENCE:case ve.SYNC:e=t.presence;break;case ve.ANNOTATION:e=t.annotations;break;case ve.OBJECT:case ve.OBJECT_SYNC:e=t.state;break;default:throw new z("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 Oe(t,e){var n="["+e;for(var i in t)"data"===i?"string"==typeof t.data?n+="; data="+t.data:I.BufferUtils.isBuffer(t.data)?n+="; data (buffer)="+I.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 Ie=class{},Be=class{constructor(t){var e,n,i,r,s,a,o,l,h,c;this.Platform=I,this.ErrorInfo=z,this.Logger=D,this.Defaults=Qt,this.Utils=R,this.EventEmitter=ue,this.MessageEncoding=Ce,this.T=null!=(e=t.plugins)?e:null,this.logger=new D,this.logger.setLog(t.logLevel,t.logHandler),this.S=null!=(i=null==(n=t.plugins)?void 0:n.MsgPack)?i:null;var d=this.options=Qt.normaliseOptions(t,this.S,this.logger);if(d.key){var u=d.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!u){var v="invalid key parameter";throw D.logAction(this.logger,D.LOG_ERROR,"BaseClient()",v),new z(v,40400,404)}d.keyName=u[1],d.keySecret=u[2]}if("clientId"in d){if("string"!=typeof d.clientId&&null!==d.clientId)throw new z("clientId must be either a string or null",40012,400);if("*"===d.clientId)throw new z('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)}this.A=null,this.serverTimeOffset=null,this.http=new ce(this),this.auth=new oe(this,d),this.C=(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!=(l=null==(o=t.plugins)?void 0:o.MessageInteractions)?l:null,this.O=null!=(c=null==(h=t.plugins)?void 0:h.Annotations)?c:null}get rest(){return this.C||jt("Rest"),this.C}get I(){return this.__FilteredSubscriptions||jt("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||jt("Push"),this.B||(this.B=this.push.LocalDevice.load(this)),this.B}baseUri(t){return Qt.getHttpScheme(this.options)+t+":"+Qt.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}};Be.Platform=I;var je=Be,Pe=["message.create","message.update","message.delete","meta","message.summary","message.append"];function Ne(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+=ft(t.data)),e}function De(){return(De=o(function*(t,e){return Promise.all(t.map(t=>t.encode(e)))})).apply(this,arguments)}var Re=class t extends Ie{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 function(t,e){return xe.apply(this,arguments)}(Object.assign(new Ue,e,{action:Pe.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 Oe(this,"Message")}},Ue=class t extends Ie{toJSON(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return Se.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 Re,M(C({},n),{action:(i=n.action,Pe[i||0]||"unknown")}));try{yield function(t,e){return Ee.apply(this,arguments)}(s,t)}catch(t){D.logAction(e,D.LOG_ERROR,"WireMessage.decode()",vt(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 Oe(this,"WireMessage")}},ze=Re,He=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)}},Le=function(){};function qe(t){var e=t||{},{agent:n}=e;return((t,e)=>{var n={};for(var i in t)T.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&A)for(var i of A(t))e.indexOf(i)<0&&S.call(t,i)&&(n[i]=t[i]);return n})(e,["agent"])}var Fe=class t extends ue{constructor(t,e,n){var i,r,s;super(t.logger),this.j=null,this.P=0,this.retryCount=0,this.history=function(){var t=o(function*(t){var e=this.client.rest.channelMixin;if(t&&t.untilAttach){if("attached"!==this.state)throw new z("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new z("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=>ue.prototype.whenState.call(this,t,this.state),this.name=e,this.channelOptions=$t(null!=(i=t.M)?i:null,this.logger,n),this.client=t,this.N=t.D?new t.D.RealtimePresence(this):null,t.O&&(this.j=new t.O.RealtimeAnnotations(this)),this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new ue(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this.R=!1,this.U={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this.H={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this.L=new ue(this.logger),(null==(r=t.options.plugins)?void 0:r.Push)&&(this.q=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.N||jt("RealtimePresence"),this.N}get annotations(){return this.j||jt("Annotations"),this.j}get push(){return this.q||jt("Push"),this.q}get object(){return this.F||jt("LiveObjects"),this.F}invalidStateError(){return new z("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&&!V(t.params))return new z("options.params must be an object",4e4,400);if(t&&"modes"in t){if(!Array.isArray(t.modes))return new z("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||!me.includes(String.prototype.toUpperCase.call(n)))return new z("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.U&&(e.U.channelOptions=e.channelOptions),e.V(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)}})})})()}V(t,e){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==t?void 0:t.params){var n=qe(t.params),i=qe(e.params);if(Object.keys(n).length!==Object.keys(i).length)return!0;if(!Ct(i,n))return!0}return!(!(null==t?void 0:t.modes)||e.modes&&It(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=[ze.fromValues({name:r,data:s})],i=t.length<=2?void 0:t[2];else if(V(r))n=[ze.fromValues(r)],i=t.length<=1?void 0:t[1];else{if(!Array.isArray(r))throw new z("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n=ze.fromValuesArray(r),i=t.length<=1?void 0:t[1]}var a=e.client.options.maxMessageSize,o=yield function(t,e){return De.apply(this,arguments)}(n,e.channelOptions),l=function(t){for(var e,n=0,i=0;i<t.length;i++)n+=(e=t[i]).size||(e.size=Ne(e));return n}(o);if(l>a)throw new z("Maximum size of messages that can be published at once exceeded (was "+l+" bytes; limit is "+a+" bytes)",40009,400);e.throwIfUnpublishableState();var h=$e({action:ve.MESSAGE,channel:e.name,messages:o,params:i?ct(i):void 0});return(yield e.sendMessage(h))||{serials:[]}})()}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(t){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.W(!1,null,(t,i)=>t?n(t):e(i))})})()}W(t,e,n){n||(n=t=>{t&&D.logAction(this.logger,D.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 z("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new z("Attach request superseded by a subsequent detach request",9e4,409))}})):n(i.getError())}attachImpl(){var t=$e({action:ve.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&t.encodeModesToFlags(Et(this.channelOptions.modes)),this.R&&t.setFlag("ATTACH_RESUME"),this.H.decodeFailureRecoveryInProgress&&(t.channelSerial=this.H.protocolMessageChannelSerial),this.sendMessage(t).catch(Le)}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 z("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 z("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":i(new z("Detach request superseded by a subsequent attach request",9e4,409))}})})}})()}detachImpl(){var t=$e({action:ve.DETACH,channel:this.name});this.sendMessage(t).catch(Le)}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 z.fromValues(n.invalidStateError());return a&&"object"==typeof a&&!Array.isArray(a)?n.client.I.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.I.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 H("Unable to sync to channel; not attached",4e4)}var t=this.connectionManager;if(!t.activeState())throw t.getError();var e=$e({action:ve.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=$e({action:ve.PRESENCE,channel:e.name,presence:t});yield e.sendMessage(n)})()}sendState(t){var e=this;return o(function*(){var n=$e({action:ve.OBJECT,channel:e.name,state:t});yield e.sendMessage(n)})()}processMessage(t){var e=this;return o(function*(){t.action!==ve.ATTACHED&&t.action!==ve.MESSAGE&&t.action!==ve.PRESENCE&&t.action!==ve.OBJECT&&t.action!==ve.ANNOTATION||e.setChannelSerial(t.channelSerial);var n,i=!1;switch(t.action){case ve.ATTACHED:e.properties.attachSerial=t.channelSerial,e.P=t.getMode(),e.params=t.params||{};var r=t.decodeModesFromFlags();e.modes=r&&kt(r)||void 0;var s=t.hasFlag("RESUMED"),a=t.hasFlag("HAS_PRESENCE"),o=t.hasFlag("HAS_BACKLOG"),l=t.hasFlag("HAS_OBJECTS");if("attached"===e.state){s||(e.N&&e.N.onAttached(a),e.F&&e.F.onAttached(l));var h=new He(e.state,e.state,s,o,t.error);e.L.emit("update",h),s&&!e.channelOptions.updateOnAttached||e.emit("update",h)}else"detaching"===e.state?e.checkPendingState():e.notifyState("attached",t.error,s,a,o,l);break;case ve.DETACHED:var c=t.error?z.fromValues(t.error):new z("Channel detached",90001,404);"detaching"===e.state?e.notifyState("detached",c):"attaching"===e.state?e.notifyState("suspended",c):"attached"!==e.state&&"suspended"!==e.state||e.requestState("attaching",c);break;case ve.SYNC:if(i=!0,n=e.syncChannelSerial=t.channelSerial,!t.presence)break;case ve.PRESENCE:if(!t.presence)break;Me(t);var d=e.channelOptions;if(e.N){var u=yield Promise.all(t.presence.map(t=>t.decode(d,e.logger)));e.N.setPresence(u,i,n)}break;case ve.OBJECT:case ve.OBJECT_SYNC:if(!e.F||!t.state)return;Me(t);var v=e.client.connection.connectionManager.getActiveTransportFormat(),p=t.state.map(t=>t.decode(e.client,v));t.action===ve.OBJECT?e.F.handleObjectMessages(p):e.F.handleObjectSyncMessages(p,t.channelSerial);break;case ve.MESSAGE:if("attached"!==e.state)return;Me(t);var f=t.messages,g=f[0],m=f[f.length-1];if(g.extras&&g.extras.delta&&g.extras.delta.from!==e.H.messageId){var w='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+e.name+'".';D.logAction(e.logger,D.LOG_ERROR,"RealtimeChannel.processMessage()",w),e.J(new z(w,40018,400));break}for(var y=[],b=0;b<f.length;b++){var{decoded:x,err:k}=yield f[b].decodeWithErr(e.U,e.logger);if(y[b]=x,k)switch(k.code){case 40018:return void e.J(k);case 40019:case 40021:return void e.notifyState("failed",k)}}e.H.messageId=m.id,e.H.protocolMessageChannelSerial=t.channelSerial,e.onEvent(y);break;case ve.ANNOTATION:Me(t);var E=e.channelOptions;if(e.j){var A=yield Promise.all((t.annotations||[]).map(t=>t.decode(E,e.logger)));e.j.$(A)}break;case ve.ERROR:var T=t.error;T&&80016==T.code?e.checkPendingState():e.notifyState("failed",z.fromValues(T))}})()}J(t){this.H.decodeFailureRecoveryInProgress||(this.H.decodeFailureRecoveryInProgress=!0,this.W(!0,t,()=>{this.H.decodeFailureRecoveryInProgress=!1}))}onAttached(){}notifyState(t,e,n,i,r,s){if(this.clearStateTimer(),["detached","suspended","failed"].includes(t)&&(this.properties.channelSerial=null),t!==this.state){this.N&&this.N.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 He(this.state,t,n,r,e),o='Channel state for channel "'+this.name+'"',l=t+(e?"; reason: "+e:"");"failed"===t&&D.logAction(this.logger,D.LOG_ERROR,o,l),"attaching"!==t&&"suspended"!==t&&(this.retryCount=0),"attached"===t&&this.onAttached(),"attached"===t?this.R=!0:"detaching"!==t&&"failed"!==t||(this.R=!1),this.state=t,this.L.emit(t,a),this.emit(t,a)}}requestState(t,e){this.notifyState(t,e),this.checkPendingState()}checkPendingState(){if(this.connectionManager.state.sendEvents)switch(this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync()}}timeoutPendingState(){switch(this.state){case"attaching":var t=new z("Channel attach timed out",90007,408);this.notifyState("suspended",t);break;case"detaching":var e=new z("Channel detach timed out",90007,408);this.notifyState("attached",e);break;default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{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=St(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,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 z("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){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 e.client.rest.channelMixin.getMessage(e,t)})()}updateMessage(t,e,n){var i=this;return o(function*(){return i.sendUpdate(t,"message.update",e,n)})()}deleteMessage(t,e,n){var i=this;return o(function*(){return i.sendUpdate(t,"message.delete",e,n)})()}appendMessage(t,e,n){var i=this;return o(function*(){return 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 z('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=ze.fromValues(M(C({},t),{action:e,version:n})),l=yield o.encode(r.channelOptions),h=$e({action:ve.MESSAGE,channel:r.name,messages:[l],params:i?ct(i):void 0}),c=yield r.sendMessage(h);return{versionSerial:null!=(a=null==(s=null==c?void 0:c.serials)?void 0:s[0])?a:null}})()}getMessageVersions(t,e){var n=this;return o(function*(){return 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 z.fromValues(t.invalidStateError())}})()}},Ve=xt;function We(t){var e=[];if(t)for(var n=0;n<t.length;n++)e.push(t[n].toString());return"[ "+e.join(", ")+" ]"}function Je(t,e,n,i,r,s){return function(t,e,n,i){var r,s,a,o,l;t.error&&(r=z.fromValues(t.error));t.messages&&(s=Ue.fromValuesArray(t.messages));e&&t.presence&&(a=e.WirePresenceMessage.fromValuesArray(t.presence));n&&t.annotations&&(o=n.WireAnnotation.fromValuesArray(t.annotations));i&&t.state&&(l=i.WireObjectMessage.fromValuesArray(t.state,R,Ce));return Object.assign(new Ge,M(C({},t),{presence:a,messages:s,annotations:o,state:l,error:r}))}(bt(t,e,s),n,i,r)}function $e(t){return Object.assign(new Ge,t)}function Ke(t,e,n,i){var r="[ProtocolMessage";void 0!==t.action&&(r+="; action="+pe[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="+We(Ue.fromValuesArray(t.messages))),t.presence&&e&&(r+="; presence="+We(e.WirePresenceMessage.fromValuesArray(t.presence))),t.annotations&&n&&(r+="; annotations="+We(n.WireAnnotation.fromValuesArray(t.annotations))),t.state&&i&&(r+="; state="+We(i.WireObjectMessage.fromValuesArray(t.state,R,Ce))),t.error&&(r+="; error="+z.fromValues(t.error).toString()),t.auth&&t.auth.accessToken&&(r+="; token="+t.auth.accessToken),t.flags&&(r+="; flags="+ge.filter(t.hasFlag).join(",")),t.params){var l="";st(t.params,function(e){l.length>0&&(l+="; "),l+=e+"="+t.params[e]}),l.length>0&&(r+="; params=["+l+"]")}return r+="]"}var Ge=class{constructor(){this.hasFlag=t=>(this.flags&fe[t])>0}setFlag(t){return this.flags=this.flags|fe[t]}getMode(){return(this.flags||0)&fe.MODE_ALL}encodeModesToFlags(t){t.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){var t=[];return me.forEach(e=>{this.hasFlag(e)&&t.push(e)}),t.length>0?t:void 0}},Qe=class extends ue{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){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 l=0;l<r.length;l++){var h=r[l],c=null==n?void 0:n[l];h.callback(e,c)}0==i.length&&this.emit("idle")}completeAllMessages(t){this.completeMessages("all",t)}resetSendAttempted(){for(var t of this.messages)t.sendAttempted=!1}clear(){this.messages=[],this.emit("idle")}},Ye=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&&[ve.MESSAGE,ve.PRESENCE,ve.ANNOTATION,ve.OBJECT].includes(n)}},Xe=class extends ue{constructor(t){super(t.logger),this.transport=t,this.messageQueue=new Qe(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){this.messageQueue.completeMessages({serial:t,count:e},null,n)}onNack(t,e,n){D.logAction(this.logger,D.LOG_ERROR,"Protocol.onNack()","serial = "+t+"; count = "+e+"; err = "+vt(n)),n||(n=new z("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(D.LOG_MICRO)&&D.logActionNoStrip(this.logger,D.LOG_MICRO,"Protocol.send()","sending msg; "+Ke(t.message,this.transport.connectionManager.realtime.D,this.transport.connectionManager.realtime.O,this.transport.connectionManager.realtime.K)),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()})}},Ze=class{constructor(t,e,n,i){this.previous=t,this.current=e,n&&(this.retryIn=n),i&&(this.reason=i)}},tn={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001};var en,nn,rn={disconnected:()=>z.fromValues({statusCode:400,code:tn.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>z.fromValues({statusCode:400,code:tn.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>z.fromValues({statusCode:400,code:tn.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>z.fromValues({statusCode:400,code:tn.CLOSING,message:"Connection closing"}),closed:()=>z.fromValues({statusCode:400,code:tn.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>z.fromValues({statusCode:500,code:tn.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>z.fromValues({statusCode:500,code:tn.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},sn=$e({action:ve.CLOSE}),an=$e({action:ve.DISCONNECT}),on=class extends ue{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",rn.closed())}disconnect(t){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",t||rn.disconnected())}fail(t){this.isConnected&&this.requestDisconnect(),this.finish("failed",t||rn.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(D.LOG_MICRO)&&D.logActionNoStrip(this.logger,D.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+Ke(t,this.connectionManager.realtime.D,this.connectionManager.realtime.O,this.connectionManager.realtime.K)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),t.action){case ve.HEARTBEAT:D.logActionNoStrip(this.logger,D.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",t.id);break;case ve.CONNECTED:this.onConnect(t),this.emit("connected",t.error,t.connectionId,t.connectionDetails,t);break;case ve.CLOSED:this.onClose(t);break;case ve.DISCONNECTED:this.onDisconnect(t);break;case ve.ACK:this.emit("ack",t.msgSerial,t.count,t.res);break;case ve.NACK:this.emit("nack",t.msgSerial,t.count,t.error);break;case ve.SYNC:this.connectionManager.onChannelMessage(t,this);break;case ve.ACTIVATE:break;case ve.AUTH:yt(this.auth.authorize(),t=>{t&&D.logAction(this.logger,D.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+vt(t))});break;case ve.ERROR:if(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;this.finish("disconnected",e)}onFatalError(t){var e=t&&t.error;this.finish("failed",e)}onClose(t){var e=t&&t.error;this.finish("closed",e)}requestClose(){this.send(sn)}requestDisconnect(){this.send(an)}ping(t){var e={action:ve.HEARTBEAT};t&&(e.id=t),this.send($e(e))}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";D.logAction(this.logger,D.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new z(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})},l=e.options.timeouts.realtimeRequestTimeout;return s=setTimeout(()=>{a.off(["preconnect","disconnected","failed"]),a.dispose(),o.call({event:"disconnected"},new z("Timeout waiting for transport to indicate itself viable",5e4,500))},l),a.on(["failed","disconnected"],o),a.on("preconnect",function(){clearTimeout(s),a.off(["failed","disconnected"],o),r(null,a)}),a.connect(),a}static isAvailable(){throw new z("isAvailable not implemented for transport",5e4,500)}};(nn=en||(en={})).WebSocket="web_socket",nn.Comet="comet",nn.XhrPolling="xhr_polling";var ln="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,hn=()=>{var t;return void 0!==I.WebStorage&&(null==(t=I.WebStorage)?void 0:t.localSupported)},cn=()=>{var t;return void 0!==I.WebStorage&&(null==(t=I.WebStorage)?void 0:t.sessionSupported)},dn=function(){},un="ably-transport-preference";function vn(t){try{return JSON.parse(t)}catch(t){return null}}var pn=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?q(t):{},n=this.options;switch(this.mode){case"resume":e.resume=this.connectionKey;break;case"recover":var i=vn(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=Qt.protocolVersion,e.agent=Wt(this.options),void 0!==n.transportParams&&L(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+="]"}},fn=class t extends ue{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 Qe(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=X(e.transports||Qt.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(en.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(en.XhrPolling)?this.baseTransport=en.XhrPolling:this.transports.includes(en.Comet)&&(this.baseTransport=en.Comet),this.domains=Qt.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,!this.transports.length){var r="no requested transports available";throw D.logAction(this.logger,D.LOG_ERROR,"realtime.ConnectionManager()",r),new Error(r)}var s=I.Config.addEventListener;s&&(cn()&&"function"==typeof e.recover&&s("beforeunload",this.persistConnection.bind(this)),!0===e.closeOnUnload&&s("beforeunload",()=>{this.requestState({state:"closing"})}),s("online",()=>{var t;this.state==this.states.disconnected||this.state==this.states.suspended?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&&this.disconnectAllTransports()}))}static supportedTransports(t){var e={supportedTransports:{}};return this.initTransports(t,e),e.supportedTransports}static initTransports(t,e){var n=C(C({},I.Transports.bundledImplementations),t);[en.WebSocket,...I.Transports.order].forEach(t=>{var i=n[t];i&&i.isAvailable()&&(e.supportedTransports[t]=i)})}initTransports(){t.initTransports(this.realtime.G,this)}createTransportParams(t,e){return new pn(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();this.sessionRecoveryName(),n&&"function"==typeof e?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){var i=vn(this.options.recover);i&&(this.msgSerial=i.msgSerial)}t(n)})}tryATransport(t,e,n){this.proposedTransport=on.tryConnect(this.supportedTransports[e],this,this.realtime.auth,t,(i,r)=>{var s,a=this.state;if(a==this.states.closing||a==this.states.closed||a==this.states.failed)return r&&r.close(),void n(!0);i?!oe.isTokenErr(i.error)||this.errorReason&&oe.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(tn).includes(s.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:i.error}),n(!0))):(this.errorReason=i.error,yt(this.realtime.auth.o(null,null),i=>{i?this.actOnErrorFromAuthorize(i):this.tryATransport(t,e,n)})):(this.setTransportPending(r,t),n(null,r))})}setTransportPending(t,e){var n=e.mode;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){t&&D.logAction(this.logger,D.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+t),this.persistTransportPreference(e);var r=this.state,s=this.states.connected.state;if(r.state==this.states.closing.state||r.state==this.states.closed.state||r.state==this.states.failed.state)return e.disconnect(),!1;if(delete this.pendingTransport,!e.isConnected)return!1;var a=this.activeProtocol;this.activeProtocol=new Xe(e),this.host=e.params.host;var o=i.connectionKey;if(o&&this.connectionKey!=o&&this.setConnection(n,i,!!t),this.onConnectionDetailsUpdate(i,e),I.Config.nextTick(()=>{e.on("connected",(t,n,i)=>{this.onConnectionDetailsUpdate(i,e),this.emit("update",new Ze(s,s,null,t))})}),r.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new Ze(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&&D.logAction(this.logger,D.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 l="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+e.shortName+"; stack = "+(new Error).stack;D.logAction(this.logger,D.LOG_ERROR,"ConnectionManager.activateTransport()",l)}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(n&&n.message,r&&(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&&oe.isTokenErr(n)?"disconnected":e;this.notifyState({state:o,error:n})}else;}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(t,e,n){var i=this.connectionId;(i&&i!==t||!i&&n)&&(this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId,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(){this.lastActivity&&this.connectionId&&(Date.now()-this.lastActivity>this.connectionStateTtl+this.maxIdleInterval&&(this.clearConnection(),this.states.connecting.failState="suspended"))}persistConnection(){if(cn()){var t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:ln.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=H.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,e;return null==(e=(t=rn)[this.state.state])?void 0:e.call(t)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(t){var e=t.current+(t.reason?"; reason: "+t.reason:"");"failed"===t.current&&D.logAction(this.logger,D.LOG_ERROR,"Connection state",e);var n=this.state=this.states[t.current];t.reason&&(this.errorReason=t.reason,this.realtime.connection.errorReason=t.reason),(n.terminal||"suspended"===n.state)&&this.clearConnection(),this.emit("connectionstate",t)}startTransitionTimer(t){this.transitionTimer&&clearTimeout(this.transitionTimer),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,this.notifyState({state:t.failState}))},t.retryDelay)}cancelTransitionTimer(){this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,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(()=>{this.retryTimer=null,this.requestState({state:"connecting"})},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{this.checkWsConnectivity().then(()=>{this.wsCheckResult=!0}).catch(()=>{this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&yt(this.realtime.http.checkConnectivity(),(t,e)=>{!t&&e||(this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new z("Unable to connect (network unreachable)",80003,404)}))})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(t){this.webSocketGiveUpTimer=setTimeout(()=>{var e,n;this.wsCheckResult||this.baseTransport&&(this.abandonedWebSocket=!0,null==(e=this.proposedTransport)||e.dispose(),null==(n=this.pendingTransport)||n.dispose(),this.connectBase(t,++this.connectCounter))},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&&oe.isTokenErr(t.error)&&!(this.errorReason&&oe.isTokenErr(this.errorReason)));if(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=St(s.retryDelay,this.disconnectedRetryCount));var o=new Ze(this.state.state,s.state,a,t.error||(null==(n=(e=rn)[s.state])?void 0:n.call(e)));if(r){var l=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},h=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;h&&h<1e3?setTimeout(l,1e3-h):I.Config.nextTick(l)}else"disconnected"!==i&&"suspended"!==i||this.startRetryTimer(a);("disconnected"===i&&!r||"suspended"===i||s.terminal)&&I.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=i||this.activeProtocol||D.logAction(this.logger,D.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(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 Ze(this.state.state,r.state,null,t.error||(null==(n=(e=rn)[r.state])?void 0:n.call(e)));this.enactStateChange(s),"connecting"==i&&I.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=vn(t.options.recover);n&&this.realtime.channels.recoverChannels(n.channelSerials)}e===this.connectCounter&&this.connectImpl(t,e)})};if(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&&oe.isTokenErr(this.errorReason)?yt(t.o(null,null),i):yt(t.l(!1),i)}}}connectImpl(t,e){if(this.state.state===this.states.connecting.state){var n=this.getTransportPreference();n&&n===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(this.disconnectAllTransports(),this.connectWs(t,++this.connectCounter))}).catch(dn),n&&n===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(t,e):this.connectWs(t,e)}}connectWs(t,e){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){this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,t,!1,e,()=>!0):this.notifyState({state:"disconnected",error:new z("No transports left to try",8e4,404)})}tryTransportWithFallbacks(t,e,n,i,r){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||h():e&&e.dispose())},l=a.shift();if(l){e.host=l;var h=()=>{a.length?this.realtime.http.checkConnectivity?yt(this.realtime.http.checkConnectivity(),(n,l)=>{i===this.connectCounter&&r()&&(n?s(n):l?(e.host=lt(a),this.tryATransport(e,t,o)):s(new z("Unable to connect (network unreachable)",80003,404)))}):s(new H("Internal error: Http.checkConnectivity not set",null,500)):s(new z("Unable to connect (and no more fallback hosts to try)",80003,404))};if(this.forceFallbackHost&&a.length)return this.forceFallbackHost=!1,void h();this.tryATransport(e,t,o)}else s(new z("Unable to connect (no available host)",80003,404))}closeImpl(){this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&this.pendingTransport.close(),this.activeProtocol&&this.activeProtocol.getTransport().close(),this.notifyState({state:"closed"})}onAuthUpdated(t,e){var n;switch(this.state.state){case"connected":var i=null==(n=this.activeProtocol)?void 0:n.getTransport();i&&i.onAuthUpdated&&i.onAuthUpdated(t);var r=$e({action:ve.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":this.disconnectAllTransports();default: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(){this.connectCounter++,this.pendingTransport&&this.pendingTransport.disconnect(),delete this.pendingTransport,this.proposedTransport&&this.proposedTransport.disconnect(),delete this.pendingTransport,this.activeProtocol&&this.activeProtocol.getTransport().disconnect()}send(t,e,n){n=n||dn;var i=this.state;if(i.sendEvents)this.sendImpl(new Ye(t,n));else if(e&&i.queueEvents)this.logger.shouldLog(D.LOG_MICRO),this.queue(t,n);else{var r="rejecting event, queueEvent was "+e+", state was "+i.state;n(this.errorReason||new z(r,9e4,400))}}sendImpl(t){var e=t.message;t.ackRequired&&!t.sendAttempted&&(e.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(t){D.logAction(this.logger,D.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+t.stack)}}queue(t,e){this.queuedMessages.push(new Ye(t,e))}sendQueuedMessages(){for(var t;t=this.queuedMessages.shift();)this.sendImpl(t)}queuePendingMessages(t){t&&t.length&&this.queuedMessages.prepend(t)}failQueuedMessages(t){var e=this.queuedMessages.count();e>0&&(D.logAction(this.logger,D.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+e+" queued messages, err = "+vt(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=>{D.logAction(this.logger,D.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 z("Unable to ping service; not connected",4e4,400);var n=null==(e=t.activeProtocol)?void 0:e.getTransport();if(!n)throw t.getStateError();var i=Date.now(),r=gt();return Pt(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||hn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.get)?void 0:e.call(t,un))}persistTransportPreference(t){var e,n;this.transportPreference=t.shortName,hn()&&(null==(n=null==(e=I.WebStorage)?void 0:e.set)||n.call(e,un,t.shortName))}unpersistTransportPreference(){var t,e;this.transportPreference=null,hn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.remove)||e.call(t,un))}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===ee.Forbidden){var e="Client configured authentication provider returned 403; failing the connection";D.logAction(this.logger,D.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",e),this.notifyState({state:"failed",error:new z(e,80019,403,t)})}else{this.notifyState({state:this.state.failState,error:new z("Client configured authentication provider request failed",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 D.logAction(this.logger,D.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||Qt.wsConnectivityCheckUrl,e=new I.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 cn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.getSession)?void 0:e.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var e,n;return cn()&&(null==(n=null==(e=I.WebStorage)?void 0:e.setSession)?void 0:n.call(e,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,e;return cn()&&(null==(e=null==(t=I.WebStorage)?void 0:t.removeSession)?void 0:e.call(t,this.sessionRecoveryName()))}},gn=class extends ue{constructor(t,e){super(t.logger),this.whenState=t=>ue.prototype.whenState.call(this,t,this.state),this.ably=t,this.connectionManager=new fn(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;I.Config.nextTick(()=>{this.emit(e,t)})}),this.connectionManager.on("update",t=>{I.Config.nextTick(()=>{this.emit("update",t)})})}connect(){this.connectionManager.requestState({state:"connecting"})}ping(){var t=this;return o(function*(){return t.connectionManager.ping()})()}close(){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()}},mn=class t extends je{constructor(e){var n,i,r,s;if(super(Qt.objectifyOptions(e,!1,"BaseRealtime",D.defaultLogger)),"string"==typeof EdgeRuntime)throw new z('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.G=t.transportImplementationsFromPlugins(this.options.plugins),this.D=null!=(i=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?i:null,this.K=null!=(s=null==(r=this.options.plugins)?void 0:r.LiveObjects)?s:null,this.connection=new gn(this,this.options),this.Y=new yn(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(t){var e={};return(null==t?void 0:t.WebSocketTransport)&&(e[en.WebSocket]=t.WebSocketTransport),(null==t?void 0:t.XHRPolling)&&(e[en.XhrPolling]=t.XHRPolling),e}get channels(){return this.Y}get clientId(){return this.auth.clientId}connect(){this.connection.connect()}close(){this.connection.close()}};mn.EventEmitter=ue;var wn=mn,yn=class extends ue{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 it(this.all,!0)){var n=this.all[e];n.properties.channelSerial&&(t[e]=n.properties.channelSerial)}return t}recoverChannels(t){for(var e of it(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):D.logAction(e.logger,D.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n)}else D.logAction(e.logger,D.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.W(!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.V(e,n.channelOptions))throw new z("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 Fe(this.realtime,t,e);return n}getDerived(t,e,n){if(e.filter){var i=Ot(e.filter),r=Mt(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]}}},bn=wn,xn=Uint8Array,kn=Uint32Array,En=Math.pow,An=new kn(8),Tn=[],Sn=new kn(64);function _n(t){return(t-(0|t))*En(2,32)|0}for(var Cn,Mn,On=2,In=0;In<64;){for(Cn=!0,Mn=2;Mn<=On/2;Mn++)On%Mn===0&&(Cn=!1);Cn&&(In<8&&(An[In]=_n(En(On,.5))),Tn[In]=_n(En(On,1/3)),In++),On++}var Bn=!!new xn(new kn([1]).buffer)[0];function jn(t){return Bn?t>>>24|(t>>>16&255)<<8|(65280&t)<<8|t<<24:t}function Pn(t,e){return t>>>e|t<<32-e}function Nn(t){var e,n=An.slice(),i=t.length,r=8*i,s=512-(r+64)%512-1+r+65,a=new xn(s/8),o=new kn(a.buffer);a.set(t,0),a[i]=128,o[o.length-1]=jn(r);for(var l=0;l<s/32;l+=16){var h=n.slice();for(e=0;e<64;e++){var c;if(e<16)c=jn(o[l+e]);else{var d=Sn[e-15],u=Sn[e-2];c=Sn[e-7]+Sn[e-16]+(Pn(d,7)^Pn(d,18)^d>>>3)+(Pn(u,17)^Pn(u,19)^u>>>10)}Sn[e]=c|=0;for(var v=(Pn(h[4],6)^Pn(h[4],11)^Pn(h[4],25))+(h[4]&h[5]^~h[4]&h[6])+h[7]+c+Tn[e],p=(Pn(h[0],2)^Pn(h[0],13)^Pn(h[0],22))+(h[0]&h[1]^h[2]&(h[0]^h[1])),f=7;f>0;f--)h[f]=h[f-1];h[0]=v+p|0,h[4]=h[4]+v|0}for(e=0;e<8;e++)n[e]=n[e]+h[e]|0}return new xn(new kn(n.map(function(t){return jn(t)})).buffer)}var Dn,Rn=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(t){for(var e,n,i,r,s="",a=this.base64CharSet,o=t.byteLength,l=o%3,h=o-l,c=0;c<h;c+=3)e=(258048&(r=t[c]<<16|t[c+1]<<8|t[c+2]))>>12,n=(4032&r)>>6,i=63&r,s+=a[(16515072&r)>>18]+a[e]+a[n]+a[i];return 1==l?(e=(3&(r=t[h]))<<4,s+=a[(252&r)>>2]+a[e]+"=="):2==l&&(e=(1008&(r=t[h]<<8|t[h+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&&I.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(I.Config.TextEncoder){var e=(new I.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=Nn(this.toBuffer(t));return this.toArrayBuffer(e)}hmacSha256(t,e){var n=function(t,e){if(t.length>64&&(t=Nn(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(Nn(a),64),Nn(o)}(this.toBuffer(e),this.toBuffer(t));return this.toArrayBuffer(n)}},Un=(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))(Un||{}),zn=Un;function Hn(){return new z("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var Ln=(Dn=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)||Qt.connectivityCheckUrl,i=null!=(e=null==t?void 0:t.options.connectivityCheckParams)?e:null,r=!(null==t?void 0:t.options.connectivityCheckUrl),s=C(C({},Ln.bundledRequestImplementations),null==t?void 0:t.T),a=s.XHRRequest,l=s.FetchRequest,h=!(!a&&!l);if(!h)throw Hn();I.Config.xhrSupported&&a?(this.supportsAuthHeaders=!0,this.Request=function(){var e=o(function*(e,n,i,r,s){return new Promise(o=>{var l,h=a.createRequest(n,i,r,s,zn.REQ_SEND,null!=(l=t&&t.options.timeouts)?l:null,this.logger,e);h.once("complete",(t,e,n,i,r)=>o({error:t,body:e,headers:n,unpacked:i,statusCode:r})),h.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,e,s=yield this.doUri(Zt.Get,n,null,null,i);return r?!s.error&&"yes"==(null==(t=s.body)?void 0:t.replace(/\n/,"")):!s.error&&((e=s.statusCode)>=200&&e<400)})):I.Config.fetchSupported&&l?(this.supportsAuthHeaders=!0,this.Request=function(){var e=o(function*(e,n,i,r,s){return l(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,e=yield this.doUri(Zt.Get,n,null,null,null);return!e.error&&"yes"==(null==(t=e.body)?void 0:t.replace(/\n/,""))})):this.Request=o(function*(){return{error:h?new H("no supported HTTP transports available",null,400):Hn()}})}get logger(){var t,e;return null!=(e=null==(t=this.client)?void 0:t.logger)?e:D.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 H("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}},Dn.methods=[Zt.Get,Zt.Delete,Zt.Post,Zt.Put,Zt.Patch],Dn.methodsWithoutBody=[Zt.Get,Zt.Delete],Dn.methodsWithBody=[Zt.Post,Zt.Put,Zt.Patch],Dn),qn=Ln,Fn="ablyjs-storage-test",Vn="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,Wn=new class{constructor(){try{Vn.sessionStorage.setItem(Fn,Fn),Vn.sessionStorage.removeItem(Fn),this.sessionSupported=!0}catch(t){this.sessionSupported=!1}try{Vn.localStorage.setItem(Fn,Fn),Vn.localStorage.removeItem(Fn),this.localSupported=!0}catch(t){this.localSupported=!1}}get(t){return this.X(t,!1)}getSession(t){return this.X(t,!0)}remove(t){return this.Z(t,!1)}removeSession(t){return this.Z(t,!0)}set(t,e,n){return this.tt(t,e,n,!1)}setSession(t,e,n){return this.tt(t,e,n,!0)}tt(t,e,n,i){var r={value:e};return n&&(r.expires=Date.now()+n),this.storageInterface(i).setItem(t,JSON.stringify(r))}X(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}Z(t,e){return this.storageInterface(e).removeItem(t)}storageInterface(t){return t?Vn.sessionStorage:Vn.localStorage}},Jn=_t(),$n="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||$n||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var Kn,Gn,Qn={agent:"browser",logTimestamps:!0,userAgent:Jn.navigator&&Jn.navigator.userAgent.toString(),currentUrl:Jn.location&&Jn.location.href,binaryType:"arraybuffer",WebSocket:Jn.WebSocket,fetchSupported:!!Jn.fetch,xhrSupported:Jn.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:(Gn=Jn.location,!Jn.WebSocket||!Gn||!Gn.origin||Gn.origin.indexOf("http")>-1),useProtocolHeartbeats:!0,supportsBinary:!!Jn.TextDecoder,preferBinary:!1,ArrayBuffer:Jn.ArrayBuffer,atob:Jn.atob,nextTick:"function"==typeof Jn.queueMicrotask?t=>Jn.queueMicrotask(t):t=>Promise.resolve().then(t),addEventListener:Jn.addEventListener,inspect:JSON.stringify,stringByteSize:function(t){return Jn.TextDecoder&&(new Jn.TextEncoder).encode(t).length||t.length},TextEncoder:Jn.TextEncoder,TextDecoder:Jn.TextDecoder,getRandomArrayBuffer:(Kn=o(function*(t){var e=new Uint8Array(t);return Jn.crypto.getRandomValues(e),e.buffer}),function(t){return Kn.apply(this,arguments)}),isWebworker:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,push:{platform:"browser",formFactor:"desktop",storage:Wn}},Yn=Qn;en.XhrPolling;var Xn=en.WebSocket;var Zn=class extends on{constructor(t,e,n){super(t,e,n),this.shortName=Xn,n.heartbeats=I.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!I.Config.WebSocket}createWebSocket(t,e){return this.uri=t+ht(e),new I.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){on.prototype.connect.call(this);var t=this,e=this.params,n=e.options,i=(n.tls?"wss://":"ws://")+this.wsHost+":"+Qt.getPort(n)+"/";yt(this.auth.getAuthParams(),function(n,r){if(!t.isDisposed){for(var s in r)" "+s+": "+r[s]+";";if(n)t.disconnect(n);else{var a=e.getConnectParams(r);try{var o=t.wsConnection=t.createWebSocket(i,a);o.binaryType=I.Config.binaryType,o.onopen=function(){t.onWsOpen()},o.onclose=function(e){t.onWsClose(e)},o.onmessage=function(e){t.onWsData(e.data)},o.onerror=function(e){t.onWsError(e)},o.on&&o.on("ping",function(){t.onActivity()})}catch(e){D.logAction(t.logger,D.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(Ve(t,this.connectionManager.realtime.S,this.params.format))}catch(t){var n="Exception from ws connection when trying to send: "+vt(t);D.logAction(this.logger,D.LOG_ERROR,"WebSocketTransport.send()",n),this.finish("disconnected",new z(n,5e4,500))}else D.logAction(this.logger,D.LOG_ERROR,"WebSocketTransport.send()","No socket connection")}onWsData(t){try{this.onProtocolMessage(Je(t,this.connectionManager.realtime.S,this.connectionManager.realtime.D,this.connectionManager.realtime.O,this.connectionManager.realtime.K,this.format))}catch(t){D.logAction(this.logger,D.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+t.stack)}}onWsOpen(){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){var i=new z("Websocket closed",80003,400);this.finish("disconnected",i)}else{var r=new z("Unclean disconnection of WebSocket ; code = "+n,80003,400);this.finish("disconnected",r)}this.emit("disposed")}onWsError(t){I.Config.nextTick(()=>{this.disconnect(Error(t.message))})}dispose(){this.isDisposed=!0;var t=this.wsConnection;t&&(t.onmessage=function(){},delete this.wsConnection,I.Config.nextTick(()=>{if(!t)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");t.close()}))}},ti={order:["xhr_polling"],bundledImplementations:{}},ei={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[en.XhrPolling,en.WebSocket]};function ni(t,e,n,i,r,s){return ii.apply(this,arguments)}function ii(){return(ii=o(function*(t,e,n,i,r,s){var a,l=new Headers(i||{}),h=t?t.toUpperCase():J(s)?"GET":"POST",c=new AbortController,d=new Promise(t=>{a=setTimeout(()=>{c.abort(),t({error:new H("Request timed out",null,408)})},e?e.options.timeouts.httpRequestTimeout:Qt.TIMEOUTS.httpRequestTimeout)}),u={method:h,headers:l,body:s,signal:c.signal};I.Config.isWebworker||(u.credentials=l.has("authorization")?"include":"same-origin");var v=o(function*(){try{var t=new URLSearchParams(r||{});t.set("rnd",gt());var e=n+"?"+t,i=yield _t().fetch(e,u);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 l=!!o&&-1===o.indexOf("application/x-msgpack"),h=function(t){var e={};return t.forEach((t,n)=>{e[n]=t}),e}(i.headers);if(i.ok)return{error:null,body:s,headers:h,unpacked:l,statusCode:i.status};var c=function(t,e){if(function(t,e){return!!e.get("x-ably-errorcode")}(0,e))return t.error&&z.fromValues(t.error)}(s,i.headers)||new H("Error response received from server: "+i.status+" body was: "+I.Config.inspect(s),null,i.status);return{error:c,body:s,headers:h,unpacked:l,statusCode:i.status}}catch(c){return clearTimeout(a),{error:c}}})();return Promise.race([d,v])})).apply(this,arguments)}var ri;I.BufferUtils=Rn,I.Http=qn,I.Config=Yn,I.Transports=ti,I.WebStorage=Wn,qn.bundledRequestImplementations={},D.initLogHandlers(),I.Defaults=(ri=ei,Object.assign(Ut,ri)),I.Config.agent&&(I.Defaults.agent+=" "+I.Config.agent);class si{constructor(){this.et=new Map}register(t){this.et.has(t.type)||this.et.set(t.type,t)}get(t){return this.et.get(t)}getAll(){return Array.from(this.et.values())}getToolDefinitions(){var t={};for(var e of this.et.values())t[e.type]={description:e.toolDescription,parameters:e.parameters};return t}}function ai(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var oi={type:"collect_email",toolDescription:"ALWAYS use this tool instead of asking for email in plain text. Renders an interactive form to collect the user's name and email. Use whenever the user wants follow-up, a demo, a meeting, pricing info, or shows buying intent. NEVER ask for name or email via plain text.",parameters:{prompt:{type:"string",description:"Message to show above the input fields"}},render(t,e){var n="string"==typeof t.prompt?t.prompt:"What's your name and email?",i=e.primaryColor,r="w-"+Date.now();return'\n <div class="vtilt-widget" data-vtilt-widget-type="collect_email" data-vtilt-widget-id="'+ai(r)+'" data-vtilt-msg-id="'+ai(e.messageId)+'">\n <p style="margin: 0 0 10px 0; font-size: 14px; color: #333;">'+ai(n)+'</p>\n <div style="display: flex; flex-direction: column; gap: 8px;">\n <input type="text" placeholder="Your name" class="vtilt-widget-input" data-vtilt-widget-field="name"\n style="width: 100%; box-sizing: border-box; padding: 10px 12px; border: 1px solid #E5E5E5; border-radius: 12px; font-size: 14px;"\n />\n <div style="display: flex; gap: 8px; align-items: center;">\n <input type="email" placeholder="your@email.com" class="vtilt-widget-input" data-vtilt-widget-field="email"\n style="flex: 1; min-width: 0; padding: 10px 12px; border: 1px solid #E5E5E5; border-radius: 12px; font-size: 14px;"\n />\n <button type="button" data-vtilt-widget-action="submit" data-vtilt-widget-type="collect_email" data-vtilt-widget-id="'+ai(r)+'"\n style="padding: 10px 16px; background: transparent; color: '+i+"; border: 2px solid "+i+'; border-radius: 12px; font-size: 14px; font-weight: 600; cursor: pointer; white-space: nowrap;"\n >Submit</button>\n </div>\n </div>\n </div>\n '},onAction:(t,e,n)=>o(function*(){if("submit"!==t)return{};var i="string"==typeof e.email?e.email.trim():"";if(!i||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))return{};var r=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),s=n.token?{"x-api-key":n.token}:{};try{var a=yield fetch(r,{method:"POST",headers:l({"Content-Type":"application/json"},s),body:JSON.stringify({widget_type:"collect_email",action:"submit",data:{email:i,name:"string"==typeof e.name?e.name.trim():""},channel_id:n.channelId,distinct_id:n.distinctId,message_id:n.messageId})});return{success:!!(yield a.json()).success}}catch(t){return{}}})()};function li(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var hi={type:"escalate_to_human",toolDescription:"Offer to connect the user with a human agent. Use when the user explicitly asks to speak with a person, when you cannot adequately help them, or when the conversation requires human judgment (billing, complaints, complex issues).",parameters:{prompt:{type:"string",description:"Message to show above the connect button"}},render(t,e){var n="string"==typeof t.prompt?t.prompt:"Would you like me to connect you with a team member?",i=e.primaryColor,r="w-esc-"+Date.now();return'\n <div class="vtilt-widget" data-vtilt-widget-type="escalate_to_human" data-vtilt-widget-id="'+li(r)+'" data-vtilt-msg-id="'+li(e.messageId)+'">\n <p style="margin: 0 0 10px 0; font-size: 14px; color: #333;">'+li(n)+'</p>\n <button type="button" data-vtilt-widget-action="escalate" data-vtilt-widget-type="escalate_to_human" data-vtilt-widget-id="'+li(r)+'"\n style="padding: 10px 20px; background: transparent; color: '+i+"; border: 2px solid "+i+'; border-radius: 12px; font-size: 14px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px;"\n ><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="'+i+'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>Connect with a person</button>\n </div>\n '},onAction:(t,e,n)=>o(function*(){if("escalate"!==t)return{};var e=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),i=n.token?{"x-api-key":n.token}:{};try{var r=yield fetch(e,{method:"POST",headers:l({"Content-Type":"application/json"},i),body:JSON.stringify({widget_type:"escalate_to_human",action:"escalate",data:{},channel_id:n.channelId,distinct_id:n.distinctId,message_id:n.messageId})});return{success:!!(yield r.json()).success}}catch(t){return{}}})()},ci="#vtilt-chat-widget",di="\n "+ci+" .vtilt-md {\n max-width: 100%;\n overflow-wrap: anywhere;\n word-break: break-word;\n font-size: inherit;\n line-height: 1.45;\n }\n "+ci+" .vtilt-md * {\n box-sizing: border-box;\n }\n "+ci+" .vtilt-md :is(p, h1, h2, h3, h4, h5, h6, ul, ol, blockquote, pre) {\n margin: 0;\n }\n "+ci+" .vtilt-md p { margin: 0 0 0.5em 0; }\n "+ci+" .vtilt-md p:last-child { margin-bottom: 0; }\n "+ci+" .vtilt-md :is(b, strong) { font-weight: 600; }\n "+ci+" .vtilt-md :is(i, em) { font-style: italic; }\n "+ci+" .vtilt-md u { text-decoration: underline; }\n "+ci+" .vtilt-md :is(h1, h2, h3, h4, h5, h6) {\n font-size: 1em;\n font-weight: 600;\n margin: 0.65em 0 0.35em 0;\n line-height: 1.3;\n }\n "+ci+" .vtilt-md :is(h1, h2, h3):first-child { margin-top: 0.15em; }\n\n /* Lists — flex rows + ::before bullets (beats host list-item / ::marker resets) */\n "+ci+" .vtilt-md :is(ul, ol) {\n list-style: none !important;\n margin: 0.5em 0 !important;\n padding: 0 0 0 0.35em !important;\n }\n "+ci+" .vtilt-md li {\n display: flex !important;\n flex-direction: row !important;\n flex-wrap: wrap !important;\n align-items: flex-start !important;\n gap: 0.35em !important;\n margin: 0.2em 0 !important;\n padding: 0 !important;\n line-height: 1.45;\n list-style: none !important;\n list-style-type: none !important;\n }\n "+ci+' .vtilt-md li::marker {\n content: "" !important;\n font-size: 0 !important;\n color: transparent !important;\n }\n '+ci+" .vtilt-md li::-webkit-list-marker {\n display: none !important;\n }\n "+ci+' .vtilt-md ul > li::before {\n content: "•" !important;\n display: inline-block !important;\n position: static !important;\n flex: 0 0 auto;\n line-height: 1.45;\n }\n '+ci+' .vtilt-md ul ul > li::before {\n content: "◦" !important;\n }\n '+ci+" .vtilt-md ol { counter-reset: vtilt-ol; }\n "+ci+" .vtilt-md ol > li { counter-increment: vtilt-ol; }\n "+ci+' .vtilt-md ol > li::before {\n content: counter(vtilt-ol) "." !important;\n display: inline-block !important;\n position: static !important;\n flex: 0 0 auto;\n min-width: 1.1em;\n line-height: 1.45;\n }\n '+ci+" .vtilt-md ol ol { counter-reset: vtilt-ol; }\n "+ci+" .vtilt-md li > :is(ul, ol) {\n flex: 1 0 100% !important;\n width: 100% !important;\n margin: 0.25em 0 0 0 !important;\n padding-left: 0.75em !important;\n }\n\n "+ci+" .vtilt-md code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n font-size: 0.9em;\n background: rgba(0, 0, 0, 0.06);\n padding: 0.1em 0.35em;\n border-radius: 4px;\n }\n "+ci+" .vtilt-md pre {\n margin: 0.5em 0;\n padding: 0.5em 0.65em;\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.06);\n overflow-x: auto;\n white-space: pre-wrap;\n }\n "+ci+" .vtilt-md pre code { background: none; padding: 0; }\n "+ci+" .vtilt-md blockquote {\n margin: 0.5em 0;\n padding-left: 0.75em;\n border-left: 3px solid rgba(0, 0, 0, 0.15);\n }\n "+ci+" .vtilt-md a { color: inherit; text-decoration: underline; }\n "+ci+" .vtilt-md br { line-height: inherit; }\n\n /* Widget visitor bubble (brand color) */\n "+ci+" .vtilt-user-md code { background: rgba(255, 255, 255, 0.2); }\n "+ci+" .vtilt-user-md pre { background: rgba(255, 255, 255, 0.15); }\n "+ci+" .vtilt-user-md pre code { background: none; }\n "+ci+" .vtilt-user-md blockquote { border-left-color: rgba(255, 255, 255, 0.35); }\n";var ui={none:0,error:1,warn:2,info:3,debug:4},vi="[vTilt]",pi=new Set(["none","error","warn","info","debug"]);function fi(){return"undefined"!=typeof console}function gi(t){var e=t.length>0&&"string"==typeof t[0]?t[0]:"",n=e?t.slice(1):t;return[e?vi+":"+e:vi,...n]}var mi="warn",wi=!1;var yi=null;function bi(){return yi||(yi={setLevel(t,e){void 0===e&&(e=!1),mi=t,e&&(wi=!0)},setLevelFromRemote(t){wi||t&&pi.has(t)&&(mi=t)},getLevel:()=>mi,isLockedByInit:()=>wi,debug(){if(!(ui[mi]<ui.debug)&&fi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...gi(e))}},info(){if(!(ui[mi]<ui.info)&&fi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...gi(e))}},warn(){if(!(ui[mi]<ui.warn)&&fi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.warn(...gi(e))}},error(){if(!(ui[mi]<ui.error)&&fi()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.error(...gi(e))}}}),yi}var xi="/api/chat/widget/channels",ki=t=>"/api/chat/widget/channels/"+t+"/messages",Ei=t=>"/api/chat/widget/channels/"+t+"/read",Ai="/api/chat/token/widget";function Ti(t,e,n){return Si.apply(this,arguments)}function Si(){return(Si=o(function*(t,e,n){void 0===n&&(n={});var i=t.getConfig(),r=w(i,e);try{var s=yield fetch(r,l({},n,{headers:l({"Content-Type":"application/json"},y(i),n.headers)}));if(!s.ok)throw new Error("API error: "+s.status);return yield s.json()}catch(t){return bi().error("chat","API request failed:",t),null}})).apply(this,arguments)}var _i="vtilt-bubble-pos";function Ci(t,e,n){var i=t.getBoundingClientRect(),r=i.left-e,s=i.top-n,a=window.innerWidth-t.offsetWidth-r,o=-r,l=window.innerHeight-t.offsetHeight-s,h=-s;return{x:Math.min(Math.max(e,o),a),y:Math.min(Math.max(n,h),l)}}function Mi(t,e,n){t.style.transform="translate3d("+e+"px, "+n+"px, 0)"}function Oi(t,e){var n,i=null!==(n=null==e?void 0:e.handle)&&void 0!==n?n:t,r=0,s=0,a=0,o=0,l=0,h=0,c=!1,d=!1,u=function(){try{var t=localStorage.getItem(_i);if(!t)return null;var e=JSON.parse(t);if("number"==typeof e.x&&"number"==typeof e.y)return e}catch(t){}return null}();if(u){r=u.x,s=u.y;var v=t.style.transition;t.style.transition="none",Mi(t,r,s);var p=Ci(t,r,s);r=p.x,s=p.y,Mi(t,r,s),t.offsetHeight,t.style.transition=v}i.style.cursor="grab",i.style.touchAction="none";var f=e=>{0===e.button&&(c=!0,d=!1,a=e.clientX,o=e.clientY,l=r,h=s,i.setPointerCapture(e.pointerId),i.style.cursor="grabbing",t.style.transition="none")},g=e=>{if(c){var n=e.clientX-a,i=e.clientY-o;if(!(!d&&Math.abs(n)<5&&Math.abs(i)<5)){d=!0;var u={x:l+n,y:h+i},v=Ci(t,u.x,u.y);r=v.x,s=v.y,Mi(t,r,s)}}},m=()=>{c&&(c=!1,i.style.cursor="grab",t.style.transition="",d&&function(t){try{localStorage.setItem(_i,JSON.stringify(t))}catch(t){}}({x:r,y:s}))},w=t=>{d&&(t.stopPropagation(),t.preventDefault(),d=!1)},y=()=>{var e=Ci(t,r,s);r=e.x,s=e.y,Mi(t,r,s)};return i.addEventListener("pointerdown",f),i.addEventListener("pointermove",g),i.addEventListener("pointerup",m),i.addEventListener("pointercancel",m),i.addEventListener("click",w,!0),window.addEventListener("resize",y),{destroy(){i.removeEventListener("pointerdown",f),i.removeEventListener("pointermove",g),i.removeEventListener("pointerup",m),i.removeEventListener("pointercancel",m),i.removeEventListener("click",w,!0),window.removeEventListener("resize",y)}}}var Ii="chat",Bi=/<!--vtilt:widget:([\s\S]*?)-->/g,ji="bottom-right",Pi={primaryColor:"#7B68EE",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',borderRadius:"16px"};class Ni{constructor(t,e){var n;void 0===e&&(e={}),this.nt=null,this.it=null,this.rt=null,this.st=null,this.ot=Pi,this.lt=null,this.ht=null,this.ct=null,this.dt=null,this.ut=null,this.vt="disconnected",this.ft=null,this.gt=null,this.wt=null,this.yt=[],this.bt=[],this.xt=[],this.kt=null,this.Et=!1,this.At=null,this.Tt=!1,this.St=new si,this._t=!1,this.Ct=null,this.Mt=null,this.Ot=null,this.It=!1,this.Bt=!1,this.jt=0,this.Pt=!1,this.Nt=!1,this.Dt=!1,this.Rt="",this.Ut="",this.zt=!1,this.Ht=0,this._instance=t,this.Lt=l({enabled:!0,position:ji,aiMode:!0,preload:!1},e,{theme:l({},Pi,e.theme)}),this.qt={isOpen:!1,isVisible:!1!==(null===(n=this.Lt.bubble)||void 0===n?void 0:n.visible),isConnected:!1,isLoading:!1,unreadCount:0,currentView:"list",channels:[],channel:null,messages:[],isTyping:!1,typingSender:null,typingSenderType:null,agentLastReadAt:null},this.St.register(oi),this.St.register(hi),this.Ft(),this.Vt(),this.Mt=this._instance._emitter.on("user:identified",()=>{this.Wt()}),this.Ot=this._instance._emitter.on("user:reset",()=>{this.Wt()}),this.getChannels(),this.Jt()}get isOpen(){return this.qt.isOpen}get isConnected(){return this.qt.isConnected}get isLoading(){return this.qt.isLoading}get unreadCount(){return this.qt.unreadCount}get channel(){return this.qt.channel}get channels(){return this.qt.channels}get currentView(){return this.qt.currentView}get $t(){return this.Lt.theme||Pi}get Kt(){return this._instance.getDistinctId()||""}Gt(t,e,n){var i,r=this._instance.getRemoteConfig(),s=null==r?void 0:r.chatTracking;if("user"===t.sender_type){if(!1===(null==s?void 0:s.trackUserMessages))return}else if(("ai"===t.sender_type||"agent"===t.sender_type)&&!1===(null==s?void 0:s.trackAgentMessages))return;this._instance.capture(b,{$channel_type:"chat",$conversation_id:e,$message_id:t.id,$direction:"user"===t.sender_type?"inbound":"outbound",$sender_type:t.sender_type,$content_preview:(null!==(i=t.content)&&void 0!==i?i:"").slice(0,100),$ai_mode:n})}open(){var t,e;this.qt.isOpen||(this.qt.isVisible=!0,this.qt.isOpen=!0,this.Qt(!0),this.Yt(),this.it&&(this.Xt(),this.it.classList.remove("vtilt-closing"),this.it.classList.add("vtilt-opening")),null===(e=(t=this.Lt).onWidgetOpen)||void 0===e||e.call(t),this.Jt(),0===this.qt.channels.length&&this.getChannels())}close(){var t,e,n;if(this.qt.isOpen){var i=this.Zt();this.qt.isOpen=!1,this._t||!1!==(null===(t=this.Lt.bubble)||void 0===t?void 0:t.visible)||(this.qt.isVisible=!1),this.Qt(!1),this.it&&(this.it.classList.remove("vtilt-opening"),this.it.classList.remove("vtilt-closing")),this.Yt();var r=this.qt.messages.filter(t=>"user"===t.sender_type).length;null===(n=(e=this.Lt).onWidgetClose)||void 0===n||n.call(e,{timeOpenSeconds:i,messagesSent:r}),this.te()}}toggle(){this.qt.isOpen?this.close():this.open()}show(){this._t=!0,this.qt.isVisible=!0,this.Yt()}hide(){this._t=!1,this.qt.isVisible=!1,this.Yt()}ee(t){return{id:t.id,project_id:"",person_id:"",distinct_id:this.Kt,status:t.status,ai_mode:t.ai_mode,unread_count:t.unread_count,last_message_at:t.last_message_at,last_message_preview:t.last_message_preview,last_message_sender:t.last_message_sender,user_last_read_at:t.user_last_read_at,agent_last_read_at:null,created_at:t.created_at}}Wt(){var t=this;return o(function*(){if(!t.It){var e=t.Kt;if(e&&e!==t.Ct){t.It=!0;try{yield t.ne(),t.qt.channels=[],t.qt.channel=null,t.qt.messages=[],t.qt.unreadCount=0,t.qt.currentView="list",t.qt.isTyping=!1,t.qt.typingSender=null,t.qt.typingSenderType=null,t.wt=null,t.gt=null,t.At=null,t.Bt=!1,t.jt=0,t.Yt(),yield t.getChannels(),yield t.Jt()}catch(t){bi().error(Ii,"failed to recreate Ably client after identity change:",t)}finally{t.It=!1}}}})()}getChannels(){var t=this;return o(function*(){t.qt.isLoading=!0,t.Yt();try{var e=yield Ti(t._instance,xi+"?distinct_id="+encodeURIComponent(t.Kt),{method:"GET"});e&&(t.qt.channels=e.channels||[],t.qt.unreadCount=t.qt.channels.reduce((t,e)=>t+(e.unread_count||0),0))}catch(t){bi().error(Ii,"failed to fetch channels:",t)}finally{t.qt.isLoading=!1,t.Yt()}})()}selectChannel(t){var e=this;return o(function*(){var n=e.qt.channels.find(e=>e.id===t);e.qt.channel=n?e.ee(n):null,e.qt.messages=[],e.qt.currentView="conversation",e.qt.isLoading=!0,e.qt.isTyping=!1,e.qt.typingSender=null,e.qt.typingSenderType=null,e.wt=t,e.Bt=!1,e.jt=0,e.Yt(),e.te();try{var i=yield Ti(e._instance,xi+"/"+t+"?distinct_id="+encodeURIComponent(e.Kt),{method:"GET"});if(!i||e.wt!==t)return;e.qt.channel=i.channel,e.qt.messages=i.messages||[],e.qt.agentLastReadAt=i.channel.agent_last_read_at||null,e.At=i.channel.user_last_read_at||null,e.qt.unreadCount=e.ie(),e.re(i.channel.id),e.qt.isOpen&&e.se()}catch(t){bi().error(Ii,"failed to select channel:",t)}finally{e.wt===t&&(e.wt=null),e.qt.isLoading=!1,e.Yt()}})()}createChannel(){var t=this;return o(function*(){var n,i,s;t.qt.channel=null,t.qt.messages=[],t.qt.currentView="conversation",t.qt.isLoading=!0,t.qt.isTyping=!1,t.qt.typingSender=null,t.qt.typingSenderType=null,t.Bt=!1,t.jt=0,t.Yt(),t.te();try{var a=yield Ti(t._instance,xi,{method:"POST",body:JSON.stringify({distinct_id:t.Kt,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})});if(!a)return;t.qt.channel=a.channel,t.qt.messages=a.messages||[],t.qt.agentLastReadAt=a.channel.agent_last_read_at||null,t.At=a.channel.user_last_read_at||null,t.qt.unreadCount=t.ie();var o={id:a.channel.id,status:a.channel.status,ai_mode:a.channel.ai_mode,last_message_at:a.channel.last_message_at,last_message_preview:a.channel.last_message_preview,last_message_sender:a.channel.last_message_sender,unread_count:t.qt.unreadCount,user_last_read_at:a.channel.user_last_read_at,created_at:a.channel.created_at};t.qt.channels.some(t=>t.id===a.channel.id)||t.qt.channels.unshift(o),null===(s=(i=t.Lt).onConversationStart)||void 0===s||s.call(i,{channelId:a.channel.id,aiMode:a.channel.ai_mode}),t.re(a.channel.id)}catch(t){bi().error(Ii,"failed to create channel:",t)}finally{t.wt=null,t.qt.isLoading=!1,t.Yt()}})()}goToChannelList(){var t=this;return o(function*(){if(t.qt.channel){var e=t.qt.channels.findIndex(e=>{var n;return e.id===(null===(n=t.qt.channel)||void 0===n?void 0:n.id)});-1!==e&&(t.qt.channels[e]=l({},t.qt.channels[e],{last_message_at:t.qt.messages.length>0?t.qt.messages[t.qt.messages.length-1].created_at:t.qt.channels[e].last_message_at,last_message_preview:t.qt.messages.length>0?t.ae(t.qt.messages[t.qt.messages.length-1]):t.qt.channels[e].last_message_preview,last_message_sender:t.qt.messages.length>0?t.qt.messages[t.qt.messages.length-1].sender_type:t.qt.channels[e].last_message_sender,unread_count:0}))}t.qt.channel=null,t.qt.messages=[],t.qt.currentView="list",t.qt.isTyping=!1,t.qt.typingSender=null,t.qt.typingSenderType=null,t.wt=null,t.gt=null,t.Bt=!1,t.jt=0,t.Yt(),t.te().then(()=>{t.ht&&!t.wt&&t.oe()})})()}sendMessage(t,e){var n=this;return o(function*(){var i,r,s,a,o,h,c=function(t,e){var n,i=function(t){return"string"==typeof t?{raw:t,format:"text"}:"markdown"in t?{raw:t.markdown,format:"markdown"}:"html"in t?{raw:t.html,format:"html"}:"text"in t?{raw:t.text,format:"text"}:null}(t);if(!i)return null;var r="string"==typeof t?null!==(n=null==e?void 0:e.format)&&void 0!==n?n:"text":i.format,s=i.raw.trim();return s?"html"===r?{content:s,content_type:"html",metadata:{}}:"markdown"===r?{content:s,content_type:"text",metadata:{[p]:f}}:{content:s,content_type:"text",metadata:{}}:null}(t,e);if(c){var{content:d,content_type:u,metadata:v}=c,g=!1!==(null==e?void 0:e.open),m=null==e?void 0:e.channel;if("new"===m?(n.qt.currentView="conversation",n.qt.channel=null,n.qt.messages=[],n.qt.isLoading=!0,g&&n.open(),yield n.createChannel()):(g&&n.open(),m&&(yield n.selectChannel(m))),n.qt.channel&&"conversation"===n.qt.currentView){var b=null===(i=n.qt.channel)||void 0===i?void 0:i.id;if(b){var x={id:"temp-"+Date.now(),channel_id:b,sender_type:"user",sender_id:n.Kt||null,sender_name:null,sender_avatar_url:null,content:d,content_type:u,metadata:v,created_at:(new Date).toISOString()};n.qt.messages.push(x),n.Yt();try{var k=n._instance.getConfig(),E=w(k,ki(b)),A=yield fetch(E,{method:"POST",headers:l({"Content-Type":"application/json"},y(k)),body:JSON.stringify({channel_id:b,distinct_id:n.Kt,content:d,content_type:u,metadata:v})});if(!A.ok)throw new Error("API error: "+A.status);if((A.headers.get("content-type")||"").includes("text/plain"))yield n.le(A,x,b);else{var T=yield A.json(),S=n.qt.messages.findIndex(t=>t.id===x.id);-1!==S&&(null==T?void 0:T.message)&&(n.qt.messages[S]=T.message),(null===(r=null==T?void 0:T.message)||void 0===r?void 0:r.id)&&(null===(a=(s=n.Lt).onMessageSent)||void 0===a||a.call(s,{channelId:b,messageId:T.message.id})),(null==T?void 0:T.message)&&n.Gt(T.message,b,null!==(h=null===(o=n.qt.channel)||void 0===o?void 0:o.ai_mode)&&void 0!==h&&h),n.Yt()}}catch(t){bi().error(Ii,"failed to send message:",t),n.qt.messages=n.qt.messages.filter(t=>t.id!==x.id),n.Yt()}}else bi().error(Ii,"no channel to send message to")}else bi().error(Ii,"cannot send message: not in conversation view")}else bi().warn(Ii,"sendMessage: message is empty")})()}markAsRead(){this.se()}he(t){var e=this;return o(function*(){try{var n=e._instance.getConfig(),i=w(n,ki(t)),r=yield fetch(i,{method:"POST",headers:l({"Content-Type":"application/json"},y(n)),body:JSON.stringify({channel_id:t,distinct_id:e.Kt,widget_action_trigger:!0})});if(!r.ok)return;if((r.headers.get("content-type")||"").includes("text/plain")){var s={id:"silent-"+Date.now(),channel_id:t,sender_type:"user",sender_id:e.Kt||null,sender_name:null,sender_avatar_url:null,content:"",content_type:"text",metadata:{},created_at:(new Date).toISOString()};yield e.le(r,s,t)}}catch(t){}})()}se(){var t;if(this.qt.channel&&!this.Tt){var e=this.qt.messages[this.qt.messages.length-1];if(e){var n=this.qt.messages.some(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&!this.ce(t.created_at)),i=this.qt.channels.find(t=>{var e;return t.id===(null===(e=this.qt.channel)||void 0===e?void 0:e.id)}),r=(null!==(t=null==i?void 0:i.unread_count)&&void 0!==t?t:0)>0;(n||r)&&(this.qt.unreadCount=0,this.Tt=!0,this.Yt(),Ti(this._instance,Ei(this.qt.channel.id),{method:"POST",body:JSON.stringify({channel_id:this.qt.channel.id,distinct_id:this.Kt,read_at:e.created_at})}).then(t=>{t&&(this.At=e.created_at,i&&(i.unread_count=0)),this.qt.unreadCount=this.qt.channels.reduce((t,e)=>t+(e.unread_count||0),0),this.Tt=!1,this.Yt()}).catch(()=>{this.Tt=!1,this.Yt()}))}}}ce(t){return!!this.At&&new Date(t)<=new Date(this.At)}ie(){return this.qt.channel&&this.At?this.qt.messages.filter(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&new Date(t.created_at)>new Date(this.At)).length:0}onMessage(t){return this.yt.push(t),()=>{var e=this.yt.indexOf(t);e>-1&&this.yt.splice(e,1)}}onTyping(t){return this.bt.push(t),()=>{var e=this.bt.indexOf(t);e>-1&&this.bt.splice(e,1)}}onConnectionChange(t){return this.xt.push(t),()=>{var e=this.xt.indexOf(t);e>-1&&this.xt.splice(e,1)}}destroy(){var t,e,n,i,r;this.ne(),this.kt&&clearTimeout(this.kt),this.Qt(!1),null===(t=this.st)||void 0===t||t.destroy(),this.st=null,null===(e=this.lt)||void 0===e||e.call(this),this.lt=null,null===(n=this.Mt)||void 0===n||n.call(this),this.Mt=null,null===(i=this.Ot)||void 0===i||i.call(this),this.Ot=null,(null===(r=this.nt)||void 0===r?void 0:r.parentNode)&&this.nt.parentNode.removeChild(this.nt),this.yt=[],this.bt=[],this.xt=[]}Jt(){var t=this;return o(function*(){var e;if(!t.ht){t.vt="connecting",t.de(!1);try{var n=yield Ti(t._instance,Ai,{method:"POST",body:JSON.stringify({distinct_id:t.Kt})});if(!(null==n?void 0:n.tokenRequest))return bi().warn(Ii,"failed to get Ably token"),void(t.vt="error");t.ft=n.project_id;var i=null!==(e=n.tokenRequest.clientId)&&void 0!==e?e:null;t.ht=new bn({plugins:{WebSocketTransport:Zn,FetchRequest:ni},authCallback:(s=o(function*(e,n){var i,r,s,a;try{var o=null!==(r=null!==(i=t.wt)&&void 0!==i?i:t.gt)&&void 0!==r?r:null===(s=t.qt.channel)||void 0===s?void 0:s.id,h=yield Ti(t._instance,Ai,{method:"POST",body:JSON.stringify(l({distinct_id:t.Kt},o&&{channel_id:o}))});if(!(null==h?void 0:h.tokenRequest))return void n("Failed to refresh token",null);var c=h.tokenRequest.clientId,d=null===(a=t.ht)||void 0===a?void 0:a.auth.clientId;if(d&&c&&c!==d)return n("clientId changed; recreating connection",null),void t.Wt();n(null,h.tokenRequest)}catch(t){n(String(t),null)}}),function(t,e){return s.apply(this,arguments)}),authMethod:"POST"}),yield t.ht.auth.authorize(n.tokenRequest),t.ht.connection.on("connected",()=>{t.vt="connected",t.qt.isConnected=!0,t.de(!0)}),t.ht.connection.on("disconnected",()=>{t.vt="disconnected",t.qt.isConnected=!1,t.de(!1)}),t.ht.connection.on("suspended",()=>{t.vt="disconnected",t.qt.isConnected=!1,t.de(!1)}),t.ht.connection.on("failed",()=>{t.vt="error",t.qt.isConnected=!1,t.de(!1)}),t.ht.connect();var r="chat:"+t.ft+":notifications";t.ct=t.ht.channels.get(r),t.ct.subscribe("notification",e=>{t.ue(e.data)}),t.Ct=(null==i?void 0:i.split(":").slice(1).join(":"))||t.Kt}catch(e){bi().error(Ii,"failed to connect to Ably:",e),t.vt="error"}var s}})()}oe(t){var e=this;return o(function*(){if(!e.ht)return!1;if("failed"===e.ht.connection.state)return bi().warn(Ii,"skipping authorize on failed connection"),e.Wt(),!1;try{var n=yield Ti(e._instance,Ai,{method:"POST",body:JSON.stringify(l({distinct_id:e.Kt},t&&{channel_id:t}))});if(!(null==n?void 0:n.tokenRequest))return bi().warn(Ii,"failed to refresh Ably token",null!=t?t:"(list)"),!1;var i=n.tokenRequest.clientId,r=e.ht.auth.clientId;return r&&i&&i!==r?(bi().warn(Ii,"Ably token clientId mismatch; recreating connection"),e.Wt(),!1):(yield e.ht.auth.authorize(n.tokenRequest),e.gt=null!=t?t:null,!0)}catch(t){return bi().error(Ii,"failed to refresh Ably token:",t),!1}})()}re(t){var e=this;return o(function*(){if(yield e.Jt(),e.ht&&e.ft)if(yield e.oe(t)){var n="chat:"+e.ft+":"+t,i=e.ht.channels.get(n),r=e.ht.channels.get(n+":typing");e.dt=i,e.ut=r;var s=()=>e.dt!==i||e.ut!==r;try{if(yield i.attach(),s())return;if(i.subscribe("message",t=>{e.ve(t.data)}),i.subscribe("read",t=>{e.pe(t.data)}),yield r.attach(),s())return;r.subscribe("typing",t=>{e.fe(t.data)})}catch(t){if(s())return void bi().debug(Ii,"channel attach superseded by concurrent disconnect");bi().error(Ii,"failed to attach chat/typing channels:",t),yield e.te(),e.gt=null}}else bi().warn(Ii,"skipping channel subscribe — no Ably capability for",t)})()}te(){var t=this;return o(function*(){var e=t.ht,n=t.dt,i=t.ut;t.dt=null,t.ut=null,t.gt=null;var r=function(){var t=o(function*(t){if(t&&e){var n=t.name;t.unsubscribe();try{yield t.detach()}catch(t){}e.channels.release(n)}});return function(e){return t.apply(this,arguments)}}();yield Promise.all([r(n),r(i)])})()}ne(){var t=this;return o(function*(){yield t.te(),t.ct&&(t.ct.unsubscribe(),t.ct=null),t.ht&&(t.ht.close(),t.ht=null),t.ft=null,t.vt="disconnected",t.qt.isConnected=!1,t.Ct=null})()}ue(t){var e,n,i,{type:r,channel_id:s,data:a}=t;if("new_channel"!==r){if("channel_updated"===r&&a){var o=this.qt.channels.findIndex(t=>t.id===s);if(-1!==o){var h=l({},this.qt.channels[o]);if(void 0!==a.last_message_at&&(h.last_message_at=a.last_message_at),void 0!==a.last_message_preview&&(h.last_message_preview=a.last_message_preview),void 0!==a.last_message_sender&&(h.last_message_sender=a.last_message_sender),void 0!==a.user_unread_count)this.qt.isOpen&&(null===(e=this.qt.channel)||void 0===e?void 0:e.id)===s||(h.unread_count=a.user_unread_count);void 0!==a.status&&(h.status=a.status),void 0!==a.ai_mode&&(h.ai_mode=a.ai_mode),this.qt.channels[o]=h,this.qt.channels.sort((t,e)=>{var n=t.last_message_at||t.created_at,i=e.last_message_at||e.created_at;return new Date(i).getTime()-new Date(n).getTime()}),this.qt.unreadCount=this.qt.channels.reduce((t,e)=>t+(e.unread_count||0),0)}(null===(n=this.qt.channel)||void 0===n?void 0:n.id)===s&&"closed"===a.status&&(this.qt.channel=l({},this.qt.channel,{status:"closed"})),this.Yt()}if("channel_closed"===r){var c=this.qt.channels.findIndex(t=>t.id===s);-1!==c&&(this.qt.channels[c]=l({},this.qt.channels[c],{status:"closed"})),(null===(i=this.qt.channel)||void 0===i?void 0:i.id)===s&&(this.qt.channel=l({},this.qt.channel,{status:"closed"})),this.Yt()}}else this.getChannels()}ve(t){var e,n,i,r,s,a;if("ai"===t.sender_type){var o=this.qt.messages.findIndex(t=>t.id.startsWith("temp-ai-"));if(-1!==o){var l=null!==(e=this.qt.messages[o].metadata)&&void 0!==e?e:{};this.qt.messages[o]=t,!(null!==(n=this.qt.messages[o].metadata)&&void 0!==n?n:{}).widgets&&l.et&&(this.qt.messages[o].metadata.et=l.et)}else{if(this.qt.messages.some(e=>e.id===t.id))return;this.qt.messages.push(t)}}else{if(this.qt.messages.some(e=>e.id===t.id))return;if("user"===t.sender_type&&t.sender_id===this.Kt){var h=this.qt.messages.findIndex(e=>e.id.startsWith("temp-")&&e.content===t.content&&e.content_type===t.content_type&&"user"===e.sender_type);return void(-1!==h&&(this.qt.messages[h]=t,this.Yt()))}this.qt.messages.push(t)}if("ai"===t.sender_type||"agent"===t.sender_type){if(this.qt.isOpen)setTimeout(()=>this.se(),100);else{this.qt.unreadCount++;var c=this.qt.channels.find(e=>e.id===t.channel_id);c&&(c.unread_count=(c.unread_count||0)+1)}null===(r=(i=this.Lt).onMessageReceived)||void 0===r||r.call(i,{channelId:t.channel_id,messageId:t.id,senderType:t.sender_type}),this.Gt(t,t.channel_id,null!==(a=null===(s=this.qt.channel)||void 0===s?void 0:s.ai_mode)&&void 0!==a&&a)}this.qt.isTyping=!1,this.qt.typingSender=null,this.qt.typingSenderType=null,this.yt.forEach(e=>e(t)),this.Yt()}fe(t){if("user"!==t.sender_type){this.qt.isTyping=t.is_typing,this.qt.typingSenderType=t.is_typing?t.sender_type:null;var e="ai"===t.sender_type?null:t.sender_name||("agent"===t.sender_type?"Agent":null);this.qt.typingSender=t.is_typing?e:null,this.bt.forEach(n=>n(t.is_typing,e||"")),this.Yt()}}pe(t){"agent"===t.reader_type&&(this.qt.agentLastReadAt=t.read_at,this.Yt())}de(t){this.xt.forEach(e=>e(t))}Ft(){var t,n,i,s;if(r){var a=this.$t;this.ot={primaryColor:null!==(t=a.primaryColor)&&void 0!==t?t:Pi.primaryColor,fontFamily:null!==(n=a.fontFamily)&&void 0!==n?n:Pi.fontFamily,borderRadius:null!==(i=a.borderRadius)&&void 0!==i?i:Pi.borderRadius};var o,l,h=this.Lt.position||ji;this.nt=r.createElement("div"),this.nt.id="vtilt-chat-container",this.nt.setAttribute("style",function(t,e){return void 0===e&&(e="bottom-right"),"\n position: fixed;\n bottom: 20px;\n "+("bottom-right"===e?"right: 20px;":"left: 20px;")+"\n z-index: 999999;\n font-family: "+t.fontFamily+";\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n "}(this.ot,h)),this.Rt=this.nt.getAttribute("style")||"",this.rt=r.createElement("div"),this.rt.id="vtilt-chat-bubble",this.rt.innerHTML='\n <svg width="28" height="28" viewBox="0 0 28 28" fill="white">\n <path d="M14 3C7.925 3 3 7.262 3 12.5c0 2.56 1.166 4.884 3.063 6.606L4.5 24l5.25-2.625C11.1 21.79 12.52 22 14 22c6.075 0 11-4.262 11-9.5S20.075 3 14 3z"/>\n </svg>\n <div class="vtilt-chat-badge" style="\n display: none;\n position: absolute;\n top: -4px;\n right: -4px;\n background: #E53935;\n color: white;\n font-size: 11px;\n font-weight: 700;\n min-width: 20px;\n height: 20px;\n border-radius: 10px;\n align-items: center;\n justify-content: center;\n padding: 0 6px;\n box-sizing: border-box;\n border: 2px solid white;\n ">0</div>\n ',this.rt.setAttribute("style",(o=this.ot,"\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: "+(l=o.primaryColor)+";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 16px "+l+"66;\n transition: transform 0.2s ease, box-shadow 0.2s ease;\n position: relative;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n ")),this.nt.appendChild(this.rt),this.it=r.createElement("div"),this.it.id="vtilt-chat-widget",this.it.innerHTML=function(t){var e=t.primaryColor;return'\n <div class="vtilt-chat-header" style="\n background: #ffffff;\n border-bottom: 1px solid #E5E5E5;\n padding: 18px 16px;\n padding-top: max(18px, env(safe-area-inset-top, 18px));\n display: flex;\n align-items: center;\n justify-content: space-between;\n min-height: 60px;\n box-sizing: border-box;\n flex-shrink: 0;\n ">\n <div style="font-weight: 600; font-size: 17px; color: #000000;">Messages</div>\n <button class="vtilt-chat-close" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n </div>\n \n <div class="vtilt-chat-content" style="\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n min-height: 0;\n background: #ffffff;\n ">\n </div>\n \n <style>\n @keyframes vtilt-open {\n from { opacity: 0; transform: scale(0.4); }\n to { opacity: 1; transform: scale(1); }\n }\n \n #vtilt-chat-bubble { transition: transform 0.15s ease, box-shadow 0.15s ease; }\n #vtilt-chat-bubble:hover { transform: scale(1.05); box-shadow: 0 6px 20px '+e+"73; }\n #vtilt-chat-bubble:active { transform: scale(0.95); }\n .vtilt-draggable #vtilt-chat-bubble:hover,\n .vtilt-draggable #vtilt-chat-bubble:active { transform: none; }\n \n /* transform-origin is set in JS by _constrainWidgetToViewport() to match widget position */\n #vtilt-chat-widget.vtilt-opening { animation: vtilt-open 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards; }\n \n .vtilt-chat-content { transition: opacity 0.15s ease; }\n \n .vtilt-chat-close:hover { color: #000 !important; background: #F0F0F0 !important; }\n .vtilt-chat-back:hover { color: #000 !important; background: #F0F0F0 !important; }\n \n .vtilt-chat-input-container > div:first-child:focus-within { \n border-color: "+e+" !important; \n box-shadow: 0 0 0 2px "+e+"20 !important; \n }\n .vtilt-chat-input { \n -webkit-text-size-adjust: 100%; \n }\n .vtilt-chat-input:focus { \n outline: none !important; \n }\n .vtilt-chat-input::placeholder { \n color: #999999; \n }\n .vtilt-input-pending > div:first-child {\n background: #FAFAFA !important;\n border-color: #EEEEEE !important;\n }\n .vtilt-input-pending .vtilt-chat-input {\n background: transparent !important;\n color: #BBBBBB !important;\n cursor: not-allowed !important;\n }\n .vtilt-input-pending .vtilt-chat-input::placeholder {\n color: #BBBBBB !important;\n }\n .vtilt-input-pending .vtilt-chat-attach,\n .vtilt-input-pending .vtilt-chat-mic {\n color: #CCCCCC !important;\n cursor: not-allowed !important;\n }\n .vtilt-chat-input::-webkit-scrollbar { \n width: 4px; \n }\n .vtilt-chat-input::-webkit-scrollbar-track { \n background: transparent; \n }\n .vtilt-chat-input::-webkit-scrollbar-thumb { \n background: rgba(0, 0, 0, 0.2); \n border-radius: 2px; \n }\n .vtilt-chat-input::-webkit-scrollbar-thumb:hover { \n background: rgba(0, 0, 0, 0.3); \n }\n /* Firefox scrollbar */\n .vtilt-chat-input { \n scrollbar-width: thin; \n scrollbar-color: rgba(0, 0, 0, 0.2) transparent; \n }\n .vtilt-chat-attach:hover,\n .vtilt-chat-emoji:hover,\n .vtilt-chat-gif:hover,\n .vtilt-chat-mic:hover {\n color: #333333 !important;\n }\n .vtilt-chat-attach:active,\n .vtilt-chat-emoji:active,\n .vtilt-chat-gif:active,\n .vtilt-chat-mic:active {\n color: #000000 !important;\n }\n .vtilt-chat-send:not(:disabled):hover {\n opacity: 0.9 !important;\n transform: scale(1.05);\n }\n .vtilt-chat-send:not(:disabled):active {\n opacity: 0.8 !important;\n transform: scale(0.95);\n }\n .vtilt-chat-send:disabled {\n cursor: not-allowed !important;\n }\n \n .vtilt-chat-send { transition: opacity 0.1s ease; }\n\n "+di+'\n \n /* Widget styles */\n .vtilt-widget { margin-top: 10px; }\n .vtilt-widget-input { font-family: inherit; }\n .vtilt-widget-input:focus { outline: none; border-color: #999; }\n \n .vtilt-chat-new-channel { transition: opacity 0.1s ease; }\n .vtilt-chat-new-channel:hover { opacity: 0.9; }\n .vtilt-chat-new-channel:active { opacity: 0.8; }\n \n .vtilt-channel-item { transition: background 0.1s ease; cursor: pointer; }\n .vtilt-channel-item:hover { background: #F5F5F5 !important; }\n .vtilt-channel-item:active { background: #EBEBEB !important; }\n\n /* Skeleton placeholders for first-load. Lives inline in the content\n area so the header stays interactive while the list / messages\n load. Calm opacity-pulse animation (the modern minimal pattern\n used by Linear / Vercel / Stripe / modern Intercom) — solid\n neutral fill that breathes instead of a fast sliding gradient,\n which felt restless against the widget\'s clean white palette. */\n @keyframes vtilt-skeleton-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.55; }\n }\n .vtilt-skeleton {\n background: #E8E8EA;\n border-radius: 6px;\n animation: vtilt-skeleton-pulse 2.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n }\n .vtilt-skeleton-circle {\n background: #E8E8EA;\n border-radius: 50%;\n animation: vtilt-skeleton-pulse 2.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n }\n\n /* Subtle fade-in for newly appended messages. */\n @keyframes vtilt-message-in {\n from { opacity: 0; transform: translateY(4px); }\n to { opacity: 1; transform: translateY(0); }\n }\n .vtilt-msg-enter {\n animation: vtilt-message-in 0.22s ease-out both;\n }\n\n /* "New messages" pill anchored above the input when the user has\n scrolled up while new agent/AI messages arrive. */\n .vtilt-new-messages-pill {\n position: absolute;\n left: 50%;\n transform: translateX(-50%);\n bottom: 12px;\n background: '+e+";\n color: white;\n padding: 6px 14px;\n border-radius: 999px;\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n box-shadow: 0 2px 8px rgba(0,0,0,0.15);\n display: none;\n align-items: center;\n gap: 6px;\n z-index: 5;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n transition: opacity 0.15s ease;\n }\n .vtilt-new-messages-pill:hover { opacity: 0.92; }\n .vtilt-new-messages-pill:active { opacity: 0.85; }\n\n @keyframes vtilt-slide-up {\n from { opacity: 0; transform: translateY(100%); }\n to { opacity: 1; transform: translateY(0); }\n }\n\n @media (max-width: 480px) {\n #vtilt-chat-bubble { width: 56px !important; height: 56px !important; }\n #vtilt-chat-bubble svg { width: 24px !important; height: 24px !important; }\n #vtilt-chat-widget.vtilt-opening {\n animation: vtilt-slide-up 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards !important;\n transform-origin: bottom center !important;\n }\n }\n \n @media (prefers-reduced-motion: reduce) {\n * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }\n }\n </style>\n "}(this.ot),this.it.setAttribute("style","\n display: none;\n flex-direction: column;\n position: absolute;\n bottom: 0;\n right: 0;\n width: 380px;\n max-width: calc(100vw - 40px);\n height: 600px;\n max-height: calc(100vh - 40px);\n max-height: calc(100dvh - 40px);\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 5px 40px rgba(0, 0, 0, 0.16);\n overflow: hidden;\n "),this.nt.appendChild(this.it),r.body.appendChild(this.nt),(null===(s=this.Lt.bubble)||void 0===s?void 0:s.draggable)&&this.nt&&this.rt&&(this.nt.classList.add("vtilt-draggable"),this.st=Oi(this.nt,{handle:this.rt}));var c=()=>{this.qt.isOpen&&(this.ge()?(this.me(),this.Qt(!0)):(this.we(),this.Qt(!1),this.Xt()),this.nt&&this.it&&this.rt&&(this.nt.style.display=this.qt.isVisible?"block":"none",this.it.style.display=this.qt.isOpen?"flex":"none",this.rt.style.display=this.qt.isOpen?"none":"flex"))},d=e;d&&(d.addEventListener("resize",c),this.lt=()=>d.removeEventListener("resize",c))}}Vt(){var t,e,n,i,r;null===(t=this.rt)||void 0===t||t.addEventListener("click",()=>this.toggle()),null===(n=null===(e=this.it)||void 0===e?void 0:e.querySelector(".vtilt-chat-close"))||void 0===n||n.addEventListener("click",()=>this.close()),null===(i=this.it)||void 0===i||i.addEventListener("click",t=>{var e,n,i,r=null===(n=null===(e=t.target)||void 0===e?void 0:e.closest)||void 0===n?void 0:n.call(e,"[data-vtilt-widget-action]");if(r){var s=r.getAttribute("data-vtilt-widget-type"),a=r.getAttribute("data-vtilt-widget-action");if(s&&a){var o=r;if(!o.disabled){t.preventDefault(),t.stopPropagation();var l=this.St.get(s);if(l){var h=r.closest(".vtilt-widget"),c={};h&&h.querySelectorAll("[data-vtilt-widget-field]").forEach(t=>{var e=t.getAttribute("data-vtilt-widget-field");e&&(c[e]=t.value)});var d=this.ye(),u=null==h?void 0:h.closest("[data-vtilt-msg-id]");d.messageId=null!==(i=null==u?void 0:u.getAttribute("data-vtilt-msg-id"))&&void 0!==i?i:"",o.disabled=!0,o.style.opacity="0.6",l.onAction(a,c,d).then(t=>{t.success?(this.be(d.messageId,s,c),this.Yt(),"escalate_to_human"!==s&&this.he(d.channelId)):this.Yt()}).catch(()=>{this.Yt()})}}}}}),null===(r=this.it)||void 0===r||r.addEventListener("keydown",t=>{var e=t;if("Enter"===e.key){var n=e.target;if("email"===(null==n?void 0:n.type)){t.preventDefault();var i=n.closest(".vtilt-widget"),r=null==i?void 0:i.querySelector("[data-vtilt-widget-action]");null==r||r.click()}}})}be(t,e,n){var i,r,s;if(t){var a=this.qt.messages.find(e=>e.id===t);if(a){var o=null!==(i=a.metadata)&&void 0!==i?i:{},h=(null!==(s=null!==(r=o.et)&&void 0!==r?r:o.widgets)&&void 0!==s?s:[]).map(t=>{if(t.type!==e)return t;var i=l({},t,{submitted:!0});return n.email&&(i.submittedEmail=String(n.email).trim()),n.name&&(i.submittedName=String(n.name).trim()),i});a.metadata.widgets=h,o.et&&(a.metadata.et=h)}}}xe(){this.ut&&(this.Et||(this.Et=!0,this.ke(!0)),this.kt&&clearTimeout(this.kt),this.kt=setTimeout(()=>{this.Et=!1,this.ke(!1)},2e3))}ke(t){this.ut&&this.ut.publish("typing",{sender_type:"user",sender_id:this.Kt,sender_name:null,is_typing:t}).catch(t=>{bi().warn(Ii,"failed to publish typing indicator:",t)})}Ee(){var t,e,n=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-input");if(n){var i=n.value.trim();if(i){this.Et&&(this.Et=!1,this.ke(!1)),this.kt&&(clearTimeout(this.kt),this.kt=null),this.sendMessage(i),n.value="",n.style.height="auto",n.style.height="60px",n.focus();var r=null===(e=this.it)||void 0===e?void 0:e.querySelector(".vtilt-chat-send");r&&(r.disabled=!0,r.style.background="#E5E5E5",r.style.color="#999999",r.style.cursor="not-allowed",r.style.opacity="0.6")}}}Yt(){var t;if(this.nt&&this.it&&this.rt){this.qt.isOpen&&this.ge()?this.me():(this.we(),this.qt.isOpen&&(this.nt.style.minWidth="60px",this.nt.style.minHeight="60px",requestAnimationFrame(()=>this.Xt()))),this.nt.style.display=this.qt.isVisible?"block":"none",this.it.style.display=this.qt.isOpen?"flex":"none",this.rt.style.display=this.qt.isOpen?"none":"flex",this.qt.isOpen||(this.nt.style.minWidth="",this.nt.style.minHeight="");var e=this.rt.querySelector(".vtilt-chat-badge");e&&(e.style.display=this.qt.unreadCount>0?"flex":"none",e.textContent=String(this.qt.unreadCount));var n=this.it.querySelector(".vtilt-chat-content");if(n)if("list"===this.qt.currentView)n.querySelector(".vtilt-chat-input")&&(this.Pt=!1),this.Ae(n);else n.querySelector(".vtilt-chat-input")||(n.innerHTML=this.Te(),this.Pt=!1,this.Se()),this._e();this.Ce();var i=this.it.querySelector(".vtilt-chat-typing");if(i){i.style.display=this.qt.isTyping&&"conversation"===this.qt.currentView?"flex":"none";var s=i.querySelector(".vtilt-chat-typing-text");s&&this.qt.isTyping&&("ai"===this.qt.typingSenderType?s.textContent="AI is thinking...":this.qt.typingSender?s.textContent=this.qt.typingSender+" is typing...":s.textContent="Agent is typing...")}var a="conversation"===this.qt.currentView&&"closed"===(null===(t=this.qt.channel)||void 0===t?void 0:t.status),o=this.it.querySelector(".vtilt-chat-input-container"),l=this.it.querySelector(".vtilt-chat-closed-banner");if(a){if(o&&(o.style.display="none"),!l&&r){var h=r.createElement("div");h.className="vtilt-chat-closed-banner",h.style.cssText="padding: 12px 16px; padding-bottom: max(12px, env(safe-area-inset-bottom, 12px)); border-top: 1px solid #E5E5E5; text-align: center; background: #FAFAFA; flex-shrink: 0;",h.innerHTML='<span style="font-size: 14px; color: #888;">This conversation has been closed.</span>';var c=this.it.querySelector(".vtilt-chat-content");(null==c?void 0:c.parentNode)&&c.parentNode.appendChild(h)}}else o&&"conversation"===this.qt.currentView&&"none"===o.style.display&&(o.style.display=""),l&&l.remove();if("conversation"===this.qt.currentView)if(o&&!a){var d=null==this.qt.channel;o.classList.toggle("vtilt-input-pending",d);var u=o.querySelector(".vtilt-chat-input");u&&(u.disabled=d,d?u.placeholder="Starting conversation…":"Starting conversation…"===u.placeholder&&(u.placeholder="Message...")),o.querySelectorAll(".vtilt-chat-attach, .vtilt-chat-mic").forEach(t=>{t.disabled=d})}}}ge(){return!!e&&e.innerWidth<=480}me(){this.nt&&this.it&&(this.zt||(this.Ut=this.nt.style.transform),this.nt.setAttribute("style","\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n font-family: "+this.ot.fontFamily+";\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n transform: none;\n "),this.it.setAttribute("style","\n flex-direction: column;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n background: #ffffff;\n border-radius: 0;\n box-shadow: none;\n overflow: hidden;\n "),this.zt=!0)}we(){this.zt&&this.nt&&this.it&&(this.nt.setAttribute("style",this.Rt),this.Ut&&(this.nt.style.transform=this.Ut),this.it.setAttribute("style","\n display: none;\n flex-direction: column;\n position: absolute;\n bottom: 0;\n right: 0;\n width: 380px;\n max-width: calc(100vw - 40px);\n height: 600px;\n max-height: calc(100vh - 40px);\n max-height: calc(100dvh - 40px);\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 5px 40px rgba(0, 0, 0, 0.16);\n overflow: hidden;\n "),this.zt=!1)}Qt(t){var n;if(this.ge()&&r){var i=r.documentElement;t?(this.Ht=null!==(n=null==e?void 0:e.scrollY)&&void 0!==n?n:0,i.style.setProperty("overflow","hidden","important"),r.body.style.setProperty("overflow","hidden","important"),r.body.style.setProperty("position","fixed","important"),r.body.style.setProperty("width","100%","important"),r.body.style.top="-"+this.Ht+"px"):(i.style.removeProperty("overflow"),r.body.style.removeProperty("overflow"),r.body.style.removeProperty("position"),r.body.style.removeProperty("width"),r.body.style.top="",null==e||e.scrollTo(0,this.Ht))}}Xt(){if(this.nt&&this.it&&this.qt.isOpen&&e&&!this.ge()){var t=this.nt.getBoundingClientRect(),n="0",i="auto",r="0",s="auto",a=t.width-380,o=t.height-600,l=t.right-380,h=t.bottom-600;l<20&&(s=(a=20-t.left)+"px",r="auto"),h<20&&(i=(o=20-t.top)+"px",n="auto"),this.it.style.left=s,this.it.style.right=r,this.it.style.top=i,this.it.style.bottom=n;var c=t.width-a,d=t.height-o;this.it.style.transformOrigin=c+"px "+d+"px",this.it.style.maxWidth="",this.it.style.maxHeight=""}}Ce(){var t,e,n,i,r=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-header");if(r){var s=this.$t.primaryColor;if("list"===this.qt.currentView)r.style.cssText="\n background: #ffffff;\n border-bottom: 1px solid #E5E5E5;\n padding: 18px 16px;\n padding-top: max(18px, env(safe-area-inset-top, 18px));\n display: flex;\n align-items: center;\n justify-content: space-between;\n min-height: 60px;\n box-sizing: border-box;\n flex-shrink: 0;\n ",r.innerHTML='\n <div style="font-weight: 600; font-size: 17px; color: #000000;">Messages</div>\n <button class="vtilt-chat-close" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n ';else{var a=null===(i=null!==(n=null===(e=this.qt.channel)||void 0===e?void 0:e.ai_mode)&&void 0!==n?n:this.Lt.aiMode)||void 0===i||i;r.style.cssText="\n background: #ffffff;\n border-bottom: 1px solid #E5E5E5;\n padding: 12px 16px;\n padding-top: max(12px, env(safe-area-inset-top, 12px));\n display: flex;\n align-items: center;\n gap: 12px;\n min-height: 60px;\n box-sizing: border-box;\n flex-shrink: 0;\n ",r.innerHTML='\n <button class="vtilt-chat-back" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin-left: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M15 18l-6-6 6-6"></path>\n </svg>\n </button>\n <div style="\n width: 44px;\n height: 44px;\n border-radius: 50%;\n background: '+(a?s:"#DEDEDE")+';\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n ">\n '+(a?'<svg width="22" height="22" viewBox="0 0 24 24" fill="white"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"/></svg>':'<svg width="22" height="22" viewBox="0 0 24 24" fill="#666"><path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"/></svg>')+'\n </div>\n <div style="flex: 1; min-width: 0;">\n <div style="font-weight: 600; font-size: 16px; color: #000000;">'+(a?"AI Assistant":"Support")+'</div>\n <div style="font-size: 13px; color: #16A34A; display: flex; align-items: center; gap: 5px; margin-top: 1px;">\n <span style="width: 7px; height: 7px; background: #16A34A; border-radius: 50%;"></span>\n Online\n </div>\n </div>\n <button class="vtilt-chat-close" style="\n background: transparent;\n border: none;\n color: #666666;\n cursor: pointer;\n padding: 6px;\n margin-right: -6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n ">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n '}var o=r.querySelector(".vtilt-chat-close");null==o||o.addEventListener("click",()=>this.close());var l=r.querySelector(".vtilt-chat-back");null==l||l.addEventListener("click",()=>this.goToChannelList())}}Ae(t){var e,n=this.qt.channels,i=this.qt.isLoading;e=n.length>0?"populated":i?"skeleton":"empty";var r=t.dataset.listMode;if("populated"!==e)return r!==e&&(t.innerHTML="empty"===e?this.Me():this.Oe(),t.dataset.listMode=e),void this.Ie(t);var s=t.querySelector(".vtilt-chat-list-items");if(s&&"populated"===r||(t.innerHTML=this.Be(),t.dataset.listMode="populated",s=t.querySelector(".vtilt-chat-list-items")),s){this.Ie(t);var a=new Map;Array.from(s.children).forEach(t=>{var e=t,n=e.dataset.channelId;n&&a.set(n,e)});var o=null;for(var l of n){var h=a.get(l.id);h?(this.je(h,l),a.delete(l.id)):h=this.Pe(l);var c=o?o.nextElementSibling:s.firstElementChild;c!==h&&s.insertBefore(h,c),o=h}a.forEach(t=>t.remove())}}Ie(t){this.Dt||(t.addEventListener("click",t=>{var e=t.target;if(e)if(e.closest(".vtilt-chat-new-channel"))this.createChannel();else{var n=e.closest("[data-channel-id]");if(n){var i=n.dataset.channelId;i&&this.selectChannel(i)}}}),this.Dt=!0)}Pe(t){var e=null==r?void 0:r.createElement("div");if(!e)return null;e.innerHTML=this.Ne(t).trim();var n=e.firstElementChild;return n.dataset.fingerprint=this.De(t),n}je(t,e){var n=this.De(e);if(t.dataset.fingerprint!==n){var i=this.Pe(e);t.replaceWith(i)}}De(t){var e,n,i;return[t.status,t.ai_mode?1:0,null!==(e=t.last_message_at)&&void 0!==e?e:"",null!==(n=t.last_message_preview)&&void 0!==n?n:"",null!==(i=t.last_message_sender)&&void 0!==i?i:"",t.unread_count].join("|")}Me(){var t=this.$t.primaryColor,e=this.Lt.greeting||"Hi! How can we help you today?";return'\n <div style="\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 48px 24px;\n text-align: center;\n ">\n <div style="\n width: 72px;\n height: 72px;\n margin-bottom: 24px;\n background: '+t+';\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n ">\n <svg width="36" height="36" viewBox="0 0 24 24" fill="white">\n <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n </svg>\n </div>\n <div style="font-size: 18px; font-weight: 600; color: #000000; margin-bottom: 12px; line-height: 1.4; max-width: 280px;">'+this.Re(e)+'</div>\n <div style="font-size: 14px; color: #666666; margin-bottom: 28px;">Start a conversation with us</div>\n <button class="vtilt-chat-new-channel" style="\n background: '+t+";\n color: white;\n border: none;\n border-radius: 100px;\n padding: 14px 28px;\n cursor: pointer;\n font-weight: 500;\n font-size: 15px;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n display: flex;\n align-items: center;\n gap: 10px;\n box-shadow: 0 2px 8px "+t+'4D;\n ">\n Send us a message\n <svg width="18" height="18" viewBox="0 0 24 24" fill="white">\n <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>\n </svg>\n </button>\n </div>\n '}Be(){var t=this.$t.primaryColor;return'\n <div class="vtilt-chat-list-root" style="flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch;">\n <div class="vtilt-chat-list-items"></div>\n </div>\n <div style="\n padding: 16px;\n padding-bottom: max(16px, env(safe-area-inset-bottom, 16px));\n border-top: 1px solid #E5E5E5;\n ">\n <button class="vtilt-chat-new-channel" style="\n width: 100%;\n background: '+t+";\n color: white;\n border: none;\n border-radius: 100px;\n padding: 14px 24px;\n cursor: pointer;\n font-weight: 500;\n font-size: 15px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n box-shadow: 0 2px 8px "+t+'4D;\n ">\n Send us a message\n <svg width="18" height="18" viewBox="0 0 24 24" fill="white">\n <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>\n </svg>\n </button>\n </div>\n '}Oe(){var t='\n <div style="\n padding: 14px 16px;\n display: flex;\n align-items: center;\n gap: 12px;\n border-bottom: 1px solid #EEEEEE;\n background: white;\n ">\n <div class="vtilt-skeleton-circle" style="width: 48px; height: 48px; flex-shrink: 0;"></div>\n <div style="flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px;">\n <div class="vtilt-skeleton" style="height: 12px; width: 40%;"></div>\n <div class="vtilt-skeleton" style="height: 10px; width: 80%;"></div>\n </div>\n </div>\n ';return'\n <div style="flex: 1; overflow: hidden;">\n '+t+t+t+t+"\n </div>\n "}Ue(t,e,n,i){return void 0===i&&(i=40),"in"===t?'\n <div style="display: flex; gap: 10px; align-items: flex-end;">\n <div class="vtilt-skeleton-circle" style="width: 32px; height: 32px; flex-shrink: 0;"></div>\n <div style="display: flex; flex-direction: column; align-items: flex-start; min-width: 0; max-width: 85%;">\n <div class="vtilt-skeleton" style="\n width: '+e+"%;\n min-width: 96px;\n height: "+i+'px;\n border-radius: 20px 20px 20px 4px;\n "></div>\n <div class="vtilt-skeleton" style="\n height: 10px;\n width: '+n+'px;\n margin-top: 8px;\n margin-left: 6px;\n border-radius: 4px;\n "></div>\n </div>\n </div>\n ':'\n <div style="display: flex; flex-direction: column; align-items: flex-end;">\n <div class="vtilt-skeleton" style="\n width: '+e+"%;\n min-width: 80px;\n max-width: 80%;\n height: "+i+'px;\n border-radius: 20px 20px 4px 20px;\n "></div>\n <div class="vtilt-skeleton" style="\n height: 10px;\n width: '+n+'px;\n margin-top: 8px;\n margin-right: 6px;\n border-radius: 4px;\n "></div>\n </div>\n '}ze(){return"\n "+this.Ue("in",62,92,40)+"\n "+this.Ue("out",42,56,40)+"\n "+this.Ue("in",78,76,60)+"\n "}He(){var t,e=null===(t=this.Lt.aiMode)||void 0===t||t,n=this.$t.primaryColor;return'\n <div style="display: flex; gap: 10px; align-items: flex-end;">\n <div style="\n width: 32px;\n height: 32px;\n border-radius: 50%;\n background: '+(e?n:"#DEDEDE")+';\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n ">'+(e?'<svg width="16" height="16" viewBox="0 0 24 24" fill="white"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"/></svg>':'<svg width="16" height="16" viewBox="0 0 24 24" fill="#666"><path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"/></svg>')+'</div>\n <div style="display: flex; flex-direction: column; align-items: flex-start; min-width: 0;">\n <div style="\n padding: 12px 16px;\n background: #ffffff;\n border-radius: 20px 20px 20px 4px;\n display: inline-flex;\n align-items: center;\n gap: 5px;\n ">\n <span style="width: 6px; height: 6px; background: #B5B5B5; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0s;"></span>\n <span style="width: 6px; height: 6px; background: #B5B5B5; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0.2s;"></span>\n <span style="width: 6px; height: 6px; background: #B5B5B5; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0.4s;"></span>\n </div>\n <div style="font-size: 12px; color: #888888; margin-top: 6px; margin-left: 4px;">\n '+(e?"AI Assistant":"Support")+"\n </div>\n </div>\n </div>\n "}Ne(t){var e=t.unread_count>0,n=this.Le(t.last_message_at||t.created_at),i=t.last_message_preview||"No messages yet",r=this.$t.primaryColor,s="user"===t.last_message_sender?"You: ":"";return'\n <div class="vtilt-channel-item" data-channel-id="'+t.id+'" style="\n padding: 14px 16px;\n cursor: pointer;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n display: flex;\n align-items: center;\n gap: 12px;\n background: white;\n border-bottom: 1px solid #EEEEEE;\n ">\n <div style="\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: '+(t.ai_mode?r:"#DEDEDE")+';\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n ">\n '+(t.ai_mode?'<svg width="24" height="24" viewBox="0 0 24 24" fill="white"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"/></svg>':'<svg width="24" height="24" viewBox="0 0 24 24" fill="#666"><path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"/></svg>')+'\n </div>\n <div style="flex: 1; min-width: 0;">\n <div style="display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 4px;">\n <div style="font-weight: '+(e?"600":"500")+'; font-size: 15px; color: #000000; line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">\n '+(t.ai_mode?"AI Assistant":"Support")+'\n </div>\n <div style="font-size: 13px; color: #888888; white-space: nowrap; flex-shrink: 0;">'+n+'</div>\n </div>\n <div style="display: flex; justify-content: space-between; align-items: center; gap: 8px;">\n <div style="\n font-size: 14px;\n color: '+(e?"#333333":"#888888")+';\n font-weight: 400;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n flex: 1;\n min-width: 0;\n line-height: 1.4;\n ">'+s+this.Re(i)+("closed"===t.status?" · Closed":"")+"</div>\n "+(e?'<div style="\n min-width: 20px;\n height: 20px;\n padding: 0 6px;\n background: '+r+';\n border-radius: 10px;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 12px;\n font-weight: 600;\n color: #FFFFFF;\n line-height: 1;\n ">'+(t.unread_count>99?"99+":t.unread_count)+"</div>":"")+"\n </div>\n </div>\n </div>\n "}Te(){return'\n <div class="vtilt-chat-messages-wrapper" style="\n position: relative;\n flex: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n ">\n <div class="vtilt-chat-messages" style="\n flex: 1;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n padding: 20px 16px 24px 16px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-height: 0;\n background: #FAFAFA;\n "></div>\n <button class="vtilt-new-messages-pill" type="button" aria-label="Jump to latest messages">\n <span class="vtilt-new-messages-pill-text">↓ 1 new message</span>\n </button>\n </div>\n \n <div class="vtilt-chat-typing" style="\n display: none;\n padding: 12px 16px;\n background: #FAFAFA;\n align-items: center;\n ">\n <div style="\n display: flex;\n align-items: center;\n gap: 6px;\n ">\n <span style="width: 7px; height: 7px; background: #999; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0s;"></span>\n <span style="width: 7px; height: 7px; background: #999; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0.2s;"></span>\n <span style="width: 7px; height: 7px; background: #999; border-radius: 50%; animation: vtilt-typing 1.2s infinite 0.4s;"></span>\n <span class="vtilt-chat-typing-text" style="\n font-size: 12px;\n color: #666;\n font-weight: 500;\n white-space: nowrap;\n margin-left: 2px;\n ">Agent is typing...</span>\n </div>\n </div>\n <style>\n @keyframes vtilt-typing { 0%, 60%, 100% { opacity: 0.35; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-2px); } }\n </style>\n \n <div class="vtilt-chat-input-container" style="\n padding: 8px 12px;\n padding-bottom: max(8px, env(safe-area-inset-bottom, 8px));\n border-top: 1px solid #E5E5E5;\n flex-shrink: 0;\n background: #ffffff;\n ">\n <div style="\n position: relative;\n border: 1px solid #DDDDDD;\n border-radius: 12px;\n background: #ffffff;\n overflow: hidden;\n ">\n <textarea\n class="vtilt-chat-input"\n placeholder="Message..."\n autocomplete="off"\n autocorrect="on"\n autocapitalize="sentences"\n rows="1"\n style="\n width: 100%;\n box-sizing: border-box;\n border: none;\n border-radius: 0;\n padding: 12px 12px 36px 12px;\n font-size: 16px;\n line-height: 1.4;\n outline: none;\n background: transparent;\n -webkit-appearance: none;\n appearance: none;\n color: #000000;\n transition: none;\n resize: none;\n overflow-y: auto;\n overflow-x: hidden;\n min-height: 60px;\n max-height: 120px;\n font-family: inherit;\n "\n ></textarea>\n <div style="\n position: absolute;\n left: 0;\n bottom: 0;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 0 8px 10px;\n pointer-events: none;\n z-index: 1;\n ">\n <button\n class="vtilt-chat-attach"\n style="\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n pointer-events: auto;\n color: #666666;\n transition: color 0.15s ease;\n "\n title="Attach file"\n >\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>\n </svg>\n </button>\n <button\n class="vtilt-chat-mic"\n style="\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n pointer-events: auto;\n color: #666666;\n transition: color 0.15s ease;\n "\n title="Voice message"\n >\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"></path>\n <path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>\n <line x1="12" y1="19" x2="12" y2="23"></line>\n <line x1="8" y1="23" x2="16" y2="23"></line>\n </svg>\n </button>\n </div>\n <button class="vtilt-chat-send" disabled style="\n position: absolute;\n right: 0;\n bottom: 0;\n background: #E5E5E5;\n color: #999999;\n border: none;\n border-radius: 50%;\n padding: 0;\n width: 32px;\n height: 32px;\n margin: 6px 8px 6px 6px;\n cursor: not-allowed;\n display: flex;\n align-items: center;\n justify-content: center;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n z-index: 2;\n transition: background-color 0.15s ease, color 0.15s ease, transform 0.1s ease, cursor 0.15s ease;\n opacity: 0.6;\n ">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">\n <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>\n </svg>\n </button>\n </div>\n </div>\n '}Se(){var t,e,n,i,r,s,a,o,l,h,c,d=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-send");null==d||d.addEventListener("click",()=>{d.disabled||this.Ee()});var u=null===(e=this.it)||void 0===e?void 0:e.querySelector(".vtilt-new-messages-pill");null==u||u.addEventListener("click",()=>{var t,e=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-messages");e&&(e.scrollTop=e.scrollHeight),this.Bt=!1,this.jt=0,this.qe()});var v=null===(n=this.it)||void 0===n?void 0:n.querySelector(".vtilt-chat-input");null===(r=null===(i=this.it)||void 0===i?void 0:i.querySelector(".vtilt-chat-attach"))||void 0===r||r.addEventListener("click",t=>{t.preventDefault(),alert("File attachments coming soon!")}),null===(a=null===(s=this.it)||void 0===s?void 0:s.querySelector(".vtilt-chat-emoji"))||void 0===a||a.addEventListener("click",t=>{t.preventDefault(),bi().debug(Ii,"emoji clicked (not implemented)")}),null===(l=null===(o=this.it)||void 0===o?void 0:o.querySelector(".vtilt-chat-gif"))||void 0===l||l.addEventListener("click",t=>{t.preventDefault(),bi().debug(Ii,"GIF clicked (not implemented)")}),null===(c=null===(h=this.it)||void 0===h?void 0:h.querySelector(".vtilt-chat-mic"))||void 0===c||c.addEventListener("click",t=>{t.preventDefault(),alert("Voice messages coming soon!")});var p=()=>{if(v){v.style.height="auto";var t=v.scrollHeight;v.style.height=Math.min(Math.max(t,60),120)+"px"}},f=this.$t.primaryColor,g=()=>{var t,e=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-send");if(e&&v){var n=v.value.trim().length>0;e.disabled=!n,n?(e.style.background=f||"#E5E5E5",e.style.color="white",e.style.cursor="pointer",e.style.opacity="1"):(e.style.background="#E5E5E5",e.style.color="#999999",e.style.cursor="not-allowed",e.style.opacity="0.6")}};null==v||v.addEventListener("input",()=>{p(),this.xe(),g()}),null==v||v.addEventListener("keydown",t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.Ee())}),v&&(p(),g())}Le(t){var e=new Date(t),n=(new Date).getTime()-e.getTime(),i=Math.floor(n/6e4),r=Math.floor(n/36e5),s=Math.floor(n/864e5);return i<1?"Just now":i<60?i+"m ago":r<24?r+"h ago":s<7?s+"d ago":e.toLocaleDateString()}_e(){var t,e,n,i,r=this,s=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-chat-messages");if(s){this.Fe(s);var a=this.$t.primaryColor,o=this.qt.messages;if(0===o.length&&this.qt.isLoading){var l=null==this.qt.channel?"new-channel":"skeleton";s.dataset.renderMode!==l&&(s.innerHTML="new-channel"===l?this.He():this.ze(),s.dataset.renderMode=l)}else{"skeleton"!==s.dataset.renderMode&&"new-channel"!==s.dataset.renderMode||(s.innerHTML="",delete s.dataset.renderMode);var h=o.findIndex(t=>("agent"===t.sender_type||"ai"===t.sender_type)&&!this.ce(t.created_at)),c=this.Ve(s),d=s.childElementCount,u=null!==(i=null===(n=null===(e=s.lastElementChild)||void 0===e?void 0:e.dataset.msgKey)||void 0===n?void 0:n.replace("msg:",""))&&void 0!==i?i:null,v=o.length>0?o[o.length-1].id:null,p=new Map;Array.from(s.children).forEach(t=>{var e=t,n=e.dataset.msgKey;n&&p.set(n,e)});for(var f=null,g=function(){var t=o[m];if(m===h&&h>0){var e="divider:"+t.id,n=p.get(e);n?p.delete(e):(n=r.We(a)).dataset.msgKey=e;var i=f?f.nextElementSibling:s.firstElementChild;i!==n&&s.insertBefore(n,i),f=n}var l="msg:"+t.id,c=r.Je(t),u=p.get(l);if(u){if(u.dataset.fingerprint!==c){var v=r.$e(t);v.dataset.msgKey=l,v.dataset.fingerprint=c,u.replaceWith(v),u=v}p.delete(l)}else if((u=r.$e(t)).dataset.msgKey=l,u.dataset.fingerprint=c,d>0){u.classList.add("vtilt-msg-enter");var g=u;setTimeout(()=>g.classList.remove("vtilt-msg-enter"),260)}var w=f?f.nextElementSibling:s.firstElementChild;w!==u&&s.insertBefore(u,w),f=u},m=0;m<o.length;m++)g();p.forEach(t=>t.remove());var w=o[o.length-1],y="user"===(null==w?void 0:w.sender_type),b=null!==v&&v!==u;c||y||0===d?(s.scrollTop=s.scrollHeight,this.Bt=!1,this.jt=0,this.qe()):b&&w&&!y&&(this.jt+=1,this.Ke())}}}We(t){var e=t||"#7B68EE",n=r.createElement("div");return n.style.cssText="display:flex;align-items:center;gap:12px;margin:12px 0",n.innerHTML='<div style="flex:1;height:1px;background:#DDD"></div><span style="font-size:12px;font-weight:600;color:'+e+'">New</span><div style="flex:1;height:1px;background:#DDD"></div>',n}$e(t){var e=r.createElement("div");return e.innerHTML=this.Ge(t).trim(),e.firstElementChild}Je(t){var e,n,i;return[t.id,t.sender_type,t.created_at,(null!==(e=t.content)&&void 0!==e?e:"").length,(null!==(n=t.content)&&void 0!==n?n:"").slice(0,64),JSON.stringify(null!==(i=t.metadata)&&void 0!==i?i:null)].join("|")}Fe(t){this.Pt||(this.Pt=!0,t.addEventListener("scroll",()=>{this.Ve(t)?(this.Bt=!1,this.jt=0,this.qe()):this.Bt=!0},{passive:!0}))}Ve(t){return t.scrollHeight-t.scrollTop-t.clientHeight<80}Ke(){var t,e=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-new-messages-pill");if(e){e.style.display="flex";var n=e.querySelector(".vtilt-new-messages-pill-text");n&&(n.textContent=this.jt<=1?"↓ 1 new message":"↓ "+this.jt+" new messages")}}qe(){var t,e=null===(t=this.it)||void 0===t?void 0:t.querySelector(".vtilt-new-messages-pill");e&&(e.style.display="none")}Ge(t){var e="user"===t.sender_type,n="ai"===t.sender_type,i=e&&this.Qe(t.created_at),r=this.$t.primaryColor;if(e)return'\n <div class="vtilt-msg" style="\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n ">\n <div style="\n max-width: 80%;\n padding: 12px 16px;\n background: '+r+";\n color: white;\n border-radius: 20px 20px 4px 20px;\n font-size: 15px;\n line-height: 1.45;\n word-wrap: break-word;\n overflow-wrap: break-word;\n white-space: "+(g(t)?"normal":"pre-wrap")+';\n ">'+this.Ye(t)+'</div>\n <div style="font-size: 12px; color: #888888; margin-top: 6px; display: flex; align-items: center; gap: 4px;">\n '+this.Xe(t.created_at)+"\n "+(i?'<svg width="14" height="14" viewBox="0 0 24 24" fill="'+r+'"><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>':"")+"\n </div>\n </div>\n ";var s=n?"AI Assistant":t.sender_name||"Support";return'\n <div class="vtilt-msg" style="\n display: flex;\n gap: 10px;\n align-items: flex-end;\n ">\n <div style="\n width: 32px;\n height: 32px;\n border-radius: 50%;\n background: '+(n?r:"#DEDEDE")+';\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n ">\n '+(n?'<svg width="16" height="16" viewBox="0 0 24 24" fill="white"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"/></svg>':'<svg width="16" height="16" viewBox="0 0 24 24" fill="#666"><path d="M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"/></svg>')+'\n </div>\n <div style="flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: flex-start;">\n <div style="\n max-width: 85%;\n padding: 12px 16px;\n background: #ffffff;\n color: #000000;\n border-radius: 20px 20px 20px 4px;\n font-size: 15px;\n line-height: 1.45;\n word-wrap: break-word;\n overflow-wrap: break-word;\n ">'+this.Ye(t)+this.Ze(t)+'</div>\n <div style="font-size: 12px; color: #888888; margin-top: 6px; margin-left: 4px;">\n '+s+" · "+this.Xe(t.created_at)+"\n </div>\n </div>\n </div>\n "}Qe(t){return!!this.qt.agentLastReadAt&&new Date(t)<=new Date(this.qt.agentLastReadAt)}le(t,e,n){var i=this;return o(function*(){var r,s,a,o,l,h={id:"temp-ai-"+Date.now(),channel_id:n,sender_type:"ai",sender_id:null,sender_name:"AI Assistant",sender_avatar_url:null,content:"",content_type:"text",metadata:{},created_at:(new Date).toISOString()};i.qt.messages.push(h),i.Yt();var c=null===(r=t.body)||void 0===r?void 0:r.getReader();if(!c)return bi().error(Ii,"no response body reader available"),void i.tn(h.id);var d=new TextDecoder,u="",v=null;try{for(;;){var{done:p,value:f}=yield c.read();if(p)break;var g=d.decode(f,{stream:!0});u+=g,v||(v=setTimeout(()=>{var t=i.qt.messages.findIndex(t=>t.id===h.id);-1!==t&&(i.qt.messages[t].content=u.replace(/<[^>]*$/,""),i.Yt()),v=null},50))}var m=i.qt.messages.findIndex(t=>t.id===h.id);if(-1!==m){var w=i.en(u);i.qt.messages[m].content=u,w.length>0&&(i.qt.messages[m].metadata.et=w),i.Yt()}null===(a=(s=i.Lt).onMessageSent)||void 0===a||a.call(s,{channelId:n,messageId:e.id}),i.Gt(e,n,null===(l=null===(o=i.qt.channel)||void 0===o?void 0:o.ai_mode)||void 0===l||l)}catch(t){bi().error(Ii,"failed to handle streaming response:",t),i.tn(h.id)}finally{c.releaseLock(),v&&clearTimeout(v)}})()}tn(t){this.qt.messages=this.qt.messages.filter(e=>e.id!==t),this.Yt()}Zt(){return 0}Ye(t){var e,n=null!==(e=t.content)&&void 0!==e?e:"";return g(t)?'<div class="vtilt-md'+("user"===t.sender_type?" vtilt-user-md":"")+'">'+this.nn(n,t.content_type)+"</div>":this.Re(n)}nn(t,e){return void 0===e&&(e="text"),v(t.replace(Bi,"").trim(),e,null!=r?r:null)}Ze(t){var e,n=null!==(e=t.metadata)&&void 0!==e?e:{},i=n.et;if(i&&0!==i.length||(i=n.widgets),i&&0!==i.length||!t.content||(i=this.en(t.content)),!i||0===i.length)return"";var r=this.ye();return r.messageId=t.id,i.map(t=>{if(t.submitted){if("collect_email"===t.type){var e=t.submittedEmail?String(t.submittedEmail).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):"",n=t.submittedName?String(t.submittedName).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):"";return'<div class="vtilt-widget"><p style="margin:0; font-size:13px; color:#16a34a;">'+(n?"&#10003; Thanks, "+n+"! We'll follow up at "+e+".":e?"&#10003; Thanks! We'll follow up at "+e+".":"&#10003; Thanks!")+"</p></div>"}return"escalate_to_human"===t.type?'<div class="vtilt-widget"><p style="margin:0; font-size:13px; color:#16a34a;">&#10003; A team member has been notified. They\'ll join shortly.</p></div>':'<div class="vtilt-widget"><p style="margin:0; font-size:13px; color:#16a34a;">&#10003; Done</p></div>'}var i=this.St.get(t.type);return i?i.render(t.params,r):""}).join("")}ye(){var t,e,n=this._instance.getConfig();return{channelId:null!==(e=null===(t=this.qt.channel)||void 0===t?void 0:t.id)&&void 0!==e?e:"",distinctId:this.Kt,primaryColor:this.$t.primaryColor||"#7B68EE",apiBase:n.api_host||"",token:n.token||"",messageId:"",buildEndpointUrl:t=>w(this._instance.getConfig(),t)}}en(t){for(var e,n,i=[],r=new RegExp(Bi.source,"g");null!==(n=r.exec(t));)try{var s=JSON.parse(n[1]);s.type&&i.push({type:s.type,params:null!==(e=s.params)&&void 0!==e?e:{}})}catch(t){}return i}registerWidget(t){this.St.register(t)}Re(t){if(!r)return t;var e=r.createElement("div");return e.textContent=t,e.innerHTML}ae(t){var e,n,i,r,s=(i=t.content||"",void 0===r&&(r=100),i.replace(/\n?<!--vtilt:widget:[\s\S]*?-->/g,"").replace(/<[^>]*>/g,"").trim().substring(0,r));if(s)return s;var a=null!==(e=t.metadata)&&void 0!==e?e:{},o=null!==(n=a.et)&&void 0!==n?n:a.widgets;return o&&o.length>0?o.map(t=>"collect_email"===t.type?t.submitted&&t.submittedEmail?"Contact collected: "+(t.submittedName?t.submittedName+" ("+t.submittedEmail+")":t.submittedEmail):"Asked for contact info":"escalate_to_human"===t.type?t.submitted?"Escalated to human agent":"Offered human escalation":t.type.replace(/_/g," ")).join(", "):""}Xe(t){if(null==t||""===t)return"";var e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}function Di(t,e){return new Ni(t,e)}s.__VTiltExtensions__=s.__VTiltExtensions__||{},s.__VTiltExtensions__.initChat=Di,t.LazyLoadedChat=Ni,t.default=Di,t.initChat=Di,Object.defineProperty(t,"__esModule",{value:!0})}({});
2
2
  //# sourceMappingURL=chat.js.map