@v-tilt/browser 1.12.0 → 1.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/all-external-dependencies.js.map +1 -1
- package/dist/array.chat.js +2 -0
- package/dist/array.chat.js.map +1 -0
- package/dist/array.chat.no-external.js +2 -0
- package/dist/array.chat.no-external.js.map +1 -0
- package/dist/array.full.chat.js +2 -0
- package/dist/array.full.chat.js.map +1 -0
- package/dist/array.full.chat.no-external.js +2 -0
- package/dist/array.full.chat.no-external.js.map +1 -0
- package/dist/array.full.js +1 -1
- package/dist/array.full.js.map +1 -1
- package/dist/array.full.no-external.js +2 -0
- package/dist/array.full.no-external.js.map +1 -0
- package/dist/array.js +1 -1
- package/dist/array.js.map +1 -1
- package/dist/array.no-external.js +1 -1
- package/dist/array.no-external.js.map +1 -1
- package/dist/chat.js +1 -1
- package/dist/chat.js.map +1 -1
- package/dist/entrypoints/all-external-dependencies.d.ts +10 -3
- package/dist/entrypoints/array.chat.d.ts +10 -0
- package/dist/entrypoints/array.chat.no-external.d.ts +6 -0
- package/dist/entrypoints/array.full.chat.d.ts +13 -0
- package/dist/entrypoints/array.full.chat.no-external.d.ts +7 -0
- package/dist/entrypoints/array.full.d.ts +5 -9
- package/dist/entrypoints/array.full.no-external.d.ts +12 -0
- package/dist/entrypoints/module.chat.es.d.ts +7 -0
- package/dist/entrypoints/module.full.chat.es.d.ts +12 -0
- package/dist/entrypoints/module.full.es.d.ts +12 -0
- package/dist/entrypoints/module.no-external.es.d.ts +1 -0
- package/dist/extensions/chat/bubble-drag.d.ts +20 -5
- package/dist/extensions/chat/chat-wrapper.d.ts +8 -2
- package/dist/extensions/chat/chat.d.ts +21 -221
- package/dist/extensions/chat/controller/__tests__/fakes/ably-realtime-fake.d.ts +84 -0
- package/dist/extensions/chat/controller/ably-client.d.ts +160 -0
- package/dist/extensions/chat/controller/ably-handlers.d.ts +95 -0
- package/dist/extensions/chat/controller/ably-token.d.ts +67 -0
- package/dist/extensions/chat/controller/chat-controller.d.ts +194 -0
- package/dist/extensions/chat/controller/message-delivery-status.d.ts +6 -0
- package/dist/extensions/chat/controller/message-order.d.ts +12 -0
- package/dist/extensions/chat/controller/message-stream.d.ts +49 -0
- package/dist/extensions/chat/lib/bubble-offset.d.ts +18 -0
- package/dist/extensions/chat/lib/merge-chat-config.d.ts +3 -0
- package/dist/extensions/chat/normalize-send-content.d.ts +2 -0
- package/dist/extensions/chat/outbox/message-delivery.d.ts +17 -0
- package/dist/extensions/chat/outbox/message-outbox.d.ts +57 -0
- package/dist/extensions/chat/store/chat-store.d.ts +122 -0
- package/dist/extensions/chat/types.d.ts +1 -19
- package/dist/extensions/chat/ui/ChannelItem.d.ts +12 -0
- package/dist/extensions/chat/ui/ChannelListView.d.ts +14 -0
- package/dist/extensions/chat/ui/ChatBubble.d.ts +14 -0
- package/dist/extensions/chat/ui/ChatHeader.d.ts +13 -0
- package/dist/extensions/chat/ui/ChatPanel.d.ts +14 -0
- package/dist/extensions/chat/ui/ChatRoot.d.ts +31 -0
- package/dist/extensions/chat/ui/ClosedBanner.d.ts +7 -0
- package/dist/extensions/chat/ui/ConnectionBanner.d.ts +32 -0
- package/dist/extensions/chat/ui/ConversationView.d.ts +14 -0
- package/dist/extensions/chat/ui/MessageBubble.d.ts +25 -0
- package/dist/extensions/chat/ui/MessageInput.d.ts +14 -0
- package/dist/extensions/chat/ui/MessageList.d.ts +19 -0
- package/dist/extensions/chat/ui/NewMessagesPill.d.ts +13 -0
- package/dist/extensions/chat/ui/Skeletons.d.ts +14 -0
- package/dist/extensions/chat/ui/TypingBubble.d.ts +23 -0
- package/dist/extensions/chat/ui/TypingIndicator.d.ts +12 -0
- package/dist/extensions/chat/ui/WidgetSlot.d.ts +20 -0
- package/dist/extensions/chat/ui/hooks/use-auto-mark-read.d.ts +18 -0
- package/dist/extensions/chat/ui/hooks/use-scroll-preservation.d.ts +33 -0
- package/dist/extensions/chat/ui/icons.d.ts +18 -0
- package/dist/extensions/chat/ui/message-render.d.ts +18 -0
- package/dist/extensions/chat/ui/shadow-styles.d.ts +13 -0
- package/dist/extensions/chat/ui/utils/mobile-body-scroll-lock.d.ts +14 -0
- package/dist/extensions/chat/widget-registry.d.ts +21 -5
- package/dist/extensions/chat/widgets/collect-email.d.ts +4 -2
- package/dist/extensions/chat/widgets/escalate-to-human.d.ts +2 -1
- package/dist/external-scripts-loader.js +1 -1
- package/dist/external-scripts-loader.js.map +1 -1
- package/dist/feature.d.ts +1 -0
- package/dist/lib/merge-vtilt-config.d.ts +9 -0
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/module.chat.d.ts +1788 -0
- package/dist/module.chat.js +2 -0
- package/dist/module.chat.js.map +1 -0
- package/dist/module.d.ts +48 -3
- package/dist/module.full.chat.d.ts +1792 -0
- package/dist/module.full.chat.js +2 -0
- package/dist/module.full.chat.js.map +1 -0
- package/dist/module.full.d.ts +1793 -0
- package/dist/module.full.js +2 -0
- package/dist/module.full.js.map +1 -0
- package/dist/module.js +1 -1
- package/dist/module.js.map +1 -1
- package/dist/module.no-external.d.ts +48 -3
- package/dist/module.no-external.js +1 -1
- package/dist/module.no-external.js.map +1 -1
- package/dist/recorder.js.map +1 -1
- package/dist/snippet-stub-methods.d.ts +14 -0
- package/dist/utils/globals.d.ts +53 -27
- package/dist/utils/index.d.ts +8 -0
- package/dist/vtilt.d.ts +6 -1
- package/dist/web-vitals.js.map +1 -1
- package/package.json +4 -1
- package/dist/extensions/chat/chat-styles.d.ts +0 -27
- package/dist/extensions/chat/message-content-styles.d.ts +0 -1
- package/dist/extensions/chat/message-html.d.ts +0 -6
- package/dist/extensions/chat/message-markdown.d.ts +0 -8
- package/dist/extensions/ga4-proxy.d.ts +0 -59
- package/dist/utils/type-utils.d.ts +0 -4
- package/dist/web-vitals.d.ts +0 -81
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
!function(){"use strict";var t="undefined"!=typeof window?window:void 0,e="undefined"!=typeof globalThis?globalThis:t,n=null==e?void 0:e.navigator,i=null==e?void 0:e.document,r=null==e?void 0:e.location,s=null==e?void 0:e.fetch;t&&i&&i.createElement,null==e||e.XMLHttpRequest,null==e||e.AbortController;var o=null==n?void 0:n.userAgent,a=null!=t?t:{};function l(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(t){return void n(t)}a.done?e(l):Promise.resolve(l).then(i,r)}function u(t){return function(){var e=this,n=arguments;return new Promise(function(i,r){var s=t.apply(e,n);function o(t){l(s,i,r,o,a,"next",t)}function a(t){l(s,i,r,o,a,"throw",t)}o(void 0)})}}function h(){return h=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},h.apply(null,arguments)}var d="x-api-key";function c(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 o=s.includes("?")?"&":"?";s=""+s+o+"token="+r}return s}function v(t){return t.token?{[d]:t.token}:{}}function f(t){return"string"==typeof t}function p(t){return void 0===t}function g(t){return null==t}function m(t){return Array.isArray(t)}function b(t){return"function"==typeof t}var y={none:0,error:1,warn:2,info:3,debug:4},w="[vTilt]",x=new Set(["none","error","warn","info","debug"]);function _(){return"undefined"!=typeof console}function k(t){var e=t.length>0&&"string"==typeof t[0]?t[0]:"",n=e?t.slice(1):t;return[e?w+":"+e:w,...n]}var S="warn",C=!1;var E=null;function T(){return E||(E={setLevel(t,e){void 0===e&&(e=!1),S=t,e&&(C=!0)},setLevelFromRemote(t){C||t&&x.has(t)&&(S=t)},getLevel:()=>S,isLockedByInit:()=>C,debug(){if(!(y[S]<y.debug)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...k(e))}},info(){if(!(y[S]<y.info)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...k(e))}},warn(){if(!(y[S]<y.warn)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.warn(...k(e))}},error(){if(!(y[S]<y.error)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.error(...k(e))}}}),E}function A(t,e){void 0===e&&(e=!0);var n=void 0!==t.log_level||!!t.debug,i=function(t){return t.log_level&&x.has(t.log_level)?t.log_level:t.debug?"debug":"warn"}(t);return T().setLevel(i,e&&n),i}function I(t,e){try{return t()}catch(t){return e}}class O{constructor(){this.k=new Map,this.C=new Map}on(t,e){return this.k.has(t)||this.k.set(t,new Set),this.k.get(t).add(e),()=>{var n;null===(n=this.k.get(t))||void 0===n||n.delete(e)}}once(t,e){return this.C.has(t)||this.C.set(t,new Set),this.C.get(t).add(e),()=>{var n;null===(n=this.C.get(t))||void 0===n||n.delete(e)}}emit(t,e){var n,i;null===(n=this.k.get(t))||void 0===n||n.forEach(n=>{try{n(e)}catch(e){T().error("emitter",'error in event listener for "'+t+'":',e)}});var r=this.C.get(t);r&&(r.forEach(n=>{try{n(e)}catch(e){T().error("emitter",'error in once listener for "'+t+'":',e)}}),this.C.delete(t)),null===(i=this.k.get("*"))||void 0===i||i.forEach(n=>{try{n({event:t,payload:e})}catch(t){T().error("emitter","error in wildcard listener:",t)}})}off(t){t?(this.k.delete(t),this.C.delete(t)):(this.k.clear(),this.C.clear())}listenerCount(t){var e,n,i,r;return(null!==(n=null===(e=this.k.get(t))||void 0===e?void 0:e.size)&&void 0!==n?n:0)+(null!==(r=null===(i=this.C.get(t))||void 0===i?void 0:i.size)&&void 0!==r?r:0)}hasListeners(t){return this.listenerCount(t)>0}}var M="sdk:initialized",R="sdk:config_updated",P="sdk:remote_config_loaded",D="consent:updated",U="event:captured",j="recording:started",B="recording:stopped",N=0,L=!1,z=!1;function q(t){(N+=1)<2||(L=!0,z||(z=!0,T().warn(t,"vTilt network requests are being cancelled before reaching the server (likely an ad blocker, privacy extension, or DNS-level filter). Further retries and snapshots have been suspended for this page. Route SDK traffic through your own domain to avoid this — see https://www.vtilt.com/docs/browser/reverse-proxy.")))}function F(){N=0}function H(){return L}var W="23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function J(t){for(var e=(2<<31-Math.clz32(57))-1,n=Math.ceil(1.6*e*t/57),i="";i.length<t;)for(var r=crypto.getRandomValues(new Uint8Array(n)),s=0;s<n&&i.length<t;s++){var o=r[s]&e;o<57&&(i+=W[o])}return i}var V=1048576;function K(t,e,n){if(t)if(Array.isArray(t))t.forEach((t,i)=>{e.call(n,t,i)});else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(n,t[i],i)}function G(t,e,n,i){var{capture:r=!1,passive:s=!0}=null!=i?i:{};null==t||t.addEventListener(e,n,{capture:r,passive:s})}function X(t,e){if(!e)return t;for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}function Q(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];for(var r of n)for(var s of r)t.push(s);return t}function Z(t){var e={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var i=t[n];null!=i&&""!==i&&(e[n]=i)}return e}var Y="/api/chat/widget/channels",tt=t=>"/api/chat/widget/channels/"+t+"/messages",et=t=>"/api/chat/widget/channels/"+t+"/read",nt="/api/chat/token/widget";function it(t,e,n){return rt.apply(this,arguments)}function rt(){return(rt=u(function*(t,e,n){void 0===n&&(n={});var i=t.getConfig(),r=c(i,e);try{var s=yield fetch(r,h({},n,{headers:h({"Content-Type":"application/json"},v(i),n.headers)}));if(!s.ok)throw new Error("API error: "+s.status);return yield s.json()}catch(t){return T().error("chat","API request failed:",t),null}})).apply(this,arguments)}var st="rich_format",ot="markdown",at=/^[a-zA-Z0-9_-]{1,64}$/;function lt(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[st])===ot}(t):"ai"===t.sender_type||"agent"===t.sender_type}function ut(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();if(!s)return null;var o={};if(null==e?void 0:e.source){var a=function(t){var e=t.trim();if(at.test(e))return e}(e.source);a&&(o.message_source=a)}return"html"===r?{content:s,content_type:"html",metadata:o}:"markdown"===r?(o[st]=ot,{content:s,content_type:"text",metadata:o}):{content:s,content_type:"text",metadata:o}}var ht="$channel_message";class dt{constructor(){this.T=new Map}register(t){this.T.has(t.type)||this.T.set(t.type,t)}get(t){return this.T.get(t)}getAll(){return Array.from(this.T.values())}getToolDefinitions(){var t={};for(var e of this.T.values())t[e.type]={description:e.toolDescription,parameters:e.parameters};return t}}var ct,vt,ft,pt,gt,mt,bt,yt,wt,xt,_t,kt,St,Ct,Et,Tt={},At=[],It=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ot=Array.isArray;function Mt(t,e){for(var n in e)t[n]=e[n];return t}function Rt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Pt(t,e,n){var i,r,s,o={};for(s in e)"key"==s?i=e[s]:"ref"==s?r=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?ct.call(arguments,2):n),"function"==typeof t&&null!=t.defaultProps)for(s in t.defaultProps)void 0===o[s]&&(o[s]=t.defaultProps[s]);return Dt(t,o,i,r,null)}function Dt(t,e,n,i,r){var s={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++ft:r,__i:-1,__u:0};return null==r&&null!=vt.vnode&&vt.vnode(s),s}function Ut(t){return t.children}function jt(t,e){this.props=t,this.context=e}function $(t,e){if(null==e)return t.__?$(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if(null!=(n=t.__k[e])&&null!=n.__e)return n.__e;return"function"==typeof t.type?$(t):null}function Bt(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],r=[],s=Mt({},e);s.__v=e.__v+1,vt.vnode&&vt.vnode(s),Kt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,null==n?$(e):n,!!(32&e.__u),r),s.__v=e.__v,s.__.__k[s.__i]=s,Xt(i,s,r),e.__e=e.__=null,s.__e!=n&&Nt(s)}}function Nt(t){if(null!=(t=t.__)&&null!=t.__c)return t.__e=t.__c.base=null,t.__k.some(function(e){if(null!=e&&null!=e.__e)return t.__e=t.__c.base=e.__e}),Nt(t)}function Lt(t){(!t.__d&&(t.__d=!0)&>.push(t)&&!$t.__r++||mt!=vt.debounceRendering)&&((mt=vt.debounceRendering)||bt)($t)}function $t(){try{for(var t,e=1;gt.length;)gt.length>e&>.sort(yt),t=gt.shift(),e=gt.length,Bt(t)}finally{gt.length=$t.__r=0}}function zt(t,e,n,i,r,s,o,a,l,u,h){var d,c,v,f,p,g,m,b=i&&i.__k||At,y=e.length;for(l=function(t,e,n,i,r){var s,o,a,l,u,h=n.length,d=h,c=0;for(t.__k=new Array(r),s=0;s<r;s++)null!=(o=e[s])&&"boolean"!=typeof o&&"function"!=typeof o?("string"==typeof o||"number"==typeof o||"bigint"==typeof o||o.constructor==String?o=t.__k[s]=Dt(null,o,null,null,null):Ot(o)?o=t.__k[s]=Dt(Ut,{children:o},null,null,null):void 0===o.constructor&&o.__b>0?o=t.__k[s]=Dt(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[s]=o,l=s+c,o.__=t,o.__b=t.__b+1,a=null,-1!=(u=o.__i=Ht(o,n,l,d))&&(d--,(a=n[u])&&(a.__u|=2)),null==a||null==a.__v?(-1==u&&(r>h?c--:r<h&&c++),"function"!=typeof o.type&&(o.__u|=4)):u!=l&&(u==l-1?c--:u==l+1?c++:(u>l?c--:c++,o.__u|=4))):t.__k[s]=null;if(d)for(s=0;s<h;s++)null!=(a=n[s])&&!(2&a.__u)&&(a.__e==i&&(i=$(a)),te(a,a));return i}(n,e,b,l,y),d=0;d<y;d++)null!=(v=n.__k[d])&&(c=-1!=v.__i&&b[v.__i]||Tt,v.__i=d,g=Kt(t,v,c,r,s,o,a,l,u,h),f=v.__e,v.ref&&c.ref!=v.ref&&(c.ref&&Yt(c.ref,null,v),h.push(v.ref,v.__c||f,v)),null==p&&null!=f&&(p=f),(m=!!(4&v.__u))||c.__k===v.__k?(l=qt(v,l,t,m),m&&c.__e&&(c.__e=null)):"function"==typeof v.type&&void 0!==g?l=g:f&&(l=f.nextSibling),v.__u&=-7);return n.__e=p,l}function qt(t,e,n,i){var r,s;if("function"==typeof t.type){for(r=t.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=t,e=qt(r[s],e,n,i));return e}t.__e!=e&&(i&&(e&&t.type&&!e.parentNode&&(e=$(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do{e=e&&e.nextSibling}while(null!=e&&8==e.nodeType);return e}function Ft(t,e){return e=e||[],null==t||"boolean"==typeof t||(Ot(t)?t.some(function(t){Ft(t,e)}):e.push(t)),e}function Ht(t,e,n,i){var r,s,o,a=t.key,l=t.type,u=e[n],h=null!=u&&!(2&u.__u);if(null===u&&null==a||h&&a==u.key&&l==u.type)return n;if(i>(h?1:0))for(r=n-1,s=n+1;r>=0||s<e.length;)if(null!=(u=e[o=r>=0?r--:s++])&&!(2&u.__u)&&a==u.key&&l==u.type)return o;return-1}function Wt(t,e,n){"-"==e[0]?t.setProperty(e,null==n?"":n):t[e]=null==n?"":"number"!=typeof n||It.test(e)?n:n+"px"}function Jt(t,e,n,i,r){var s,o;t:if("style"==e)if("string"==typeof n)t.style.cssText=n;else{if("string"==typeof i&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Wt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Wt(t.style,e,n[e])}else if("o"==e[0]&&"n"==e[1])s=e!=(e=e.replace(kt,"$1")),o=e.toLowerCase(),e=o in t||"onFocusOut"==e||"onFocusIn"==e?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?i?n[_t]=i[_t]:(n[_t]=St,t.addEventListener(e,s?Et:Ct,s)):t.removeEventListener(e,s?Et:Ct,s);else{if("http://www.w3.org/2000/svg"==r)e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=e&&"height"!=e&&"href"!=e&&"list"!=e&&"form"!=e&&"tabIndex"!=e&&"download"!=e&&"rowSpan"!=e&&"colSpan"!=e&&"role"!=e&&"popover"!=e&&e in t)try{t[e]=null==n?"":n;break t}catch(t){}"function"==typeof n||(null==n||!1===n&&"-"!=e[4]?t.removeAttribute(e):t.setAttribute(e,"popover"==e&&1==n?"":n))}}function Vt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(null==e[xt])e[xt]=St++;else if(e[xt]<n[_t])return;return n(vt.event?vt.event(e):e)}}}function Kt(t,e,n,i,r,s,o,a,l,u){var h,d,c,v,f,p,g,m,b,y,$,w,x,_,k,S=e.type;if(void 0!==e.constructor)return null;128&n.__u&&(l=!!(32&n.__u),s=[a=e.__e=n.__e]),(h=vt.__b)&&h(e);t:if("function"==typeof S)try{if(m=e.props,b=S.prototype&&S.prototype.render,y=(h=S.contextType)&&i[h.__c],$=h?y?y.props.value:h.__:i,n.__c?g=(d=e.__c=n.__c).__=d.__E:(b?e.__c=d=new S(m,$):(e.__c=d=new jt(m,$),d.constructor=S,d.render=ee),y&&y.sub(d),d.state||(d.state={}),d.__n=i,c=d.__d=!0,d.__h=[],d._sb=[]),b&&null==d.__s&&(d.__s=d.state),b&&null!=S.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=Mt({},d.__s)),Mt(d.__s,S.getDerivedStateFromProps(m,d.__s))),v=d.props,f=d.state,d.__v=e,c)b&&null==S.getDerivedStateFromProps&&null!=d.componentWillMount&&d.componentWillMount(),b&&null!=d.componentDidMount&&d.__h.push(d.componentDidMount);else{if(b&&null==S.getDerivedStateFromProps&&m!==v&&null!=d.componentWillReceiveProps&&d.componentWillReceiveProps(m,$),e.__v==n.__v||!d.__e&&null!=d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(m,d.__s,$)){e.__v!=n.__v&&(d.props=m,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(t){t&&(t.__=e)}),At.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&o.push(d);break t}null!=d.componentWillUpdate&&d.componentWillUpdate(m,d.__s,$),b&&null!=d.componentDidUpdate&&d.__h.push(function(){d.componentDidUpdate(v,f,p)})}if(d.context=$,d.props=m,d.__P=t,d.__e=!1,w=vt.__r,x=0,b)d.state=d.__s,d.__d=!1,w&&w(e),h=d.render(d.props,d.state,d.context),At.push.apply(d.__h,d._sb),d._sb=[];else do{d.__d=!1,w&&w(e),h=d.render(d.props,d.state,d.context),d.state=d.__s}while(d.__d&&++x<25);d.state=d.__s,null!=d.getChildContext&&(i=Mt(Mt({},i),d.getChildContext())),b&&!c&&null!=d.getSnapshotBeforeUpdate&&(p=d.getSnapshotBeforeUpdate(v,f)),_=null!=h&&h.type===Ut&&null==h.key?Qt(h.props.children):h,a=zt(t,Ot(_)?_:[_],e,n,i,r,s,o,a,l,u),d.base=e.__e,e.__u&=-161,d.__h.length&&o.push(d),g&&(d.__E=d.__=null)}catch(t){if(e.__v=null,l||null!=s)if(t.then){for(e.__u|=l?160:128;a&&8==a.nodeType&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,e.__e=a}else{for(k=s.length;k--;)Rt(s[k]);Gt(e)}else e.__e=n.__e,e.__k=n.__k,t.then||Gt(e);vt.__e(t,e,n)}else null==s&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Zt(n.__e,e,n,i,r,s,o,l,u);return(h=vt.diffed)&&h(e),128&e.__u?void 0:a}function Gt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Gt))}function Xt(t,e,n){for(var i=0;i<n.length;i++)Yt(n[i],n[++i],n[++i]);vt.__c&&vt.__c(e,t),t.some(function(e){try{t=e.__h,e.__h=[],t.some(function(t){t.call(e)})}catch(t){vt.__e(t,e.__v)}})}function Qt(t){return"object"!=typeof t||null==t||t.__b>0?t:Ot(t)?t.map(Qt):void 0!==t.constructor?null:Mt({},t)}function Zt(t,e,n,i,r,s,o,a,l){var u,h,d,c,v,f,p,g=n.props||Tt,m=e.props,b=e.type;if("svg"==b?r="http://www.w3.org/2000/svg":"math"==b?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=s)for(u=0;u<s.length;u++)if((v=s[u])&&"setAttribute"in v==!!b&&(b?v.localName==b:3==v.nodeType)){t=v,s[u]=null;break}if(null==t){if(null==b)return document.createTextNode(m);t=document.createElementNS(r,b,m.is&&m),a&&(vt.__m&&vt.__m(e,s),a=!1),s=null}if(null==b)g===m||a&&t.data==m||(t.data=m);else{if(s="textarea"==b&&null!=m.defaultValue?null:s&&ct.call(t.childNodes),!a&&null!=s)for(g={},u=0;u<t.attributes.length;u++)g[(v=t.attributes[u]).name]=v.value;for(u in g)v=g[u],"dangerouslySetInnerHTML"==u?d=v:"children"==u||u in m||"value"==u&&"defaultValue"in m||"checked"==u&&"defaultChecked"in m||Jt(t,u,null,v,r);for(u in m)v=m[u],"children"==u?c=v:"dangerouslySetInnerHTML"==u?h=v:"value"==u?f=v:"checked"==u?p=v:a&&"function"!=typeof v||g[u]===v||Jt(t,u,v,g[u],r);if(h)a||d&&(h.__html==d.__html||h.__html==t.innerHTML)||(t.innerHTML=h.__html),e.__k=[];else if(d&&(t.innerHTML=""),zt("template"==e.type?t.content:t,Ot(c)?c:[c],e,n,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,s,o,s?s[0]:n.__k&&$(n,0),a,l),null!=s)for(u=s.length;u--;)Rt(s[u]);a&&"textarea"!=b||(u="value","progress"==b&&null==f?t.removeAttribute("value"):null!=f&&(f!==t[u]||"progress"==b&&!f||"option"==b&&f!=g[u])&&Jt(t,u,f,g[u],r),u="checked",null!=p&&p!=t[u]&&Jt(t,u,p,g[u],r))}return t}function Yt(t,e,n){try{if("function"==typeof t){var i="function"==typeof t.__u;i&&t.__u(),i&&null==e||(t.__u=t(e))}else t.current=e}catch(t){vt.__e(t,n)}}function te(t,e,n){var i,r;if(vt.unmount&&vt.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||Yt(i,null,e)),null!=(i=t.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(t){vt.__e(t,e)}i.base=i.__P=null}if(i=t.__k)for(r=0;r<i.length;r++)i[r]&&te(i[r],e,n||"function"!=typeof t.type);n||Rt(t.__e),t.__c=t.__=t.__e=void 0}function ee(t,e,n){return this.constructor(t,n)}function ne(t,e,n){var i,r,s;e==document&&(e=document.documentElement),vt.__&&vt.__(t,e),i=!1?null:e.__k,r=[],s=[],Kt(e,t=e.__k=Pt(Ut,null,[t]),i||Tt,Tt,e.namespaceURI,i?null:e.firstChild?ct.call(e.childNodes):null,r,i?i.__e:e.firstChild,false,s),Xt(r,t,s)}ct=At.slice,vt={__e:function(t,e,n,i){for(var r,s,o;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&null!=s.getDerivedStateFromError&&(r.setState(s.getDerivedStateFromError(t)),o=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(t,i||{}),o=r.__d),o)return r.__E=r}catch(e){t=e}throw t}},ft=0,pt=function(t){return null!=t&&void 0===t.constructor},jt.prototype.setState=function(t,e){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=Mt({},this.state),"function"==typeof t&&(t=t(Mt({},n),this.props)),t&&Mt(n,t),null!=t&&this.__v&&(e&&this._sb.push(e),Lt(this))},jt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Lt(this))},jt.prototype.render=Ut,gt=[],bt="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,yt=function(t,e){return t.__v.__b-e.__v.__b},$t.__r=0,wt=Math.random().toString(8),xt="__d"+wt,_t="__a"+wt,kt=/(PointerCapture)$|Capture$/i,St=0,Ct=Vt(!1),Et=Vt(!0);var ie=0;function re(t,e,n,i,r,s){e||(e={});var o,a,l=e;if("ref"in l)for(a in l={},e)"ref"==a?o=e[a]:l[a]=e[a];var u={type:t,props:l,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ie,__i:-1,__u:0,__source:r,__self:s};if("function"==typeof t&&(o=t.defaultProps))for(a in o)void 0===l[a]&&(l[a]=o[a]);return vt.vnode&&vt.vnode(u),u}var se,oe,ae,le,ue=0,he=[],de=vt,ce=de.__b,ve=de.__r,fe=de.diffed,pe=de.__c,ge=de.unmount,me=de.__;function be(t,e){de.__h&&de.__h(oe,t,ue||e),ue=0;var n=oe.__H||(oe.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function ye(t){return ue=1,function(t,e,n){var i=be(se++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Oe(void 0,e),function(t){var e=i.__N?i.__N[0]:i.__[0],n=i.t(e,t);e!==n&&(i.__N=[n,i.__[1]],i.__c.setState({}))}],i.__c=oe,!oe.__f)){var r=function(t,e,n){if(!i.__c.__H)return!0;var r=i.__c.__H.__.filter(function(t){return t.__c});if(r.every(function(t){return!t.__N}))return!s||s.call(this,t,e,n);var o=i.__c.props!==t;return r.some(function(t){if(t.__N){var e=t.__[0];t.__=t.__N,t.__N=void 0,e!==t.__[0]&&(o=!0)}}),s&&s.call(this,t,e,n)||o};oe.__f=!0;var s=oe.shouldComponentUpdate,o=oe.componentWillUpdate;oe.componentWillUpdate=function(t,e,n){if(this.__e){var i=s;s=void 0,r(t,e,n),s=i}o&&o.call(this,t,e,n)},oe.shouldComponentUpdate=r}return i.__N||i.__}(Oe,t)}function we(t,e){var n=be(se++,3);!de.__s&&Ie(n.__H,e)&&(n.__=t,n.u=e,oe.__H.__h.push(n))}function xe(t){return ue=5,_e(function(){return{current:t}},[])}function _e(t,e){var n=be(se++,7);return Ie(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function ke(t,e){return ue=8,_e(function(){return t},e)}function Se(){for(var t;t=he.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Te),e.__h.some(Ae),e.__h=[]}catch(n){e.__h=[],de.__e(n,t.__v)}}}de.__b=function(t){oe=null,ce&&ce(t)},de.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),me&&me(t,e)},de.__r=function(t){ve&&ve(t),se=0;var e=(oe=t.__c).__H;e&&(ae===oe?(e.__h=[],oe.__h=[],e.__.some(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.some(Te),e.__h.some(Ae),e.__h=[],se=0)),ae=oe},de.diffed=function(t){fe&&fe(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(1!==he.push(e)&&le===de.requestAnimationFrame||((le=de.requestAnimationFrame)||Ee)(Se)),e.__H.__.some(function(t){t.u&&(t.__H=t.u),t.u=void 0})),ae=oe=null},de.__c=function(t,e){e.some(function(t){try{t.__h.some(Te),t.__h=t.__h.filter(function(t){return!t.__||Ae(t)})}catch(n){e.some(function(t){t.__h&&(t.__h=[])}),e=[],de.__e(n,t.__v)}}),pe&&pe(t,e)},de.unmount=function(t){ge&&ge(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(t){try{Te(t)}catch(t){e=t}}),n.__H=void 0,e&&de.__e(e,n.__v))};var Ce="function"==typeof requestAnimationFrame;function Ee(t){var e,n=function(){clearTimeout(i),Ce&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Ce&&(e=requestAnimationFrame(n))}function Te(t){var e=oe,n=t.__c;"function"==typeof n&&(t.__c=void 0,n()),oe=e}function Ae(t){var e=oe;t.__c=t.__(),oe=e}function Ie(t,e){return!t||t.length!==e.length||e.some(function(e,n){return e!==t[n]})}function Oe(t,e){return"function"==typeof e?e(t):e}var Me=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Re(t){var{prompt:e,ctx:n}=t,[i,r]=ye(""),[s,o]=ye(""),[a,l]=ye(!1),h=Me.test(s.trim())&&!a,d=function(){var t=u(function*(){if(h){l(!0);try{yield n.dispatch("submit",{email:s.trim(),name:i.trim()})}finally{l(!1)}}});return function(){return t.apply(this,arguments)}}();return re("div",{class:"vt-widget",children:[re("p",{children:e}),re("div",{style:"display: flex; flex-direction: column; gap: 8px;",children:[re("input",{type:"text",class:"vt-widget-input",placeholder:"Your name",value:i,onInput:t=>r(t.currentTarget.value),disabled:a}),re("div",{style:"display: flex; gap: 8px; align-items: center;",children:[re("input",{type:"email",class:"vt-widget-input",style:"flex: 1; min-width: 0; margin: 0;",placeholder:"your@email.com",value:s,onInput:t=>o(t.currentTarget.value),onKeyDown:t=>{"Enter"===t.key&&(t.preventDefault(),d())},disabled:a}),re("button",{type:"button",class:"vt-widget-btn","data-style":"outline",onClick:()=>{d()},disabled:!h,children:"Submit"})]})]})]})}var Pe={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)=>re(Re,{prompt:"string"==typeof t.prompt?t.prompt:"What's your name and email?",ctx:e}),onAction:(t,e,n)=>u(function*(){if("submit"!==t)return{};var i="string"==typeof e.email?e.email.trim():"";if(!i||!Me.test(i))return{};var r=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),s=n.token?{"x-api-key":n.token,"Content-Type":"application/json"}:{"Content-Type":"application/json"};try{var o=yield fetch(r,{method:"POST",headers: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 o.json()).success}}catch(t){return{}}})()},De={fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function Ue(t){return re("svg",h({width:24,height:24,viewBox:"0 0 24 24"},De,t,{children:re("path",{d:"M18 6L6 18M6 6l12 12"})}))}function je(t){return re("svg",h({width:24,height:24,viewBox:"0 0 24 24"},De,t,{children:re("path",{d:"M15 18l-6-6 6-6"})}))}function Be(t){return re("svg",h({width:16,height:16,viewBox:"0 0 24 24",fill:"currentColor"},t,{children:re("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}))}function Ne(t){return re("svg",h({width:28,height:28,viewBox:"0 0 28 28",fill:"white"},t,{children:re("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"})}))}function Le(t){return re("svg",h({width:22,height:22,viewBox:"0 0 24 24",fill:"currentColor"},t,{children:re("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"})}))}function $e(t){return re("svg",h({width:22,height:22,viewBox:"0 0 24 24",fill:"currentColor"},t,{children:re("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"})}))}function ze(t){return re("svg",h({width:36,height:36,viewBox:"0 0 24 24",fill:"white"},t,{children:re("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"})}))}function qe(t){return re("svg",h({width:16,height:16,viewBox:"0 0 24 24"},De,t,{children:[re("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),re("circle",{cx:"12",cy:"7",r:"4"})]}))}function Fe(t){var{prompt:e,ctx:n}=t,[i,r]=ye(!1),s=function(){var t=u(function*(){if(!i){r(!0);try{yield n.dispatch("escalate",{})}finally{r(!1)}}});return function(){return t.apply(this,arguments)}}();return re("div",{class:"vt-widget",children:[re("p",{children:e}),re("button",{type:"button",class:"vt-widget-btn","data-style":"outline",onClick:()=>{s()},disabled:i,children:[re(qe,{}),"Connect with a person"]})]})}var He={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)=>re(Fe,{prompt:"string"==typeof t.prompt?t.prompt:"Would you like me to connect you with a team member?",ctx:e}),onAction:(t,e,n)=>u(function*(){if("escalate"!==t)return{};var e=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),i=n.token?{"x-api-key":n.token,"Content-Type":"application/json"}:{"Content-Type":"application/json"};try{var r=yield fetch(e,{method:"POST",headers: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{}}})()},We=Symbol.for("preact-signals");function Je(){if(Qe>1)Qe--;else{var t,e=!1;for(!function(){var t=Ye;for(Ye=void 0;void 0!==t;)t.S.v===t.v&&(t.S.i=t.i),t=t.o}();void 0!==Xe;){var n=Xe;for(Xe=void 0,Ze++;void 0!==n;){var i=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&sn(n))try{n.c()}catch(n){e||(t=n,e=!0)}n=i}}if(Ze=0,Qe--,e)throw t}}var Ve=void 0;function Ke(t){var e=Ve;Ve=void 0;try{return t()}finally{Ve=e}}var Ge,Xe=void 0,Qe=0,Ze=0,Ye=void 0,tn=0;function en(t){if(void 0!==Ve){var e=t.n;if(void 0===e||e.t!==Ve)return e={i:0,S:t,p:Ve.s,n:void 0,t:Ve,e:void 0,x:void 0,r:e},void 0!==Ve.s&&(Ve.s.n=e),Ve.s=e,t.n=e,32&Ve.f&&t.S(e),e;if(-1===e.i)return e.i=0,void 0!==e.n&&(e.n.p=e.p,void 0!==e.p&&(e.p.n=e.n),e.p=Ve.s,e.n=void 0,Ve.s.n=e,Ve.s=e),e}}function nn(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=null==e?void 0:e.watched,this.Z=null==e?void 0:e.unwatched,this.name=null==e?void 0:e.name}function rn(t,e){return new nn(t,e)}function sn(t){for(var e=t.s;void 0!==e;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function on(t){for(var e=t.s;void 0!==e;e=e.n){var n=e.S.n;if(void 0!==n&&(e.r=n),e.S.n=e,e.i=-1,void 0===e.n){t.s=e;break}}}function an(t){for(var e=t.s,n=void 0;void 0!==e;){var i=e.p;-1===e.i?(e.S.U(e),void 0!==i&&(i.n=e.n),void 0!==e.n&&(e.n.p=i)):n=e,e.S.n=e.r,void 0!==e.r&&(e.r=void 0),e=i}t.s=n}function ln(t,e){nn.call(this,void 0),this.x=t,this.s=void 0,this.g=tn-1,this.f=4,this.W=null==e?void 0:e.watched,this.Z=null==e?void 0:e.unwatched,this.name=null==e?void 0:e.name}function un(t,e){return new ln(t,e)}function hn(t){var e=t.m;if(t.m=void 0,"function"==typeof e){Qe++;var n=Ve;Ve=void 0;try{e()}catch(e){throw t.f&=-2,t.f|=8,dn(t),e}finally{Ve=n,Je()}}}function dn(t){for(var e=t.s;void 0!==e;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,hn(t)}function cn(t){if(Ve!==this)throw new Error("Out-of-order effect");an(this),Ve=t,this.f&=-2,8&this.f&&dn(this),Je()}function vn(t,e){this.x=t,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=null==e?void 0:e.name}function fn(t,e){var n=new vn(t,e);try{n.c()}catch(t){throw n.d(),t}var i=n.d.bind(n);return i[Symbol.dispose]=i,i}function pn(t,e){vt[t]=e.bind(null,vt[t]||function(){})}function gn(t){if(Ge){var e=Ge;Ge=void 0,e()}Ge=t&&t.S()}function mn(t){var e=this,n=t.data,i=function(t){return _e(function(){return rn(t)},[])}(n);i.value=n;var r=_e(function(){for(var t=e.__v;t=t.__;)if(t.__c){t.__c.__$f|=4;break}return e.__$u.c=function(){var t,n=e.__$u.S(),i=r.value;n(),pt(i)||3!==(null==(t=e.base)?void 0:t.nodeType)?(e.__$f|=1,e.setState({})):e.base.data=i},un(function(){var t=i.value.value;return 0===t?0:!0===t?"":t||""})},[]);return r.value}function bn(t,e,n,i){var r=e in t&&void 0===t.ownerSVGElement,s=rn(n);return{o:function(t,e){s.value=t,i=e},d:fn(function(){var n=s.value.value;i[e]!==n&&(i[e]=n,r?t[e]=n:n?t.setAttribute(e,n):t.removeAttribute(e))})}}nn.prototype.brand=We,nn.prototype.h=function(){return!0},nn.prototype.S=function(t){var e=this,n=this.t;n!==t&&void 0===t.e&&(t.x=n,this.t=t,void 0!==n?n.e=t:Ke(function(){var t;null==(t=e.W)||t.call(e)}))},nn.prototype.U=function(t){var e=this;if(void 0!==this.t){var n=t.e,i=t.x;void 0!==n&&(n.x=i,t.e=void 0),void 0!==i&&(i.e=n,t.x=void 0),t===this.t&&(this.t=i,void 0===i&&Ke(function(){var t;null==(t=e.Z)||t.call(e)}))}},nn.prototype.subscribe=function(t){var e=this;return fn(function(){var n=e.value,i=Ve;Ve=void 0;try{t(n)}finally{Ve=i}},{name:"sub"})},nn.prototype.valueOf=function(){return this.value},nn.prototype.toString=function(){return this.value+""},nn.prototype.toJSON=function(){return this.value},nn.prototype.peek=function(){var t=this;return Ke(function(){return t.value})},Object.defineProperty(nn.prototype,"value",{get:function(){var t=en(this);return void 0!==t&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Ze>100)throw new Error("Cycle detected");!function(t){0!==Qe&&0===Ze&&0!==t.l&&(t.l=0,Ye={S:t,v:t.v,i:t.i,o:Ye})}(this),this.v=t,this.i++,tn++,Qe++;try{for(var e=this.t;void 0!==e;e=e.x)e.t.N()}finally{Je()}}}}),ln.prototype=new nn,ln.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if(32==(36&this.f))return!0;if(this.f&=-5,this.g===tn)return!0;if(this.g=tn,this.f|=1,this.i>0&&!sn(this))return this.f&=-2,!0;var t=Ve;try{on(this),Ve=this;var e=this.x();(16&this.f||this.v!==e||0===this.i)&&(this.v=e,this.f&=-17,this.i++)}catch(t){this.v=t,this.f|=16,this.i++}return Ve=t,an(this),this.f&=-2,!0},ln.prototype.S=function(t){if(void 0===this.t){this.f|=36;for(var e=this.s;void 0!==e;e=e.n)e.S.S(e)}nn.prototype.S.call(this,t)},ln.prototype.U=function(t){if(void 0!==this.t&&(nn.prototype.U.call(this,t),void 0===this.t)){this.f&=-33;for(var e=this.s;void 0!==e;e=e.n)e.S.U(e)}},ln.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;void 0!==t;t=t.x)t.t.N()}},Object.defineProperty(ln.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=en(this);if(this.h(),void 0!==t&&(t.i=this.i),16&this.f)throw this.v;return this.v}}),vn.prototype.c=function(){var t=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var e=this.x();"function"==typeof e&&(this.m=e)}finally{t()}},vn.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,hn(this),on(this),Qe++;var t=Ve;return Ve=this,cn.bind(this,t)},vn.prototype.N=function(){2&this.f||(this.f|=2,this.u=Xe,Xe=this)},vn.prototype.d=function(){this.f|=8,1&this.f||dn(this)},vn.prototype.dispose=function(){this.d()},mn.displayName="_st",Object.defineProperties(nn.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:mn},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),pn("__b",function(t,e){if("string"==typeof e.type){var n,i=e.props;for(var r in i)if("children"!==r){var s=i[r];s instanceof nn&&(n||(e.__np=n={}),n[r]=s,i[r]=s.peek())}}t(e)}),pn("__r",function(t,e){t(e),gn();var n,i=e.__c;i&&(i.__$f&=-2,void 0===(n=i.__$u)&&(i.__$u=n=function(){var t;return fn(function(){t=this}),t.c=function(){i.__$f|=1,i.setState({})},t}())),gn(n)}),pn("__e",function(t,e,n,i){gn(),t(e,n,i)}),pn("diffed",function(t,e){var n;if(gn(),"string"==typeof e.type&&(n=e.__e)){var i=e.__np,r=e.props;if(i){var s=n.U;if(s)for(var o in s){var a=s[o];void 0===a||o in i||(a.d(),s[o]=void 0)}else n.U=s={};for(var l in i){var u=s[l],h=i[l];void 0===u?(u=bn(n,l,h,r),s[l]=u):u.o(h,r)}}}t(e)}),pn("unmount",function(t,e){if("string"==typeof e.type){var n=e.__e;if(n){var i=n.U;if(i)for(var r in n.U=void 0,i){var s=i[r];s&&s.d()}}}else{var o=e.__c;if(o){var a=o.__$u;a&&(o.__$u=void 0,a.d())}}t(e)}),pn("__h",function(t,e,n,i){(i<3||9===i)&&(e.__$f|=2),t(e,n,i)}),jt.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,i=n&&void 0!==n.s;for(var r in e)return!0;if(this.__f||"boolean"==typeof this.u&&!0===this.u){if(!(i||2&this.__$f||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(i||4&this.__$f))return!0;if(3&this.__$f)return!0}for(var s in t)if("__source"!==s&&t[s]!==this.props[s])return!0;for(var o in this.props)if(!(o in t))return!0;return!1};var yn={primaryColor:"#7B68EE",fontFamily:"'Inter var', 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",borderRadius:"12px"};class wn{constructor(){this.isOpen=rn(!1),this.isVisible=rn(!0),this.isLoading=rn(!1),this.currentView=rn("list"),this.channels=rn([]),this.channel=rn(null),this.messages=rn([]),this.isTyping=rn(!1),this.typingSender=rn(null),this.typingSenderType=rn(null),this.agentLastReadAt=rn(null),this.initialUserReadAt=rn(null),this.userScrolledUp=rn(!1),this.unreadNewMessagesCount=rn(0),this.theme=rn(h({},yn)),this.connectionState=rn("disconnected"),this.ablyProjectId=rn(null),this.realtimeChannelId=rn(null),this.realtimeAttached=rn(!1),this.pendingRealtimeChannelId=rn(null),this.identityChangeInFlight=rn(!1),this.lastConnectedDistinctId=rn(null),this.A=new Map,this.isConnected=un(()=>"connected"===this.connectionState.value),this.polledUnreadTotal=rn(null),this.unreadCount=un(()=>this.isOpen.value||null===this.polledUnreadTotal.value?this.channels.value.reduce((t,e)=>t+(e.unread_count||0),0):this.polledUnreadTotal.value),this.connectionBanner=un(()=>{var t=this.connectionState.value;return"suspended"===t?"reconnecting":"failed"===t?"failed":"none"}),this.realtimeReady=un(()=>{var t=this.channel.value;return!!t&&("connected"===this.connectionState.value&&this.realtimeAttached.value&&this.realtimeChannelId.value===t.id)})}setMessages(t){this.messages.value=t}patchChannelSummary(t,e){var n=this.channels.value.findIndex(e=>e.id===t);if(-1!==n){var i=[...this.channels.value];i[n]=h({},i[n],e),i.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.channels.value=i}}prependChannelSummary(t){this.channels.value.some(e=>e.id===t.id)||(this.channels.value=[t,...this.channels.value])}clearActiveChannel(){this.channel.value=null,this.messages.value=[],this.isTyping.value=!1,this.typingSender.value=null,this.typingSenderType.value=null,this.userScrolledUp.value=!1,this.unreadNewMessagesCount.value=0,this.realtimeChannelId.value=null,this.realtimeAttached.value=!1,this.pendingRealtimeChannelId.value=null,this.agentLastReadAt.value=null,this.initialUserReadAt.value=null}prepareChannelSwitch(){this.messages.value=[],this.isTyping.value=!1,this.typingSender.value=null,this.typingSenderType.value=null,this.userScrolledUp.value=!1,this.unreadNewMessagesCount.value=0,this.agentLastReadAt.value=null,this.initialUserReadAt.value=null}cacheMessages(t,e){if(t){var n=e.filter(t=>!t.id.startsWith("temp-"));for(this.A.delete(t),this.A.set(t,n);this.A.size>wn.MESSAGES_CACHE_LIMIT;){var i=this.A.keys().next().value;if(void 0===i)break;this.A.delete(i)}}}getCachedMessages(t){if(!t)return null;var e=this.A.get(t);return e?(this.A.delete(t),this.A.set(t,e),e):null}clearMessagesCache(){this.A.clear()}}wn.MESSAGES_CACHE_LIMIT=10;var xn={bottom:20,right:20,left:20};function _n(t,e){return void 0!==t&&Number.isFinite(t)?Math.max(0,t):e}function kn(t){return null===t?h({},xn):{bottom:_n(null==t?void 0:t.bottom,xn.bottom),right:_n(null==t?void 0:t.right,xn.right),left:_n(null==t?void 0:t.left,xn.left)}}function Sn(t,e,n){t.style.bottom=n.bottom+"px","bottom-right"===e?(t.style.right=n.right+"px",t.style.left=""):(t.style.left=n.left+"px",t.style.right="")}var Cn="vtilt-bubble-pos";function En(t){try{localStorage.setItem(Cn,JSON.stringify(t))}catch(t){}}function Tn(t,e,n){var i=t.getBoundingClientRect(),r=i.left-e,s=i.top-n,o=window.innerWidth-t.offsetWidth-r,a=-r,l=window.innerHeight-t.offsetHeight-s,u=-s;return{x:Math.min(Math.max(e,a),o),y:Math.min(Math.max(n,u),l)}}function An(t,e,n){t.style.transform="translate3d("+e+"px, "+n+"px, 0)"}function In(t,e){var n,i=null!==(n=null==e?void 0:e.handle)&&void 0!==n?n:t,r=null==e?void 0:e.onPositionChange,s=0,o=0,a=0,l=0,u=0,h=0,d=!1,c=!1,v=function(){try{var t=localStorage.getItem(Cn);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(v){s=v.x,o=v.y;var f=t.style.transition;t.style.transition="none",An(t,s,o);var p=Tn(t,s,o);s=p.x,o=p.y,An(t,s,o),t.offsetHeight,t.style.transition=f}i.style.cursor="grab",i.style.touchAction="none";var g=e=>{0===e.button&&(d=!0,c=!1,a=e.clientX,l=e.clientY,u=s,h=o,i.setPointerCapture(e.pointerId),i.style.cursor="grabbing",t.style.transition="none")},m=e=>{if(d){var n=e.clientX-a,i=e.clientY-l;if(!(!c&&Math.abs(n)<5&&Math.abs(i)<5)){c=!0;var v={x:u+n,y:h+i},f=Tn(t,v.x,v.y);s=f.x,o=f.y,An(t,s,o),null==r||r()}}},b=()=>{d&&(d=!1,i.style.cursor="grab",t.style.transition="",c&&(En({x:s,y:o}),null==r||r()))},y=t=>{c&&(t.stopPropagation(),t.preventDefault(),c=!1)},w=()=>{var e=s,n=o,i=Tn(t,s,o);s=i.x,o=i.y,An(t,s,o),e===s&&n===o||En({x:s,y:o}),null==r||r()};return i.addEventListener("pointerdown",g),i.addEventListener("pointermove",m),i.addEventListener("pointerup",b),i.addEventListener("pointercancel",b),i.addEventListener("click",y,!0),window.addEventListener("resize",w),{destroy(){i.removeEventListener("pointerdown",g),i.removeEventListener("pointermove",m),i.removeEventListener("pointerup",b),i.removeEventListener("pointercancel",b),i.removeEventListener("click",y,!0),window.removeEventListener("resize",w)}}}function On(t){var{store:e,controller:n,bubbleRef:i}=t,r=e.unreadCount.value;return re("button",{type:"button",class:"vt-bubble",ref:i,onClick:()=>n.toggle(),"aria-label":"Open chat",children:[re(Ne,{}),re("span",{class:"vt-bubble-badge","data-visible":r>0?"true":"false",children:r>99?"99+":r})]})}function Mn(t){var{channel:e,onSelect:n}=t,i=e.unread_count>0,r=function(t){var e=new Date(t),n=Date.now()-e.getTime(),i=Math.floor(n/6e4),r=Math.floor(n/36e5),s=Math.floor(n/864e5);if(i<1)return"Just now";if(i<60)return i+"m ago";if(r<24)return r+"h ago";if(s<7)return s+"d ago";return e.toLocaleDateString()}(e.last_message_at||e.created_at),s=e.last_message_preview||"No messages yet",o="user"===e.last_message_sender?"You: ":"",a="closed"===e.status?" · Closed":"";return re("button",{type:"button",class:"vt-channel-item","data-channel-id":e.id,onClick:()=>n(e.id),children:[re("div",{class:"vt-channel-avatar","data-mode":e.ai_mode?"ai":"support",children:e.ai_mode?re(Le,{width:24,height:24}):re($e,{width:24,height:24})}),re("div",{class:"vt-channel-body",children:[re("div",{class:"vt-channel-row",children:[re("div",{class:"vt-channel-name","data-unread":i?"true":"false",children:e.ai_mode?"AI Assistant":"Support"}),re("div",{class:"vt-channel-time",children:r})]}),re("div",{class:"vt-channel-row",children:[re("div",{class:"vt-channel-preview","data-unread":i?"true":"false",children:[o,s,a]}),i&&re("div",{class:"vt-channel-unread",children:e.unread_count>99?"99+":e.unread_count})]})]})]})}function Rn(){return re("div",{style:"flex: 1; overflow: hidden;",children:[re(Pn,{}),re(Pn,{}),re(Pn,{}),re(Pn,{})]})}function Pn(){return re("div",{style:"padding: 14px 16px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--vtilt-border-light); background: white;",children:[re("div",{class:"vt-skeleton-circle",style:"width: 48px; height: 48px; flex-shrink: 0;"}),re("div",{style:"flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px;",children:[re("div",{class:"vt-skeleton",style:"height: 12px; width: 40%;"}),re("div",{class:"vt-skeleton",style:"height: 10px; width: 80%;"})]})]})}function Dn(){return re(Ut,{children:[re(Un,{direction:"in",widthPct:62,metaPx:92,height:40}),re(Un,{direction:"out",widthPct:42,metaPx:56,height:40}),re(Un,{direction:"in",widthPct:78,metaPx:76,height:60})]})}function Un(t){var{direction:e,widthPct:n,metaPx:i,height:r}=t;return re("div","in"===e?{style:"display: flex; gap: 10px; align-items: flex-end;",children:[re("div",{class:"vt-skeleton-circle",style:"width: 32px; height: 32px; flex-shrink: 0;"}),re("div",{style:"display: flex; flex-direction: column; align-items: flex-start; min-width: 0; max-width: 85%;",children:[re("div",{class:"vt-skeleton",style:"width: "+n+"%; min-width: 96px; height: "+r+"px; border-radius: 20px 20px 20px 4px;"}),re("div",{class:"vt-skeleton",style:"height: 10px; width: "+i+"px; margin-top: 8px; margin-left: 6px; border-radius: 4px;"})]})]}:{style:"display: flex; flex-direction: column; align-items: flex-end;",children:[re("div",{class:"vt-skeleton",style:"width: "+n+"%; min-width: 80px; max-width: 80%; height: "+r+"px; border-radius: 20px 20px 4px 20px;"}),re("div",{class:"vt-skeleton",style:"height: 10px; width: "+i+"px; margin-top: 8px; margin-right: 6px; border-radius: 4px;"})]})}function jn(t){var{store:e,controller:n}=t,i=e.channels.value,r=e.isLoading.value;return 0===i.length&&r?re(Rn,{}):0===i.length?re(Bn,{controller:n}):re(Ut,{children:[re("div",{class:"vt-list-root",children:i.map(t=>re(Mn,{channel:t,onSelect:t=>{n.selectChannel(t)}},t.id))}),re("div",{class:"vt-list-footer",children:re("button",{type:"button",class:"vt-new-channel-btn",onClick:()=>{n.createChannel()},children:["Send us a message",re(Be,{width:18,height:18})]})})]})}function Bn(t){var{controller:e}=t,n=e.config.greeting||"Hi! How can we help you today?";return re("div",{class:"vt-list-empty",children:[re("div",{class:"vt-list-empty-icon",children:re(ze,{})}),re("div",{class:"vt-list-empty-title",children:n}),re("div",{class:"vt-list-empty-subtitle",children:"Start a conversation with us"}),re("button",{type:"button",class:"vt-new-channel-btn",style:"width: auto; padding: 14px 28px;",onClick:()=>{e.createChannel()},children:["Send us a message",re(Be,{width:18,height:18})]})]})}function Nn(t){var e,n,i,{store:r,controller:s}=t;if("list"===r.currentView.value)return re("div",{class:"vt-header","data-view":"list",children:[re("div",{class:"vt-header-title",children:"Messages"}),re("button",{type:"button",class:"vt-iconbtn vt-header-close",onClick:()=>s.close(),"aria-label":"Close",children:re(Ue,{})})]});var o=null===(i=null!==(n=null===(e=r.channel.value)||void 0===e?void 0:e.ai_mode)&&void 0!==n?n:s.config.aiMode)||void 0===i||i;return re("div",{class:"vt-header","data-view":"conversation",children:[re("button",{type:"button",class:"vt-iconbtn vt-header-back",onClick:()=>s.goToChannelList(),"aria-label":"Back",children:re(je,{})}),re("div",{class:"vt-header-avatar","data-mode":o?"ai":"support",children:re(o?Le:$e,{})}),re("div",{class:"vt-header-info",children:[re("div",{class:"vt-header-name",children:o?"AI Assistant":"Support"}),re("div",{class:"vt-header-status",children:"Online"})]}),re("button",{type:"button",class:"vt-iconbtn vt-header-close",onClick:()=>s.close(),"aria-label":"Close",children:re(Ue,{})})]})}function Ln(){return re("div",{class:"vt-closed-banner",children:"This conversation has been closed."})}function $n(t){var{store:e}=t,n=e.connectionBanner.value,i=function(t,e){var[n,i]=ye(!1);return we(()=>{if(t){var n=setTimeout(()=>i(!0),e);return()=>clearTimeout(n)}i(!1)},[t,e]),n}("reconnecting"===n,2500),r=ke(()=>{"undefined"!=typeof window&&window.location.reload()},[]);return"failed"===n?re("div",{class:"vt-conn-banner","data-kind":"failed",role:"alert",children:[re("span",{class:"vt-conn-banner-icon","aria-hidden":"true",children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[re("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"}),re("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),re("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}),re("span",{class:"vt-conn-banner-text",children:"Connection lost"}),re("button",{type:"button",class:"vt-conn-banner-action",onClick:r,children:"Retry"})]}):i?re("div",{class:"vt-conn-banner","data-kind":"reconnecting",role:"status",children:[re("span",{class:"vt-conn-banner-dot","aria-hidden":"true"}),re("span",{class:"vt-conn-banner-text",children:"Reconnecting"})]}):null}function zn(t){var{store:e,controller:n}=t,[i,r]=ye(""),s=xe(null),o=null==e.channel.value,a=()=>{var t=i.trim();t&&(n.stopUserTyping(),n.sendMessage(t),r(""),s.current&&(s.current.style.height="",s.current.focus()))};return we(()=>{s.current&&function(t){t.style.height="auto";var e=120,n=60;t.style.height=Math.min(Math.max(t.scrollHeight,n),e)+"px"}(s.current)},[i]),re("div",{class:"vt-input-container","data-pending":o?"true":"false",children:re("div",{class:"vt-input-box",children:[re("textarea",{class:"vt-input-textarea",ref:s,rows:1,placeholder:o?"Starting conversation…":"Message...",autocomplete:"off",autocorrect:"on",autocapitalize:"sentences",disabled:o,value:i,onInput:t=>{var e=t.currentTarget.value;r(e),n.notifyUserTyping()},onBlur:()=>{n.stopUserTyping()},onKeyDown:t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),a())}}),re("button",{type:"button",class:"vt-input-send","data-active":i.trim().length>0?"true":"false",disabled:0===i.trim().length||o,onClick:a,"aria-label":"Send message",children:re(Be,{})})]})})}function qn(t,e){for(var n in t)if("__source"!==n&&!(n in e))return!0;for(var i in e)if("__source"!==i&&t[i]!==e[i])return!0;return!1}function Fn(t,e){this.props=t,this.context=e}function Hn(t,e){function n(t){var n=this.props.ref;return n!=t.ref&&n&&("function"==typeof n?n(null):n.current=null),e?!e(this.props,t)||n!=t.ref:qn(this.props,t)}function i(e){return this.shouldComponentUpdate=n,Pt(t,e)}return i.displayName="Memo("+(t.displayName||t.name)+")",i.__f=i.prototype.isReactComponent=!0,i.type=t,i}(Fn.prototype=new jt).isPureReactComponent=!0,Fn.prototype.shouldComponentUpdate=function(t,e){return qn(this.props,t)||qn(this.state,e)};var Wn=vt.__b;vt.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Wn&&Wn(t)};var Jn=vt.__e;vt.__e=function(t,e,n,i){if(t.then)for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return null==e.__e&&(e.__e=n.__e,e.__k=n.__k),r.__c(t,e);Jn(t,e,n,i)};var Vn=vt.unmount;function Kn(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(t){"function"==typeof t.__c&&t.__c()}),t.__c.__H=null),null!=(t=function(t,e){for(var n in e)t[n]=e[n];return t}({},t)).__c&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(t){return Kn(t,e,n)})),t}function Gn(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(t){return Gn(t,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function Xn(){this.__u=0,this.o=null,this.__b=null}function Qn(t){var e=t.__&&t.__.__c;return e&&e.__a&&e.__a(t)}function Zn(){this.i=null,this.l=null}vt.unmount=function(t){var e=t.__c;e&&(e.__z=!0),e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Vn&&Vn(t)},(Xn.prototype=new jt).__c=function(t,e){var n=e.__c,i=this;null==i.o&&(i.o=[]),i.o.push(n);var r=Qn(i.__v),s=!1,o=function(){s||i.__z||(s=!0,n.__R=null,r?r(l):l())};n.__R=o;var a=n.__P;n.__P=null;var l=function(){if(! --i.__u){if(i.state.__a){var t=i.state.__a;i.__v.__k[0]=Gn(t,t.__c.__P,t.__c.__O)}var e;for(i.setState({__a:i.__b=null});e=i.o.pop();)e.__P=a,e.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(o,o)},Xn.prototype.componentWillUnmount=function(){this.o=[]},Xn.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Kn(this.__b,n,i.__O=i.__P)}this.__b=null}var r=e.__a&&Pt(Ut,null,t.fallback);return r&&(r.__u&=-33),[Pt(Ut,null,e.__a?null:t.children),r]};var Yn=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&("t"!==t.props.revealOrder[0]||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};(Zn.prototype=new jt).__a=function(t){var e=this,n=Qn(e.__v),i=e.l.get(t);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Yn(e,t,i)):r()};n?n(s):s()}},Zn.prototype.render=function(t){this.i=null,this.l=new Map;var e=Ft(t.children);t.revealOrder&&"b"===t.revealOrder[0]&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},Zn.prototype.componentDidUpdate=Zn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Yn(t,n,e)})};var ti="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,ei=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,ni=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ii=/[A-Z0-9]/g,ri="undefined"!=typeof document,si=function(t){return("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(t)};jt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(jt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var oi=vt.event;vt.event=function(t){return oi&&(t=oi(t)),t.persist=function(){},t.isPropagationStopped=function(){return this.cancelBubble},t.isDefaultPrevented=function(){return this.defaultPrevented},t.nativeEvent=t};var ai={configurable:!0,get:function(){return this.class}},li=vt.vnode;vt.vnode=function(t){"string"==typeof t.type&&function(t){var e=t.props,n=t.type,i={},r=-1==n.indexOf("-");for(var s in e){var o=e[s];if(!("value"===s&&"defaultValue"in e&&null==o||ri&&"children"===s&&"noscript"===n||"class"===s||"className"===s)){var a=s.toLowerCase();"defaultValue"===s&&"value"in e&&null==e.value?s="value":"download"===s&&!0===o?o="":"translate"===a&&"no"===o?o=!1:"o"===a[0]&&"n"===a[1]?"ondoubleclick"===a?s="ondblclick":"onchange"!==a||"input"!==n&&"textarea"!==n||si(e.type)?"onfocus"===a?s="onfocusin":"onblur"===a?s="onfocusout":ni.test(s)&&(s=a):a=s="oninput":r&&ei.test(s)?s=s.replace(ii,"-$&").toLowerCase():null===o&&(o=void 0),"oninput"===a&&i[s=a]&&(s="oninputCapture"),i[s]=o}}"select"==n&&(i.multiple&&Array.isArray(i.value)&&(i.value=Ft(e.children).forEach(function(t){t.props.selected=-1!=i.value.indexOf(t.props.value)})),null!=i.defaultValue&&(i.value=Ft(e.children).forEach(function(t){t.props.selected=i.multiple?-1!=i.defaultValue.indexOf(t.props.value):i.defaultValue==t.props.value}))),e.class&&!e.className?(i.class=e.class,Object.defineProperty(i,"className",ai)):e.className&&(i.class=i.className=e.className),t.props=i}(t),t.$$typeof=ti,li&&li(t)};var ui=vt.__r;vt.__r=function(t){ui&&ui(t),t.__c};var hi=vt.diffed;function di(t,e){var n=Date.parse(t.created_at),i=Date.parse(e.created_at);return n!==i?n-i:t.id.localeCompare(e.id)}function ci(t,e){return function(t){return t.length<2?t:[...t].sort(di)}([...t,e])}vt.diffed=function(t){hi&&hi(t);var e=t.props,n=t.__e;null!=n&&"textarea"===t.type&&"value"in e&&e.value!==n.value&&(n.value=null==e.value?"":e.value)};var vi="chat.stream",fi=/<!--vtilt:widget:([\s\S]*?)-->/g;function pi(t){for(var e,n,i=[],r=new RegExp(fi.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}function gi(t){return mi.apply(this,arguments)}function mi(){return mi=u(function*(t){var e,n,i,{store:r,response:s,channelId:o,tempId:a,signal:l,isActive:u,onStreamStart:d,onComplete:c}=t,v=()=>{var t;return!(null==l?void 0:l.aborted)&&(null===(t=null==u?void 0:u())||void 0===t||t)},f=s.headers.get("X-Vtilt-Message-Id"),p=s.headers.get("X-Vtilt-Message-Created-At"),g=null!==(e=null!=a?a:f)&&void 0!==e?e:"temp-ai-"+Date.now();if(v()&&(null==d||d(g),v())){var m={id:g,channel_id:o,sender_type:"ai",sender_id:null,sender_name:"AI Assistant",sender_avatar_url:null,content:"",content_type:"text",metadata:{},created_at:null!=p?p:(new Date).toISOString()};r.setMessages(ci(r.messages.value,m));var b=null===(n=s.body)||void 0===n?void 0:n.getReader();if(!b)return T().error(vi,"no response body reader available"),void bi(r,g);var y=new TextDecoder,w="",x=null,_=!0,k=()=>{if(v()){var t=r.messages.value.findIndex(t=>t.id===g);if(-1!==t){var e=[...r.messages.value];e[t]=h({},e[t],{content:w.replace(/<[^>]*$/,"")}),r.setMessages(e)}}else bi(r,g)},S=()=>{null===x&&(x=requestAnimationFrame(()=>{k(),x=null}))};try{for(;;){if(!v())return void bi(r,g);var{done:C,value:E}=yield b.read();if(C)break;var A=y.decode(E,{stream:!0});w+=A,_?(_=!1,k()):S()}if(!v())return void bi(r,g);null!==x&&(cancelAnimationFrame(x),x=null),k();var I=r.messages.value.findIndex(t=>t.id===g);if(-1!==I){var O=pi(w),M=[...r.messages.value],R=h({},null!==(i=M[I].metadata)&&void 0!==i?i:{});O.length>0&&(R.T=O),M[I]=h({},M[I],{content:w,metadata:R}),r.setMessages(M)}null==c||c(g)}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return void bi(r,g);T().error(vi,"failed to handle streaming response:",t),bi(r,g)}finally{b.releaseLock(),null!==x&&cancelAnimationFrame(x)}}}),mi.apply(this,arguments)}function bi(t,e){var n=t.messages.value.filter(t=>t.id!==e);n.length!==t.messages.value.length&&t.setMessages(n)}var yi=/<(?:p|ul|ol|li|h[1-6]|br|div|pre|blockquote)\b/i,wi=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 xi(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>')}function _i(t,e){for(var n=Array.from(t.children),i=0;i<n.length;){var r=n[i];if("LI"!==r.tagName)_i(r,e),i++;else{for(var s=[],o=i;o<n.length&&"LI"===n[o].tagName;)s.push(n[o]),o++;var a=e.createElement("ul");for(var l of(t.insertBefore(a,s[0]),s))a.appendChild(l);i=o}}}function ki(t,e){if(void 0===e&&(e="text"),!t)return"";var n=t.trim();if(!n)return"";if("undefined"==typeof document)return n;var i,r,s=function(t,e){return"html"!==t&&!yi.test(e)}(e,n)?function(t){if(!t||yi.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 o=s[1].length;n.push("<h"+o+">"+xi(s[2])+"</h"+o+">"),i++}else if(/^[-*]\s+/.test(r)){for(var a=[];i<e.length&&/^[-*]\s+/.test(e[i]);)a.push("<li>"+xi(e[i].replace(/^[-*]\s+/,""))+"</li>"),i++;n.push("<ul>"+a.join("")+"</ul>")}else if(/^\d+\.\s+/.test(r)){for(var l=[];i<e.length&&/^\d+\.\s+/.test(e[i]);)l.push("<li>"+xi(e[i].replace(/^\d+\.\s+/,""))+"</li>"),i++;n.push("<ol>"+l.join("")+"</ol>")}else if(""!==r.trim()){for(var u=[];i<e.length&&""!==e[i].trim()&&!/^#{1,6}\s/.test(e[i])&&!/^[-*]\s+/.test(e[i])&&!/^\d+\.\s+/.test(e[i]);)u.push(xi(e[i])),i++;n.push("<p>"+u.join("<br>")+"</p>")}else i++}return n.join("")}(n):n,o=document.createElement("div");return o.innerHTML=s,i=document,(r=t=>{for(var e of Array.from(t.children))if(wi.has(e.tagName)){for(var n of Array.from(e.attributes))"A"===e.tagName&&"href"===n.name||e.removeAttribute(n.name);"A"===e.tagName&&(e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")),r(e)}else e.replaceWith(i.createTextNode(e.textContent||""))})(o),_i(o,document),o.innerHTML}var Si=Hn(function(t){var{message:e,controller:n}=t,i=function(t){var e,n=null!==(e=t.metadata)&&void 0!==e?e:{},i=n.T;i&&0!==i.length||(i=n.widgets);i&&0!==i.length||!t.content||(i=pi(t.content));return null!=i?i:[]}(e);return 0===i.length?null:re(Ut,{children:i.map((t,i)=>{if(t.submitted)return re(Ci,{widget:t},i);var r=n.widgets.get(t.type);if(!r)return null;var s=n.getWidgetContext(e.id,t.type);return re("div",{children:r.render(t.params,s)},i)})})},(t,e)=>t.message===e.message&&t.controller===e.controller);function Ci(t){var e,n,{widget:i}=t;if("collect_email"===i.type){var r=null!==(e=i.submittedEmail)&&void 0!==e?e:"",s=null!==(n=i.submittedName)&&void 0!==n?n:"";return re("div",{class:"vt-widget",children:re("p",{class:"vt-widget-thanks",children:s?"✓ Thanks, "+s+"! We'll follow up at "+r+".":r?"✓ Thanks! We'll follow up at "+r+".":"✓ Thanks!"})})}return"escalate_to_human"===i.type?re("div",{class:"vt-widget",children:re("p",{class:"vt-widget-thanks",children:"✓ A team member has been notified. They'll join shortly."})}):re("div",{class:"vt-widget",children:re("p",{class:"vt-widget-thanks",children:"✓ Done"})})}var Ei=Hn(function(t){var{message:e,controller:n,isReadByAgent:i}=t,r="user"===e.sender_type?"out":"in",s=_e(()=>function(t){if("user"===t.sender_type)return"";if("ai"===t.sender_type)return"AI Assistant";return t.sender_name||"Agent"}(e),[e.sender_type,e.sender_name]);return re("div",{class:"vt-message","data-direction":r,children:[re("div",{class:"vt-message-row",children:["in"===r&&re(Ai,{senderType:e.sender_type}),re(Ti,{message:e})]}),re(Si,{message:e,controller:n}),re("div",{class:"vt-message-meta",children:[s?re("span",{children:s}):null,s?re("span",{children:" · "}):null,re("time",{children:Oi(e.created_at)}),"out"===r?re(Ii,{message:e,controller:n}):null,"out"===r&&i?re("span",{children:" · Read"}):null]})]})},(t,e)=>t.message===e.message&&t.message.delivery_status===e.message.delivery_status&&t.controller===e.controller&&t.isReadByAgent===e.isReadByAgent);function Ti(t){var e,{message:n}=t,i=(null!==(e=n.content)&&void 0!==e?e:"").replace(fi,"").trim();if(!i)return re("div",{class:"vt-message-bubble"});if(!lt(n))return re("div",{class:"vt-message-bubble",children:i});var r=ki(i,n.content_type);return re("div",{class:"vt-message-bubble",children:re("div",{class:"vt-md"+("user"===n.sender_type?" vt-user-md":""),dangerouslySetInnerHTML:{__html:r}})})}function Ai(t){var{senderType:e}=t,n="ai"===e;return re("div",{class:"vt-message-avatar","data-mode":n?"ai":"support",children:re(n?Le:$e,{width:16,height:16})})}function Ii(t){var{message:e,controller:n}=t,i=e.delivery_status;return i?re("span","pending"===i||"sending"===i?{children:" · Sending…"}:{children:[" · ",re("button",{type:"button",class:"vt-message-retry",onClick:()=>n.retryFailedMessage(e.id),children:"Failed — tap to retry"})]}):null}function Oi(t){if(!t)return"";var e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Mi(t){var{senderType:e,senderName:n}=t,i="ai"===e,r=i?"AI Assistant":n||"Agent";return re("div",{class:"vt-message","data-direction":"in","data-typing":"true",children:[re("div",{class:"vt-message-row",children:[re("div",{class:"vt-message-avatar","data-mode":i?"ai":"support",children:re(i?Le:$e,{width:16,height:16})}),re("div",{class:"vt-message-bubble","data-typing":"true","aria-label":r+" is typing",children:[re("span",{class:"vt-typing-dot"}),re("span",{class:"vt-typing-dot"}),re("span",{class:"vt-typing-dot"})]})]}),re("div",{class:"vt-message-meta",children:re("span",{children:r})})]})}function Ri(t){var{count:e,visible:n,onJump:i}=t;return re("button",{type:"button",class:"vt-new-pill","data-visible":n&&e>0?"true":"false","aria-label":"Jump to latest messages",onClick:i,children:re("span",{children:e>1?"↓ "+e+" new messages":"↓ 1 new message"})})}function Pi(t){var{store:e,scrollRef:n,messages:i,typingActive:r=!1}=t,s=xe(null),o=xe(0);return we(()=>{var t=n.current;if(t){var i=()=>{t.scrollHeight-t.scrollTop-t.clientHeight<80?e.userScrolledUp.value&&(e.userScrolledUp.value=!1,e.unreadNewMessagesCount.value=0):e.userScrolledUp.value||(e.userScrolledUp.value=!0)};return t.addEventListener("scroll",i,{passive:!0}),()=>t.removeEventListener("scroll",i)}},[n.current]),we(()=>{var t,r,a,l=n.current;if(l){var u=null!==(t=i[i.length-1])&&void 0!==t?t:null;if(u){var h=u.id,d=null!==(a=null===(r=u.content)||void 0===r?void 0:r.length)&&void 0!==a?a:0,c=h!==s.current,v=!c&&"ai"===u.sender_type&&d>o.current;if(c||v)if(s.current=h,o.current=d,c){if("user"===u.sender_type)return l.scrollTop=l.scrollHeight,e.userScrolledUp.value=!1,void(e.unreadNewMessagesCount.value=0);var f=l.scrollHeight-l.scrollTop-l.clientHeight<80;!e.userScrolledUp.value||f?l.scrollTop=l.scrollHeight:"agent"!==u.sender_type&&"ai"!==u.sender_type||(e.unreadNewMessagesCount.value=e.unreadNewMessagesCount.value+1)}else(t=>{var n=t.scrollHeight-t.scrollTop-t.clientHeight<80;e.userScrolledUp.value&&!n||(t.scrollTop=t.scrollHeight)})(l)}}},[i,n.current]),we(()=>{if(r){var t=n.current;if(t){var i=t.scrollHeight-t.scrollTop-t.clientHeight<80;e.userScrolledUp.value&&!i||(t.scrollTop=t.scrollHeight)}}},[r,n.current]),{jumpToBottom:()=>{var t=n.current;t&&(t.scrollTop=t.scrollHeight,e.userScrolledUp.value=!1,e.unreadNewMessagesCount.value=0)}}}function Di(t){var{store:e,controller:n}=t,i=xe(null),r=e.messages.value,s=e.channel.value,o=e.agentLastReadAt.value,a=e.isTyping.value,l=e.typingSenderType.value,u=e.typingSender.value,{jumpToBottom:h}=Pi({store:e,scrollRef:i,messages:r,typingActive:a});!function(t){var e,n,i,{store:r,controller:s,messages:o}=t;we(()=>{if(r.isOpen.value&&"conversation"===r.currentView.value&&r.channel.value){var t=setTimeout(()=>s.markAsRead(),80);return()=>clearTimeout(t)}},[null!==(n=null===(e=o[o.length-1])||void 0===e?void 0:e.id)&&void 0!==n?n:null,r.isOpen.value,r.currentView.value,null===(i=r.channel.value)||void 0===i?void 0:i.id])}({store:e,controller:n,messages:r});var d=!s&&e.isLoading.value&&0===r.length,c=!!s&&e.isLoading.value&&0===r.length,v=a&&("ai"===l||"agent"===l);return re("div",{class:"vt-messages-wrapper",children:[re("div",{class:"vt-messages",ref:i,children:d?re(Mi,{senderType:!1===n.config.aiMode?"agent":"ai"}):c?re(Dn,{}):re(Ut,{children:[r.map(t=>{return re(Ei,{message:t,controller:n,isReadByAgent:(e=t.created_at,!!o&&new Date(e)<=new Date(o))},t.id);var e}),v&&re(Mi,{senderType:l,senderName:u})]})}),re(Ri,{count:e.unreadNewMessagesCount.value,visible:e.userScrolledUp.value,onJump:h})]})}function Ui(t){var e,{store:n,controller:i}=t,r="closed"===(null===(e=n.channel.value)||void 0===e?void 0:e.status);return re(Ut,{children:[re(Di,{store:n,controller:i}),re($n,{store:n}),r?re(Ln,{}):re(zn,{store:n,controller:i})]})}function ji(t){var{store:e,controller:n}=t,i=e.currentView.value;return re("div",{class:"vt-panel vt-opening",children:[re(Nn,{store:e,controller:n}),re("div",{class:"vt-content",children:re("list"===i?jn:Ui,{store:e,controller:n})})]})}var Bi="vtilt-chat-font";function Ni(t){!function(){if("undefined"!=typeof document&&!document.getElementById(Bi)){var t=document.createElement("link");t.rel="preconnect",t.href="https://fonts.gstatic.com",t.crossOrigin="anonymous",document.head.appendChild(t);var e=document.createElement("link");e.id=Bi,e.rel="stylesheet",e.href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap",document.head.appendChild(e)}}();var e=document.createElement("div");e.id="vtilt-chat-host",e.style.cssText="all: initial; position: fixed; inset: auto; z-index: 999999; pointer-events: none;",document.body.appendChild(e);var n=e.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent='\n/* Load Inter so the widget looks like vTilt on every host page. The @import\n sits at the very top of the stylesheet (required by the spec) and only\n fetches the variable-axis subset we need. If the host\'s CSP blocks Google\n Fonts the font-family fallback chain below keeps the widget legible. */\n@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap");\n\n:host {\n --vtilt-primary: #7B68EE;\n --vtilt-primary-shadow: rgba(123, 104, 238, 0.4);\n --vtilt-font: "Inter var", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n --vtilt-radius: 16px;\n --vtilt-text: #000000;\n --vtilt-text-muted: #666666;\n --vtilt-text-subtle: #888888;\n --vtilt-bg: #ffffff;\n --vtilt-bg-list: #FAFAFA;\n --vtilt-border: #E5E5E5;\n --vtilt-border-light: #EEEEEE;\n --vtilt-skeleton: #E8E8EA;\n --vtilt-online: #16A34A;\n\n all: initial;\n font-family: var(--vtilt-font);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n color: var(--vtilt-text);\n}\n\n*, *::before, *::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n}\n\nbutton {\n font-family: inherit;\n cursor: pointer;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n}\n\n/* =========================================================================\n * Container + bubble + panel\n * ========================================================================= */\n\n/* The host element gets \'all: initial\' inline (set in ChatRoot.tsx) so the\n host page can\'t position or style it. Inline styles win over \':host\' rules\n in the cascade, so the host\'s effective font-family / color end up at the\n UA default — and shadow children inherit from there. We re-establish the\n widget typography on .vt-container (which lives *inside* the shadow tree)\n so every descendant inherits Inter + the themed text color, regardless of\n what the host page or the host element\'s inline reset look like. */\n.vt-container {\n position: fixed;\n bottom: var(--vt-bubble-offset-bottom, 20px);\n /* Pin the container to the bubble\'s intrinsic size so it keeps the\n * same bounding box even after the bubble itself goes display:none on\n * open. Without this the container collapses to 0x0 and the absolutely\n * positioned panel anchors at that zero-size point — which means the\n * opened panel no longer overlaps the bubble\'s last visible footprint\n * for any non-default anchor (e.g. a bubble dragged to the bottom-left\n * with data-position="bottom-right" would see the panel jump 60px away\n * from where the bubble had been). With a fixed container size, the\n * panel\'s [data-panel-anchor] corner always coincides with the matching\n * corner of the bubble, regardless of drag offset. */\n width: 60px;\n height: 60px;\n z-index: 999999;\n font-family: var(--vtilt-font);\n font-size: 14px;\n line-height: 1.4;\n color: var(--vtilt-text);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.vt-container[data-position="bottom-right"] {\n right: var(--vt-bubble-offset-right, 20px);\n}\n.vt-container[data-position="bottom-left"] {\n left: var(--vt-bubble-offset-left, 20px);\n}\n.vt-container[data-hidden="true"] { display: none; }\n\n.vt-bubble {\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 16px var(--vtilt-primary-shadow);\n transition: transform 0.15s ease, box-shadow 0.15s ease;\n position: relative;\n border: none;\n}\n.vt-bubble:hover { transform: scale(1.05); box-shadow: 0 6px 20px var(--vtilt-primary-shadow); }\n.vt-bubble:active { transform: scale(0.95); }\n.vt-container[data-open="true"] .vt-bubble { display: none; }\n.vt-container[data-draggable="true"] .vt-bubble:hover,\n.vt-container[data-draggable="true"] .vt-bubble:active { transform: none; }\n\n.vt-bubble-badge {\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 border: 2px solid white;\n}\n.vt-bubble-badge[data-visible="true"] { display: flex; }\n\n/* Panel position is driven by [data-panel-anchor] on the container.\n * The chat widget recomputes the anchor from the bubble\'s actual viewport\n * position (see usePanelAnchor in ui/ChatRoot.tsx) so the panel always\n * extends into whichever side has more room — even after the bubble has\n * been dragged across the viewport. The default anchor (no attribute) is\n * "bottom-right" so the very first paint, before JS has computed the\n * anchor, matches the most common default position.\n *\n * Per-anchor max-width / max-height are exposed as the CSS variables\n * --vt-panel-max-w and --vt-panel-max-h. JS sets them to the available\n * room from the chosen anchor (capped by the panel\'s intrinsic 380x600\n * design size), so on small or oddly-shaped viewports the panel never\n * overruns the opposite edge. The min(...) wrapper falls back to the\n * original "viewport minus 40px" formula when the variables aren\'t set. */\n.vt-panel {\n display: none;\n flex-direction: column;\n position: absolute;\n bottom: 0;\n right: 0;\n width: 380px;\n height: 600px;\n /* Effective size = min(intrinsic, room-from-anchor, viewport-minus-margin).\n * The viewport term is a backstop: while the chat is open we deliberately\n * freeze the per-anchor variable, so a viewport resize during open could\n * otherwise leave a stale value that overruns the opposite edge. */\n max-width: min(380px, var(--vt-panel-max-w, calc(100vw - 40px)), calc(100vw - 40px));\n max-height: min(600px, var(--vt-panel-max-h, calc(100vh - 40px)), calc(100vh - 40px));\n max-height: min(600px, var(--vt-panel-max-h, calc(100dvh - 40px)), calc(100dvh - 40px));\n background: var(--vtilt-bg);\n border-radius: var(--vtilt-radius);\n box-shadow: 0 5px 40px rgba(0, 0, 0, 0.16);\n overflow: hidden;\n}\n.vt-container[data-panel-anchor="bottom-left"] .vt-panel { right: auto; left: 0; }\n.vt-container[data-panel-anchor="top-right"] .vt-panel { bottom: auto; top: 0; }\n.vt-container[data-panel-anchor="top-left"] .vt-panel { bottom: auto; top: 0; right: auto; left: 0; }\n.vt-container[data-open="true"] .vt-panel { display: flex; }\n.vt-container[data-open="true"] .vt-panel.vt-opening {\n animation: vt-open 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards;\n /* The animation scales from 0.4 to 1; transform-origin decides which\n * corner of the panel that scale grows from. JS sets --vt-panel-origin\n * to the same corner usePanelAnchor picked for [data-panel-anchor], so\n * the panel always appears to "pop" out of the bubble. The fallback\n * matches the default bottom-right anchor used before JS computes a\n * direction (or in environments where the variable isn\'t set). */\n transform-origin: var(--vt-panel-origin, bottom right);\n}\n\n@keyframes vt-open {\n from { opacity: 0; transform: scale(0.4); }\n to { opacity: 1; transform: scale(1); }\n}\n\n/* =========================================================================\n * Header\n * ========================================================================= */\n\n.vt-header {\n background: var(--vtilt-bg);\n border-bottom: 1px solid var(--vtilt-border);\n padding: 18px 16px;\n padding-top: max(18px, env(safe-area-inset-top, 18px));\n display: flex;\n align-items: center;\n min-height: 60px;\n flex-shrink: 0;\n gap: 12px;\n}\n.vt-header[data-view="list"] {\n justify-content: space-between;\n}\n.vt-header[data-view="conversation"] {\n padding: 12px 16px;\n padding-top: max(12px, env(safe-area-inset-top, 12px));\n}\n\n.vt-header-title { font-weight: 600; font-size: 17px; color: var(--vtilt-text); }\n.vt-header-info { flex: 1; min-width: 0; }\n.vt-header-name { font-weight: 600; font-size: 16px; color: var(--vtilt-text); }\n.vt-header-status {\n font-size: 13px;\n color: var(--vtilt-online);\n display: flex;\n align-items: center;\n gap: 5px;\n margin-top: 1px;\n}\n.vt-header-status::before {\n content: "";\n width: 7px;\n height: 7px;\n background: var(--vtilt-online);\n border-radius: 50%;\n}\n\n.vt-iconbtn {\n background: transparent;\n border: none;\n color: var(--vtilt-text-muted);\n padding: 6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n}\n.vt-iconbtn:hover { color: var(--vtilt-text); background: #F0F0F0; }\n.vt-header-back { margin-left: -6px; }\n.vt-header-close { margin-right: -6px; }\n\n.vt-header-avatar {\n width: 44px;\n height: 44px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n color: white;\n}\n.vt-header-avatar[data-mode="support"] { background: #DEDEDE; color: #666; }\n\n/* =========================================================================\n * Content area (channel list, conversation)\n * ========================================================================= */\n\n.vt-content {\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n min-height: 0;\n background: var(--vtilt-bg);\n}\n\n/* Channel list ----------------------------------------------------------- */\n\n.vt-list-root {\n flex: 1;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n}\n\n.vt-list-empty {\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.vt-list-empty-icon {\n width: 72px;\n height: 72px;\n margin-bottom: 24px;\n background: var(--vtilt-primary);\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.vt-list-empty-title {\n font-size: 18px;\n font-weight: 600;\n color: var(--vtilt-text);\n margin-bottom: 12px;\n line-height: 1.4;\n max-width: 280px;\n}\n.vt-list-empty-subtitle {\n font-size: 14px;\n color: var(--vtilt-text-muted);\n margin-bottom: 28px;\n}\n\n.vt-channel-item {\n padding: 14px 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--vtilt-bg);\n border: none;\n width: 100%;\n text-align: left;\n border-bottom: 1px solid var(--vtilt-border-light);\n transition: background 0.1s ease;\n font: inherit;\n color: inherit;\n}\n.vt-channel-item:hover { background: #F5F5F5; }\n.vt-channel-item:active { background: #EBEBEB; }\n\n.vt-channel-avatar {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n color: white;\n}\n.vt-channel-avatar[data-mode="support"] { background: #DEDEDE; color: #666; }\n\n.vt-channel-body { flex: 1; min-width: 0; }\n.vt-channel-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n margin-bottom: 4px;\n}\n.vt-channel-name {\n font-weight: 500;\n font-size: 15px;\n color: var(--vtilt-text);\n line-height: 1.2;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.vt-channel-name[data-unread="true"] { font-weight: 600; }\n.vt-channel-time {\n font-size: 13px;\n color: var(--vtilt-text-subtle);\n white-space: nowrap;\n flex-shrink: 0;\n}\n.vt-channel-preview {\n font-size: 14px;\n color: var(--vtilt-text-subtle);\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}\n.vt-channel-preview[data-unread="true"] { color: #333; }\n.vt-channel-unread {\n min-width: 20px;\n height: 20px;\n padding: 0 6px;\n background: var(--vtilt-primary);\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}\n\n.vt-list-footer {\n padding: 16px;\n padding-bottom: max(16px, env(safe-area-inset-bottom, 16px));\n border-top: 1px solid var(--vtilt-border);\n}\n\n.vt-new-channel-btn {\n width: 100%;\n background: var(--vtilt-primary);\n color: white;\n border: none;\n border-radius: 100px;\n padding: 14px 24px;\n font-weight: 500;\n font-size: 15px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n box-shadow: 0 2px 8px var(--vtilt-primary-shadow);\n transition: opacity 0.1s ease;\n}\n.vt-new-channel-btn:hover { opacity: 0.9; }\n.vt-new-channel-btn:active { opacity: 0.8; }\n\n/* Conversation ----------------------------------------------------------- */\n\n.vt-messages-wrapper {\n position: relative;\n flex: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n}\n\n.vt-messages {\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: var(--vtilt-bg-list);\n}\n\n.vt-message {\n display: flex;\n flex-direction: column;\n animation: vt-message-in 0.22s ease-out both;\n}\n.vt-message[data-direction="in"] { align-items: flex-start; }\n.vt-message[data-direction="out"] { align-items: flex-end; }\n\n.vt-message-row {\n display: flex;\n gap: 10px;\n align-items: flex-end;\n max-width: 85%;\n}\n.vt-message[data-direction="out"] .vt-message-row {\n flex-direction: row-reverse;\n}\n\n.vt-message-avatar {\n width: 32px;\n height: 32px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n color: white;\n}\n.vt-message-avatar[data-mode="support"] { background: #DEDEDE; color: #666; }\n\n.vt-message-bubble {\n padding: 10px 14px;\n background: var(--vtilt-bg);\n border-radius: 20px 20px 20px 4px;\n font-size: 14px;\n line-height: 1.4;\n color: var(--vtilt-text);\n word-wrap: break-word;\n overflow-wrap: anywhere;\n min-width: 0;\n}\n.vt-message[data-direction="out"] .vt-message-bubble {\n background: var(--vtilt-primary);\n color: white;\n border-radius: 20px 20px 4px 20px;\n}\n\n.vt-message-meta {\n font-size: 12px;\n color: var(--vtilt-text-subtle);\n margin-top: 6px;\n}\n.vt-message[data-direction="in"] .vt-message-meta { margin-left: 46px; }\n.vt-message[data-direction="out"] .vt-message-meta { margin-right: 4px; }\n\n.vt-message-retry {\n font: inherit;\n font-size: inherit;\n color: var(--vtilt-error, #dc2626);\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n text-decoration: underline;\n}\n\n@keyframes vt-message-in {\n from { opacity: 0; transform: translateY(4px); }\n to { opacity: 1; transform: translateY(0); }\n}\n\n/* Markdown content rules (parity with chat-message-content.css) */\n.vt-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.vt-md p { margin: 0 0 0.5em 0; }\n.vt-md p:last-child { margin-bottom: 0; }\n.vt-md :is(b, strong) { font-weight: 600; }\n.vt-md :is(i, em) { font-style: italic; }\n.vt-md u { text-decoration: underline; }\n.vt-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.vt-md :is(h1, h2, h3):first-child { margin-top: 0.15em; }\n.vt-md :is(ul, ol) {\n list-style: none;\n margin: 0.5em 0;\n padding: 0 0 0 0.35em;\n}\n.vt-md li {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n align-items: flex-start;\n gap: 0.35em;\n margin: 0.2em 0;\n padding: 0;\n line-height: 1.45;\n}\n.vt-md ul > li::before {\n content: "•";\n display: inline-block;\n flex: 0 0 auto;\n line-height: 1.45;\n}\n.vt-md ul ul > li::before { content: "◦"; }\n.vt-md ol { counter-reset: vt-ol; }\n.vt-md ol > li { counter-increment: vt-ol; }\n.vt-md ol > li::before {\n content: counter(vt-ol) ".";\n display: inline-block;\n flex: 0 0 auto;\n min-width: 1.1em;\n line-height: 1.45;\n}\n.vt-md ol ol { counter-reset: vt-ol; }\n.vt-md li > :is(ul, ol) {\n flex: 1 0 100%;\n width: 100%;\n margin: 0.25em 0 0 0;\n padding-left: 0.75em;\n}\n.vt-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.vt-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.vt-md pre code { background: none; padding: 0; }\n.vt-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.vt-md a { color: inherit; text-decoration: underline; }\n\n/* Brand-colored "out" bubble inverts code/pre/quote backdrop. */\n.vt-user-md code { background: rgba(255, 255, 255, 0.2); }\n.vt-user-md pre { background: rgba(255, 255, 255, 0.15); }\n.vt-user-md pre code { background: none; }\n.vt-user-md blockquote { border-left-color: rgba(255, 255, 255, 0.35); }\n\n/* Typing bubble + new-messages pill -------------------------------------\n *\n * The typing indicator is no longer a separate strip above the composer\n * - it is an inline .vt-message rendered as the last child of the\n * message list, reusing the avatar + bubble shape so the dots morph\n * into the real message when it arrives. The only typing-specific\n * style is the [data-typing] modifier that switches the bubble layout\n * to inline-flex so the three dots sit horizontally instead of\n * stacking. The dot animation rules are reused by TypingBubble. */\n\n.vt-message-bubble[data-typing="true"] {\n display: inline-flex;\n align-items: center;\n gap: 5px;\n /* Critical: do NOT override the base .vt-message-bubble padding here.\n * The row uses align-items: flex-end, so a bubble shorter than a\n * single-line text bubble would bottom-align with the avatar and\n * visually sit lower than where the real message will appear. We\n * inherit 10px 14px from the base, then enforce a min content\n * height of one text line (14px font-size * 1.4 line-height) so the\n * total bubble height matches a single-line text bubble exactly.\n * When the dots morph into text the bubble stays put — no jolt. */\n min-height: 1.4em;\n}\n.vt-typing-dot {\n width: 6px;\n height: 6px;\n background: #B5B5B5;\n border-radius: 50%;\n animation: vt-typing-bounce 1.2s infinite;\n}\n.vt-typing-dot:nth-child(2) { animation-delay: 0.2s; }\n.vt-typing-dot:nth-child(3) { animation-delay: 0.4s; }\n@keyframes vt-typing-bounce {\n 0%, 60%, 100% { opacity: 0.35; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n\n.vt-new-pill {\n position: absolute;\n left: 50%;\n transform: translateX(-50%);\n bottom: 12px;\n background: var(--vtilt-primary);\n color: white;\n padding: 6px 14px;\n border-radius: 999px;\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n border: none;\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 transition: opacity 0.15s ease;\n}\n.vt-new-pill[data-visible="true"] { display: flex; }\n.vt-new-pill:hover { opacity: 0.92; }\n\n/* Closed banner + connection banner ------------------------------------- */\n\n.vt-closed-banner {\n padding: 12px 16px;\n padding-bottom: max(12px, env(safe-area-inset-bottom, 12px));\n border-top: 1px solid var(--vtilt-border);\n text-align: center;\n background: var(--vtilt-bg-list);\n flex-shrink: 0;\n font-size: 14px;\n color: var(--vtilt-text-subtle);\n}\n\n/* Connection banner.\n *\n * Two visual modes:\n * - data-kind="reconnecting": slim pill. Pulsing dot + "Reconnecting"\n * label. Slate background — informational, not alarming.\n * - data-kind="failed": actionable card. Warning icon + "Connection\n * lost" + Retry button. Red because the user must act.\n */\n.vt-conn-banner {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 12px;\n border-top: 1px solid var(--vtilt-border);\n font-size: 12px;\n font-weight: 500;\n flex-shrink: 0;\n}\n.vt-conn-banner[data-kind="reconnecting"] {\n background: #F8FAFC;\n color: #475569;\n justify-content: center;\n}\n.vt-conn-banner[data-kind="failed"] {\n background: #FEF2F2;\n color: #991B1B;\n}\n.vt-conn-banner-icon {\n display: inline-flex;\n flex-shrink: 0;\n color: #DC2626;\n}\n.vt-conn-banner-text {\n flex: 1;\n}\n.vt-conn-banner[data-kind="reconnecting"] .vt-conn-banner-text {\n flex: 0 0 auto;\n}\n.vt-conn-banner-dot {\n display: inline-block;\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #F59E0B;\n flex-shrink: 0;\n animation: vt-conn-pulse 1.4s ease-in-out infinite;\n}\n@keyframes vt-conn-pulse {\n 0%, 100% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.4; transform: scale(0.85); }\n}\n.vt-conn-banner-action {\n appearance: none;\n border: 1px solid #DC2626;\n background: transparent;\n color: #DC2626;\n font: inherit;\n font-weight: 600;\n font-size: 11px;\n padding: 3px 10px;\n border-radius: 999px;\n cursor: pointer;\n flex-shrink: 0;\n transition: background 0.12s ease, color 0.12s ease;\n}\n.vt-conn-banner-action:hover,\n.vt-conn-banner-action:focus-visible {\n background: #DC2626;\n color: #FFFFFF;\n outline: none;\n}\n@media (prefers-reduced-motion: reduce) {\n .vt-conn-banner-dot {\n animation: none;\n }\n}\n\n/* Input ----------------------------------------------------------------- */\n\n.vt-input-container {\n padding: 8px 12px;\n padding-bottom: max(8px, env(safe-area-inset-bottom, 8px));\n border-top: 1px solid var(--vtilt-border);\n flex-shrink: 0;\n background: var(--vtilt-bg);\n}\n.vt-input-box {\n position: relative;\n border: 1px solid #DDD;\n border-radius: 12px;\n background: var(--vtilt-bg);\n transition: border-color 0.15s ease, box-shadow 0.15s ease;\n}\n.vt-input-box:focus-within {\n border-color: var(--vtilt-primary);\n box-shadow: 0 0 0 2px rgba(123, 104, 238, 0.12);\n}\n.vt-input-textarea {\n width: 100%;\n box-sizing: border-box;\n border: none;\n border-radius: 0;\n padding: 12px 48px 12px 12px;\n font-size: 16px;\n line-height: 1.4;\n outline: none;\n background: transparent;\n color: var(--vtilt-text);\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.vt-input-textarea::placeholder { color: #999; }\n.vt-input-textarea:disabled { color: #BBB; cursor: not-allowed; }\n\n.vt-input-send {\n position: absolute;\n right: 4px;\n bottom: 4px;\n background: #E5E5E5;\n color: #999;\n border: none;\n border-radius: 50%;\n padding: 0;\n width: 32px;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background-color 0.15s ease, color 0.15s ease, opacity 0.15s ease;\n opacity: 0.6;\n}\n.vt-input-send[data-active="true"] {\n background: var(--vtilt-primary);\n color: white;\n cursor: pointer;\n opacity: 1;\n}\n.vt-input-send[data-active="true"]:hover { opacity: 0.9; }\n.vt-input-send[data-active="true"]:active { opacity: 0.8; transform: scale(0.95); }\n.vt-input-send:disabled { cursor: not-allowed; }\n\n.vt-input-container[data-pending="true"] .vt-input-box {\n background: var(--vtilt-bg-list);\n border-color: var(--vtilt-border-light);\n}\n\n/* Skeletons ------------------------------------------------------------- */\n\n@keyframes vt-skeleton-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.55; }\n}\n.vt-skeleton {\n background: var(--vtilt-skeleton);\n border-radius: 6px;\n animation: vt-skeleton-pulse 2.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n}\n.vt-skeleton-circle {\n background: var(--vtilt-skeleton);\n border-radius: 50%;\n animation: vt-skeleton-pulse 2.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n}\n\n/* Built-in widgets ------------------------------------------------------ */\n\n.vt-widget { margin-top: 10px; }\n.vt-widget p { margin: 0 0 10px 0; font-size: 14px; color: #333; }\n.vt-widget-input {\n font-family: inherit;\n font-size: 14px;\n padding: 8px 10px;\n border: 1px solid #DDD;\n border-radius: 8px;\n width: 100%;\n margin-bottom: 8px;\n}\n.vt-widget-input:focus { outline: none; border-color: var(--vtilt-primary); }\n.vt-widget-btn {\n padding: 10px 16px;\n background: var(--vtilt-primary);\n color: white;\n border: none;\n border-radius: 12px;\n font-size: 14px;\n font-weight: 600;\n cursor: pointer;\n}\n.vt-widget-btn[data-style="outline"] {\n background: transparent;\n color: var(--vtilt-primary);\n border: 2px solid var(--vtilt-primary);\n display: inline-flex;\n align-items: center;\n gap: 8px;\n}\n.vt-widget-btn:disabled { opacity: 0.6; cursor: not-allowed; }\n.vt-widget-thanks { font-size: 13px; color: var(--vtilt-online); margin: 0; }\n\n/* Mobile fullscreen ----------------------------------------------------\n *\n * On viewports <=480px the open panel covers the whole device, regardless\n * of where the bubble was dragged. The rules live in a media query (not\n * a JS-driven data attribute) so they remain correct on viewport resize\n * — rotation, browser-window resize, devtools toggling — without needing\n * a re-render to update an attribute.\n *\n * "transform: none !important" is required because bubble-drag.ts sets\n * an inline "transform: translate3d(...)" on the container. Per the CSS\n * cascade, author !important declarations win over inline normal styles,\n * so the open panel snaps back to (0, 0) and fills the viewport even\n * after the user has dragged the bubble away from its anchor corner.\n */\n\n@media (max-width: 480px) {\n .vt-bubble { width: 56px; height: 56px; }\n .vt-container { width: 56px; height: 56px; }\n\n .vt-container[data-open="true"] {\n top: 0; left: 0; right: 0; bottom: 0;\n /* Stretch the container from a 56x56 box back to the viewport so the\n * fullscreen panel inside has room to fill the screen. */\n width: auto; height: auto;\n transform: none !important;\n }\n .vt-container[data-open="true"] .vt-panel {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n border-radius: 0;\n box-shadow: none;\n }\n}\n\n@media (prefers-reduced-motion: reduce) {\n * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }\n}\n',n.appendChild(i);var r=document.createElement("div");return r.style.cssText="pointer-events: auto;",n.appendChild(r),function(t,e){var n=()=>{var n=e.theme.value;t.style.setProperty("--vtilt-primary",n.primaryColor),t.style.setProperty("--vtilt-primary-shadow",n.primaryColor+"66"),t.style.setProperty("--vtilt-font",n.fontFamily),t.style.setProperty("--vtilt-radius",n.borderRadius)};n(),e.theme.subscribe(n)}(e,t.store),ne(re(Li,{store:t.store,controller:t.controller,position:t.position,bubbleDraggable:t.bubbleDraggable}),r),{host:e,destroy(){ne(null,r),e.remove()}}}function Li(t){var{store:e,controller:n,position:i,bubbleDraggable:r}=t,s=xe(null),o=xe(null),a=xe(null),l=function(t,e){return ke(()=>{var n=e.current;if(n&&"undefined"!=typeof window&&!t.isOpen.value){var i=n.getBoundingClientRect();if(0!==i.width&&0!==i.height){var r=window.innerWidth,s=window.innerHeight,o=(i.left+i.right)/2>r/2?"right":"left",a=(i.top+i.bottom)/2>s/2?"bottom":"top",l=a+"-"+o;n.setAttribute("data-panel-anchor",l),n.style.setProperty("--vt-panel-origin",a+" "+o);var u="right"===o?i.right:r-i.left,h="bottom"===a?i.bottom:s-i.top;n.style.setProperty("--vt-panel-max-w",Math.max(0,u-20)+"px"),n.style.setProperty("--vt-panel-max-h",Math.max(0,h-20)+"px")}}},[t,e])}(e,s);return function(t,e){var n=be(se++,4);!de.__s&&Ie(n.__H,e)&&(n.__=t,n.u=e,oe.__h.push(n))}(()=>{if(r&&s.current&&o.current)return a.current=In(s.current,{handle:o.current,onPositionChange:l}),()=>{var t;null===(t=a.current)||void 0===t||t.destroy(),a.current=null}},[r,l]),we(()=>{l();var t=()=>l();window.addEventListener("resize",t);var n=e.isOpen.subscribe(t=>{t||l()});return()=>{window.removeEventListener("resize",t),n()}},[e,l]),function(t){we(()=>{var e=t.isOpen.value,n=t.isOpen.subscribe(t=>{var n,i;if("undefined"!=typeof document){var r=function(t,e,n){return n?e&&!t?{nextWasOpen:!0,shouldLock:!0,shouldUnlock:!1}:!e&&t?{nextWasOpen:!1,shouldLock:!1,shouldUnlock:!0}:{nextWasOpen:e,shouldLock:!1,shouldUnlock:!1}:{nextWasOpen:e,shouldLock:!1,shouldUnlock:!1}}(e,t,"undefined"!=typeof window&&window.innerWidth<=480);e=r.nextWasOpen;var s=document.documentElement,o=document.body;if(r.shouldLock){var a=null!==(n=null===window||void 0===window?void 0:window.scrollY)&&void 0!==n?n:0;s.style.setProperty("overflow","hidden","important"),o.style.setProperty("overflow","hidden","important"),o.style.setProperty("position","fixed","important"),o.style.setProperty("width","100%","important"),o.style.top="-"+a+"px",o.dataset.vtScrollY=String(a)}else if(r.shouldUnlock){var l=Number(null!==(i=o.dataset.vtScrollY)&&void 0!==i?i:0);s.style.removeProperty("overflow"),o.style.removeProperty("overflow"),o.style.removeProperty("position"),o.style.removeProperty("width"),o.style.top="",delete o.dataset.vtScrollY,null===window||void 0===window||window.scrollTo(0,l)}}else e=t});return n},[t])}(e),re("div",{ref:s,class:"vt-container","data-position":i,"data-draggable":r?"true":"false","data-hidden":e.isVisible.value?"false":"true","data-open":e.isOpen.value?"true":"false",children:[re(On,{store:e,controller:n,bubbleRef:o}),re(ji,{store:e,controller:n})]})}var $i=Object.defineProperty,zi=Object.defineProperties,qi=Object.getOwnPropertyDescriptors,Fi=Object.getOwnPropertySymbols,Hi=Object.prototype.hasOwnProperty,Wi=Object.prototype.propertyIsEnumerable,Ji=(t,e,n)=>e in t?$i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vi=(t,e)=>{for(var n in e||(e={}))Hi.call(e,n)&&Ji(t,n,e[n]);if(Fi)for(var n of Fi(e))Wi.call(e,n)&&Ji(t,n,e[n]);return t},Ki=(t,e)=>zi(t,qi(e)),Gi=function(t,e){this[0]=t,this[1]=e},Xi=class{},Qi="undefined"!=typeof global?global:"undefined"!=typeof window?window:self;function Zi(t,e){return(""+t).padStart(e?3:2,"0")}function Yi(t){return Xi.Config.logTimestamps?function(e){var n=new Date;t(Zi(n.getHours())+":"+Zi(n.getMinutes())+":"+Zi(n.getSeconds())+"."+Zi(n.getMilliseconds(),1)+" "+e)}:function(e){t(e)}}var tr=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==Qi?void 0:Qi.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(Yi));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)}};tr.defaultLogLevel=1,tr.LOG_NONE=0,tr.LOG_ERROR=1,tr.LOG_MAJOR=2,tr.LOG_MINOR=3,tr.LOG_MICRO=4,tr.logAction=(t,e,n,i)=>{tr.logActionNoStrip(t,e,n,i)};var er=tr,nr={};function ir(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="+Mr(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)$i(t,n,{get:e[n],enumerable:!0})})(nr,{Format:()=>Cr,allSame:()=>Sr,allToLowerCase:()=>$r,allToUpperCase:()=>zr,arrChooseN:()=>jr,arrDeleteValue:()=>yr,arrEquals:()=>Gr,arrIntersect:()=>mr,arrIntersectOb:()=>br,arrPopRandomElement:()=>Er,arrWithoutValue:()=>wr,cheapRandStr:()=>Dr,containsValue:()=>pr,copy:()=>ar,createMissingPluginError:()=>Xr,dataSizeBytes:()=>Pr,decodeBody:()=>Nr,encodeBody:()=>Lr,ensureArray:()=>lr,forInOwnNonNullProperties:()=>kr,getBackoffCoefficient:()=>qr,getGlobalObject:()=>Wr,getJitterCoefficient:()=>Fr,getRetryTime:()=>Hr,inherits:()=>fr,inspectBody:()=>Rr,inspectError:()=>Mr,intersect:()=>gr,isEmpty:()=>hr,isErrorInfoOrPartialErrorInfo:()=>Or,isNil:()=>dr,isObject:()=>ur,keysArray:()=>xr,listenerToAsyncIterator:()=>ts,matchDerivedChannel:()=>Vr,mixin:()=>or,parseQueryString:()=>Ir,prototypicalClone:()=>vr,randomString:()=>Ur,shallowClone:()=>cr,shallowEquals:()=>Jr,stringifyValues:()=>Ar,throwMissingPluginError:()=>Qr,toBase64:()=>Kr,toQueryString:()=>Tr,valuesArray:()=>_r,whenPromiseSettles:()=>Br,withTimeoutAsync:()=>Zr});var rr=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 ir(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: "+Xi.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}},sr=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 ir(this)}static fromValues(e){var{message:n,code:i,statusCode:r}=e;if("string"!=typeof n||!dr(i)&&"number"!=typeof i||!dr(r)&&"number"!=typeof r)throw new Error("PartialErrorInfo.fromValues(): invalid values: "+Xi.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 or(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 ar(t){return or({},t)}function lr(t){return dr(t)?[]:Array.isArray(t)?t:[t]}function ur(t){return"[object Object]"==Object.prototype.toString.call(t)}function hr(t){for(var e in t)return!1;return!0}function dr(t){return null==t}function cr(t){var e=new Object;for(var n in t)e[n]=t[n];return e}function vr(t,e){class n{}n.prototype=t;var i=new n;return e&&or(i,e),i}var fr=function(t,e){Xi.Config.inherits?Xi.Config.inherits(t,e):(t.super_=e,t.prototype=vr(e.prototype,{constructor:t}))};function pr(t,e){for(var n in t)if(t[n]==e)return!0;return!1}function gr(t,e){return Array.isArray(e)?mr(t,e):br(t,e)}function mr(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 br(t,e){for(var n=[],i=0;i<t.length;i++){var r=t[i];r in e&&n.push(r)}return n}function yr(t,e){var n=t.indexOf(e),i=-1!=n;return i&&t.splice(n,1),i}function wr(t,e){var n=t.slice();return yr(n,e),n}function xr(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(i);return n}function _r(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(t[i]);return n}function kr(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&t[n]&&e(n)}function Sr(t,e){if(0===t.length)return!0;var n=t[0][e];return t.every(function(t){return t[e]===n})}var Cr=(t=>(t.msgpack="msgpack",t.json="json",t))(Cr||{});function Er(t){return t.splice((e=t,Math.floor(Math.random()*e.length)),1)[0];var e}function Tr(t){var e=[];if(t)for(var n in t)e.push(encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e.length?"?"+e.join("&"):""}function Ar(t){return Object.fromEntries(Object.entries(t).map(t=>{var[e,n]=t;return[e,String(n)]}))}function Ir(t){for(var e,n=/([^?&=]+)=?([^&]*)/g,i={};e=n.exec(t);)i[decodeURIComponent(e[1])]=decodeURIComponent(e[2]);return i}function Or(t){return"object"==typeof t&&null!==t&&(t instanceof rr||t instanceof sr)}function Mr(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():Xi.Config.inspect(t)}function Rr(t){return Xi.BufferUtils.isBuffer(t)?t.toString():"string"==typeof t?t:Xi.Config.inspect(t)}function Pr(t){if(Xi.BufferUtils.isBuffer(t))return Xi.BufferUtils.byteLength(t);if("string"==typeof t)return Xi.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 Dr(){return String(Math.random()).substr(2)}var Ur=function(){var t=u(function*(t){var e=yield Xi.Config.getRandomArrayBuffer(t);return Xi.BufferUtils.base64Encode(e)});return function(e){return t.apply(this,arguments)}}();function jr(t,e){for(var n=Math.min(e,t.length),i=t.slice(),r=[],s=0;s<n;s++)r.push(Er(i));return r}function Br(t,e){t.then(t=>{null==e||e(null,t)}).catch(t=>{null==e||e(t)})}function Nr(t,e,n){return"msgpack"==n?(e||Qr("MsgPack"),e.decode(t)):JSON.parse(String(t))}function Lr(t,e,n){return"msgpack"==n?(e||Qr("MsgPack"),e.encode(t,!0)):JSON.stringify(t)}function $r(t){return t.map(function(t){return t&&t.toLowerCase()})}function zr(t){return t.map(function(t){return t&&t.toUpperCase()})}function qr(t){return Math.min((t+2)/3,2)}function Fr(){return 1-.2*Math.random()}function Hr(t,e){return t*qr(e)*Fr()}function Wr(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:self}function Jr(t,e){return Object.keys(t).every(n=>t[n]===e[n])&&Object.keys(e).every(n=>e[n]===t[n])}function Vr(t){var e=t.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!e||!e.length||e.length<5)throw new rr("regex match failed",400,40010);if(e[2])throw new rr("cannot use a derived option with a "+e[2]+" channel",400,40010);return{qualifierParam:e[3]||"",channelName:e[4]}}function Kr(t){var e=Xi.BufferUtils,n=e.utf8Encode(t);return e.base64Encode(n)}function Gr(t,e){return t.length===e.length&&t.every(function(t,n){return t===e[n]})}function Xr(t){return new rr(t+" plugin not provided",40019,400)}function Qr(t){throw Xr(t)}function Zr(t,e,n){return Yr.apply(this,arguments)}function Yr(){return Yr=u(function*(t,e,n){void 0===e&&(e=5e3),void 0===n&&(n="Timeout expired");var i=new rr(n,5e4,500);return Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(i),e))])}),Yr.apply(this,arguments)}function ts(t){return n=(t,i,r,s)=>{try{var o=e[t](i),a=(i=o.value)instanceof Gi,l=o.done;Promise.resolve(a?i[0]:i).then(e=>a?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 rr("Concurrent next() calls are not supported",4e4,400);var r=yield new Gi(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 es="2.17.0",ns={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:es,protocolVersion:5,agent:"ably-js/"+es,getPort:function(t,e){return e||t.tls?t.tlsPort:t.port},getHttpScheme:function(t){return t.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:rs,getEndpointFallbackHosts:ss,getFallbackHosts:as,getHosts:function(t){return[t.primaryDomain].concat(as(t))},checkHost:ls,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 er.logAction(i,er.LOG_ERROR,n+"()",s),new Error(s)}var o;if("string"==typeof t)if(-1==t.indexOf(":")){if(!e){var a=n+" cannot be initialized with just an Ably Token; you must provide a client options object with a `plugins` property. (Set this Ably Token as the object’s `token` property.)";throw er.logAction(i,er.LOG_ERROR,n+"()",a),new Error(a)}o={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 er.logAction(i,er.LOG_ERROR,n+"()",l),new Error(l)}o={key:t}}else o=t;r&&(o=Ki(Vi({},o),{plugins:Vi(Vi({},r),o.plugins)}));return o},normaliseOptions:function(t,e,n){var i=null!=n?n:er.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.");hs(t),"function"==typeof t.recover&&!0===t.closeOnUnload&&(er.logAction(i,er.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||ns.ENDPOINT;t.fallbackHosts||t.restHost||t.realtimeHost||t.port||t.tlsPort||(t.fallbackHosts=ss(t.environment||r));var s=t.environment&&t.environment+".realtime.ably.net",o=t.restHost||t.realtimeHost||s||rs(r);(t.fallbackHosts||[]).concat(o).forEach(ls),t.port=t.port||ns.PORT,t.tlsPort=t.tlsPort||ns.TLS_PORT,"tls"in t||(t.tls=!0);var a=function(t){var e={};for(var n in ns.TIMEOUTS)e[n]=t[n]||ns.TIMEOUTS[n];return e}(t);t.useBinaryProtocol=!!e&&("useBinaryProtocol"in t?Xi.Config.supportsBinary&&t.useBinaryProtocol:Xi.Config.preferBinary);var l={};t.clientId&&(l["X-Ably-ClientId"]=Xi.BufferUtils.base64Encode(Xi.BufferUtils.utf8Encode(t.clientId)));"idempotentRestPublishing"in t||(t.idempotentRestPublishing=!0);var u=null,h=t.connectivityCheckUrl;if(t.connectivityCheckUrl){var[d,c]=t.connectivityCheckUrl.split("?");u=c?Ir(c):{},-1===d.indexOf("://")&&(d="https://"+d),h=d}var v=t.wsConnectivityCheckUrl;v&&-1===v.indexOf("://")&&(v="wss://"+v);return Ki(Vi({},t),{primaryDomain:o,maxMessageSize:t.maxMessageSize||ns.maxMessageSize,timeouts:a,connectivityCheckParams:u,connectivityCheckUrl:h,wsConnectivityCheckUrl:v,headers:l})},defaultGetHeaders:function(t,e){var{format:n,protocolVersion:i=vs.protocolVersion}=void 0===e?{}:e;return{accept:cs[null!=n?n:t.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":i.toString(),"Ably-Agent":us(t)}},defaultPostHeaders:function(t,e){var{format:n,protocolVersion:i=vs.protocolVersion}=void 0===e?{}:e,r=cs[null!=n?n:t.useBinaryProtocol?"msgpack":"json"];return{accept:r,"content-type":r,"X-Ably-Version":i.toString(),"Ably-Agent":us(t)}}};function is(t){return t.includes(".")||t.includes("::")||"localhost"===t}function rs(t){return is(t)?t:t.startsWith("nonprod:")?t.replace("nonprod:","")+".realtime.ably-nonprod.net":t+".realtime.ably.net"}function ss(t){return is(t)?[]:t.startsWith("nonprod:")?os(t.replace("nonprod:",""),"ably-realtime-nonprod.com"):os(t,"ably-realtime.com")}function os(t,e){return["a","b","c","d","e"].map(n=>t+"."+n+".fallback."+e)}function as(t){var e=t.fallbackHosts,n=void 0!==t.httpMaxRetryCount?t.httpMaxRetryCount:ns.httpMaxRetryCount;return e?jr(e,n):[]}function ls(t){if("string"!=typeof t)throw new rr("host must be a string; was a "+typeof t,4e4,400);if(!t.length)throw new rr("host must not be zero-length",4e4,400)}function us(t){var e=ns.agent;if(t.agents)for(var n in t.agents)e+=" "+n+"/"+t.agents[n];return e}function hs(t){if(t.endpoint&&(t.environment||t.restHost||t.realtimeHost))throw new rr("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 rr("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function ds(t,e,n){var i=n||{};if(i.cipher){t||Qr("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 cs={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},vs={protocolVersion:ns.protocolVersion};var fs=ns;var ps=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){er.logAction(this.logger,er.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)})}},gs=(t=>(t.Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t))(gs||{}),ms=gs,bs=(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))(bs||{});var ys=bs,ws=Math.pow(2,17);function xs(t){return Or(t)?(t.code||(403===t.statusCode?t.code=40300:(t.code=40170,t.statusCode=401)),t):new rr(Mr(t),t.code||40170,t.statusCode||401)}function _s(t){if(!t)return"";"string"==typeof t&&(t=JSON.parse(t));var e=Object.create(null),n=xr(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 ks(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 er.logAction(e,er.LOG_ERROR,"Auth()",n),new Error(n)}}var Ss=0;var Cs=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)&&er.logAction(this.logger,er.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.I(e.defaultTokenParams,e),ks(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 er.logAction(this.logger,er.LOG_ERROR,"Auth()",n),new rr(n,40160,401)}this.O(e)}}get logger(){return this.client.logger}authorize(t,e){var n=this;return u(function*(){if(e&&e.key&&n.authOptions.key!==e.key)throw new rr("Unable to update auth options with incompatible key",40102,401);try{var i=yield n.M(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===ys.Forbidden&&n.client.connection.connectionManager.actOnErrorFromAuthorize(t),t}})()}M(t,e){var n=this;return u(function*(){n.tokenDetails=null,n.I(t,e),ks(n.authOptions,n.logger);try{return n.R(!0)}finally{delete n.tokenParams.timestamp,delete n.authOptions.queryTime}})()}requestToken(t,e){var n=this;return u(function*(){var i,r=e||n.authOptions,s=t||ar(n.tokenParams),o=n.client;if(r.authCallback)i=r.authCallback;else if(r.authUrl)i=(t,e)=>{var i,s=or({accept:"application/json, text/plain"},r.authHeaders),o=r.authMethod&&"post"===r.authMethod.toLowerCase(),a=r.authUrl.indexOf("?");a>-1&&(i=Ir(r.authUrl.slice(a)),r.authUrl=r.authUrl.slice(0,a),o||(r.authParams=or(i,r.authParams)));var l=or({},r.authParams||{},t),u=t=>{var n,i,r=null!=(n=t.body)?n:null,s=null;if(t.error);else{var o=null!=(i=t.headers["content-type"])?i:null;s=Array.isArray(o)?o.join(", "):o}if(t.error)e(t.error,null);else if(t.unpacked)e(null,r);else if(Xi.BufferUtils.isBuffer(r)&&(r=r.toString()),s){var a=s.indexOf("application/json")>-1,l=s.indexOf("text/plain")>-1||s.indexOf("application/jwt")>-1;if(a||l){if(a){if(r.length>ws)return void e(new rr("authUrl response exceeded max permitted length",40170,401),null);try{r=JSON.parse(r)}catch(t){return void e(new rr("Unexpected error processing authURL response; err = "+t.message,40170,401),null)}}e(null,r,s)}else e(new rr("authUrl responded with unacceptable content-type "+s+", should be either text/plain, application/jwt or application/json",40170,401),null)}else e(new rr("authUrl response is missing a content-type header",40170,401),null)};if(o){var h=s||{};h["content-type"]="application/x-www-form-urlencoded";var d=Tr(l).slice(1);Br(n.client.http.doUri(ms.Post,r.authUrl,h,d,i),(t,e)=>u(t||e))}else Br(n.client.http.doUri(ms.Get,r.authUrl,s||{},null,l),(t,e)=>u(t||e))};else{if(!r.key){throw er.logAction(n.logger,er.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 rr("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403)}i=(t,e)=>{Br(n.createTokenRequest(t,r),(t,n)=>e(t,null!=n?n:null))}}"capability"in s&&(s.capability=_s(s.capability));return new Promise((t,e)=>{var a=!1,l=n.client.options.timeouts.realtimeRequestTimeout,u=setTimeout(()=>{a=!0;var t="Token request callback timed out after "+l/1e3+" seconds";er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()",t),e(new rr(t,40170,401))},l);i(s,(i,s,l)=>{if(!a){if(clearTimeout(u),i)return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+Mr(i)),void e(xs(i));if("string"!=typeof s){if("object"!=typeof s||null===s){var h="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof s;return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()",h),void e(new rr(h,40170,401))}var d=JSON.stringify(s).length;if(d>ws&&!r.suppressMaxLengthCheck)e(new rr("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 c="Expected token request callback to call back with a token string, token request object, or token details object";return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()",c),void e(new rr(c,40170,401))}var v,f,p,g;f=(i,r,s)=>{if(i)return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+Mr(i)),void e(xs(i));s||(r=JSON.parse(r)),t(r)},p="/keys/"+(v=s).keyName+"/requestToken",g=fs.defaultPostHeaders(n.client.options,{format:"json"}),r.requestHeaders&&or(g,r.requestHeaders),Br(n.client.http.do(ms.Post,function(t){return o.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 rr("Token string is empty",40170,401)):s.length>ws?e(new rr("Token string exceeded max permitted length (was "+s.length+" bytes)",40170,401)):"undefined"===s||"null"===s?e(new rr("Token string was literal null/undefined",40170,401)):"{"!==s[0]||l&&l.indexOf("application/jwt")>-1?t({token:s}):e(new rr("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 u(function*(){e=e||n.authOptions,t=t||ar(n.tokenParams);var i=e.key;if(!i)throw new rr("No key specified",40101,403);var r=i.split(":"),s=r[0],o=r[1];if(!o)throw new rr("Invalid key specified",40101,403);if(""===t.clientId)throw new rr("clientId can’t be an empty string",40012,400);"capability"in t&&(t.capability=_s(t.capability));var a=or({keyName:s},t),l=t.clientId||"",u=t.ttl||"",h=t.capability||"";a.timestamp||(a.timestamp=yield n.P(e&&e.queryTime));var d=a.nonce||(a.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),c=a.timestamp,v=a.keyName+"\n"+u+"\n"+h+"\n"+l+"\n"+c+"\n"+d+"\n";return a.mac=a.mac||((t,e)=>{var n=Xi.BufferUtils,i=n.utf8Encode(t),r=n.utf8Encode(e),s=n.hmacSha256(i,r);return n.base64Encode(s)})(v,o),a})()}getAuthParams(){var t=this;return u(function*(){if("basic"==t.method)return{key:t.key};var e=yield t.R(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}})()}getAuthHeaders(){var t=this;return u(function*(){if("basic"==t.method)return{authorization:"Basic "+t.basicKey};var e=yield t.R(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Kr(e.token)}})()}O(t){this.method="basic",this.key=t.key,this.basicKey=Kr(t.key),this.authOptions=t||{},"clientId"in t&&this.D(t.clientId)}I(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.D(e.clientId),this.authOptions=e)}R(t){var e=this;return u(function*(){var n=e.tokenDetails;if(n){if(e.j(n.clientId))throw new rr("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=ps.create(e.logger))).createPromise();if(null!==e.currentTokenRequestId&&!t)return i;var r,s=e.currentTokenRequestId=Ss++,o=null;try{r=yield e.requestToken(e.tokenParams,e.authOptions)}catch(t){o=t}if(e.currentTokenRequestId>s)return i;e.currentTokenRequestId=null;var a=e.waitingForTokenRequest;return e.waitingForTokenRequest=null,o?(null==a||a.rejectAll(o),i):(null==a||a.resolveAll(e.tokenDetails=r),i)})()}D(t){if("string"!=typeof t&&null!==t)throw new rr("clientId must be either a string or null",40012,400);if("*"===t)throw new rr('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.B(t);if(e)throw e}B(t){if(this.j(t)){var e="Unexpected clientId mismatch: client has "+this.clientId+", requested "+t,n=new rr(e,40102,401);return er.logAction(this.logger,er.LOG_ERROR,"Auth._uncheckedSetClientId()",e),n}return this.clientId=this.tokenParams.clientId=t,null}j(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)}P(t){var e=this;return u(function*(){return e.client.getTimestamp(t||!!e.authOptions.queryTime)})()}};function Es(t){var e=[];if(t)for(var n in t)e.push(n+"="+t[n]);return e.join("&")}function Ts(t,e){return t+(e?"?":"")+Es(e)}var As=class{constructor(t){this.client=t,this.platformHttp=new Xi.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:er.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}L(t){var e=t.connection,n=e&&e.connectionManager.host;return n?[n].concat(fs.getFallbackHosts(t.options)):fs.getHosts(t.options)}do(t,e,n,i,r){var s=this;return u(function*(){try{var o=s.client;if(!o)return{error:new rr("http.do called without client",5e4,500)};var a="function"==typeof e?e:function(t){return o.baseUri(t)+e},l=o.$;if(l){if(l.validUntil>Date.now()){var h=yield s.doUri(t,a(l.host),n,i,r);return h.error&&s.platformHttp.shouldFallback(h.error)?(o.$=null,s.do(t,e,n,i,r)):h}o.$=null}var d=s.L(o);if(1===d.length)return s.doUri(t,a(d[0]),n,i,r);var c=null,v=function(){var e=u(function*(e,l){var u=e.shift();c=null!=c?c:new Date;var h=yield s.doUri(t,a(u),n,i,r);return h.error&&s.platformHttp.shouldFallback(h.error)&&e.length?Date.now()-c.getTime()>o.options.timeouts.httpMaxRetryDuration?{error:new rr("Timeout for trying fallback hosts retries. Total elapsed time exceeded the "+o.options.timeouts.httpMaxRetryDuration+"ms limit",50003,500)}:v(e,!0):(l&&(o.$={host:u,validUntil:Date.now()+o.options.timeouts.fallbackRetryTimeout}),h)});return function(t,n){return e.apply(this,arguments)}}();return v(d)}catch(t){return{error:new rr("Unexpected error in Http.do: "+Mr(t),500,5e4)}}})()}doUri(t,e,n,i,r){var s=this;return u(function*(){try{!function(t,e,n,i,r){r.shouldLog(er.LOG_MICRO)&&er.logActionNoStrip(r,er.LOG_MICRO,"Http."+t+"()","Sending; "+Ts(e,i)+"; Body"+(Xi.BufferUtils.isBuffer(n)?" (Base64): "+Xi.BufferUtils.base64Encode(n):": "+n))}(t,e,i,r,s.logger);var o=yield s.platformHttp.doUri(t,e,n,i,r);return s.logger.shouldLog(er.LOG_MICRO)&&function(t,e,n,i,r){t.error?er.logActionNoStrip(r,er.LOG_MICRO,"Http."+e+"()","Received Error; "+Ts(n,i)+"; Error: "+Mr(t.error)):er.logActionNoStrip(r,er.LOG_MICRO,"Http."+e+"()","Received; "+Ts(n,i)+"; Headers: "+Es(t.headers)+"; StatusCode: "+t.statusCode+"; Body"+(Xi.BufferUtils.isBuffer(t.body)?" (Base64): "+Xi.BufferUtils.base64Encode(t.body):": "+t.body))}(o,t,e,r,s.logger),o}catch(t){return{error:new rr("Unexpected error in Http.doUri: "+Mr(t),500,5e4)}}})()}};function Is(t,e,n){for(var i,r,s,o=0;o<t.length;o++)if(i=t[o],n&&(i=i[n]),Array.isArray(i)){for(;-1!==(r=i.indexOf(e));)i.splice(r,1);n&&0===i.length&&delete t[o][n]}else if(ur(i))for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&Array.isArray(i[s])&&Is([i],e,s)}var Os=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: "+Xi.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: "+Xi.Config.inspect(e));if(dr(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: "+Xi.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||dr(e[0])&&dr(e[1]))return this.any=[],this.events=Object.create(null),this.anyOnce=[],void(this.eventsOnce=Object.create(null));var[i,r]=e,s=null,o=null;if(1!==e.length&&r){if("function"!=typeof r)throw new Error("EventEmitter.off(): invalid arguments:"+Xi.Config.inspect(e));[o,s]=[i,r]}else"function"==typeof i?s=i:o=i;if(s&&dr(o))Is([this.any,this.events,this.anyOnce,this.eventsOnce],s);else if(Array.isArray(o))o.forEach(t=>{this.off(t,s)});else{if("string"!=typeof o)throw new Error("EventEmitter.off(): invalid arguments:"+Xi.Config.inspect(e));s?Is([this.events,this.eventsOnce],s,o):(delete this.events[o],delete this.eventsOnce[o])}}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 o=this.eventsOnce[t];o&&(Array.prototype.push.apply(s,o),delete this.eventsOnce[t]);var a=this.events[t];a&&Array.prototype.push.apply(s,a),s.forEach(t=>{!function(t,e,n,i){try{n.apply(e,i)}catch(e){er.logAction(t,er.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,o]=e;if(1===e.length&&"function"==typeof s)this.anyOnce.push(s);else if(dr(s)){if("function"!=typeof o)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));this.anyOnce.push(o)}else if(Array.isArray(s)){var a=this,l=function(){var t=Array.prototype.slice.call(arguments);if(s.forEach(function(t){a.off(t,l)}),"function"!=typeof o)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));o.apply(this,t)};s.forEach(function(t){a.on(t,l)})}else{if("string"!=typeof s)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));var u=this.eventsOnce[s]||(this.eventsOnce[s]=[]);if(o){if("function"!=typeof o)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));u.push(o)}}}whenState(t,e){var n=this;return u(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)})()}},Ms={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},Rs=[];Object.keys(Ms).forEach(function(t){Rs[Ms[t]]=t});var Ps={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},Ds=Object.keys(Ps);Ps.MODE_ALL=Ps.PRESENCE|Ps.PUBLISH|Ps.SUBSCRIBE|Ps.PRESENCE_SUBSCRIBE|Ps.ANNOTATION_PUBLISH|Ps.ANNOTATION_SUBSCRIBE|Ps.OBJECT_SUBSCRIBE|Ps.OBJECT_PUBLISH;var Us=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function js(){return(js=u(function*(t,e){var{data:n,encoding:i}=yield Bs(t.data,t.encoding,e);return t.data=n,t.encoding=i,t})).apply(this,arguments)}function Bs(t,e,n){return Ns.apply(this,arguments)}function Ns(){return(Ns=u(function*(t,e,n){var i=n.channelCipher,r=t,s=e?e+"/":"";return Xi.BufferUtils.isBuffer(r)||(r=Xi.BufferUtils.utf8Encode(String(r)),s+="utf-8/"),{data:yield i.encrypt(r),encoding:s=s+"cipher+"+i.algorithm}})).apply(this,arguments)}function Ls(){return Ls=u(function*(t,e){var{data:n,encoding:i}=$s(t.data,t.encoding);return t.data=n,t.encoding=i,null!=e&&e.cipher?function(t,e){return js.apply(this,arguments)}(t,e):t}),Ls.apply(this,arguments)}function $s(t,e){if("string"==typeof t||Xi.BufferUtils.isBuffer(t)||null==t)return{data:t,encoding:e};if(ur(t)||Array.isArray(t))return{data:JSON.stringify(t),encoding:e?e+"/json":"json"};throw new rr("Data type is unsupported",40013,400)}function zs(){return(zs=u(function*(t,e){var{data:n,encoding:i,error:r}=yield qs(t.data,t.encoding,e);if(t.data=n,t.encoding=i,r)throw r})).apply(this,arguments)}function qs(t,e,n){return Fs.apply(this,arguments)}function Fs(){return Fs=u(function*(t,e,n){var i,r=function(t){return t&&t.channelOptions?t:{channelOptions:t,plugins:{},baseEncodedPreviousPayload:void 0}}(n),s=t,o=t,a=e;if(e){var l,u=e.split("/"),h=u.length,d="";try{for(;(l=h)>0;){var c=u[--h].match(/([-\w]+)(\+([\w-]+))?/);if(!c)break;switch(d=c[1]){case"base64":o=Xi.BufferUtils.base64Decode(String(o)),l==u.length&&(s=o);continue;case"utf-8":o=Xi.BufferUtils.utf8Decode(o);continue;case"json":o=JSON.parse(o);continue;case"cipher":if(null!=r.channelOptions&&r.channelOptions.cipher&&r.channelOptions.channelCipher){var v=c[3],f=r.channelOptions.channelCipher;if(v!=f.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");o=yield f.decrypt(o);continue}throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!r.plugins||!r.plugins.vcdiff)throw new rr("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new rr("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var p=r.baseEncodedPreviousPayload;"string"==typeof p&&(p=Xi.BufferUtils.utf8Encode(p));var g=Xi.BufferUtils.toBuffer(p);o=Xi.BufferUtils.toBuffer(o),s=o=Xi.BufferUtils.arrayBufferViewToBuffer(r.plugins.vcdiff.decode(o,g))}catch(t){throw new rr("Vcdiff delta decode failed with "+t,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(t){var m=t;i=new rr("Error processing the "+d+" encoding, decoder returned ‘"+m.message+"’",m.code||40013,400)}finally{a=l<=0?null:u.slice(0,l).join("/")}}return i?{error:i,data:o,encoding:a}:(r.baseEncodedPreviousPayload=s,{data:o,encoding:a})}),Fs.apply(this,arguments)}function Hs(){var t=arguments.length>0?"json":"msgpack",{data:e,encoding:n}=Ws(this.data,this.encoding,t);return Object.assign({},this,{encoding:n,data:e})}function Ws(t,e,n){return t&&Xi.BufferUtils.isBuffer(t)?"msgpack"===n?{data:Xi.BufferUtils.toBuffer(t),encoding:e}:{data:Xi.BufferUtils.base64Encode(t),encoding:e?e+"/base64":"base64"}:{data:t,encoding:e}}var Js={encryptData:Bs,encodeData:$s,encodeDataForWire:Ws,decodeData:qs};function Vs(t){var e,{id:n,connectionId:i,timestamp:r}=t;switch(t.action){case Ms.MESSAGE:e=t.messages;break;case Ms.PRESENCE:case Ms.SYNC:e=t.presence;break;case Ms.ANNOTATION:e=t.annotations;break;case Ms.OBJECT:case Ms.OBJECT_SYNC:e=t.state;break;default:throw new rr("Unexpected action "+t.action,4e4,400)}for(var s=0;s<e.length;s++){var o=e[s];o.connectionId||(o.connectionId=i),o.timestamp||(o.timestamp=r),n&&!o.id&&(o.id=n+":"+s)}}function Ks(t,e){var n="["+e;for(var i in t)"data"===i?"string"==typeof t.data?n+="; data="+t.data:Xi.BufferUtils.isBuffer(t.data)?n+="; data (buffer)="+Xi.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 Gs=class{},Xs=class{constructor(t){var e,n,i,r,s,o,a,l,u,h;this.Platform=Xi,this.ErrorInfo=rr,this.Logger=er,this.Defaults=fs,this.Utils=nr,this.EventEmitter=Os,this.MessageEncoding=Js,this.q=null!=(e=t.plugins)?e:null,this.logger=new er,this.logger.setLog(t.logLevel,t.logHandler),this.F=null!=(i=null==(n=t.plugins)?void 0:n.MsgPack)?i:null;var d=this.options=fs.normaliseOptions(t,this.F,this.logger);if(d.key){var c=d.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!c){var v="invalid key parameter";throw er.logAction(this.logger,er.LOG_ERROR,"BaseClient()",v),new rr(v,40400,404)}d.keyName=c[1],d.keySecret=c[2]}if("clientId"in d){if("string"!=typeof d.clientId&&null!==d.clientId)throw new rr("clientId must be either a string or null",40012,400);if("*"===d.clientId)throw new rr('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.$=null,this.serverTimeOffset=null,this.http=new As(this),this.auth=new Cs(this,d),this.H=(null==(r=t.plugins)?void 0:r.Rest)?new t.plugins.Rest(this):null,this.J=null!=(o=null==(s=t.plugins)?void 0:s.Crypto)?o:null,this.__FilteredSubscriptions=null!=(l=null==(a=t.plugins)?void 0:a.MessageInteractions)?l:null,this.V=null!=(h=null==(u=t.plugins)?void 0:u.Annotations)?h:null}get rest(){return this.H||Qr("Rest"),this.H}get K(){return this.__FilteredSubscriptions||Qr("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||Qr("Push"),this.G||(this.G=this.push.LocalDevice.load(this)),this.G}baseUri(t){return fs.getHttpScheme(this.options)+t+":"+fs.getPort(this.options,!1)}stats(t){var e=this;return u(function*(){return e.rest.stats(t)})()}time(t){var e=this;return u(function*(){return e.rest.time(t)})()}request(t,e,n,i,r,s){var o=this;return u(function*(){return o.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 u(function*(){return!e.isTimeOffsetSet()&&t?e.time():e.getTimestampUsingOffset()})()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return null!==this.serverTimeOffset}};Xs.Platform=Xi;var Qs=Xs,Zs=["message.create","message.update","message.delete","meta","message.summary","message.append"];function Ys(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+=Pr(t.data)),e}function to(){return(to=u(function*(t,e){return Promise.all(t.map(t=>t.encode(e)))})).apply(this,arguments)}var eo=class t extends Gs{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 u(function*(){return function(t,e){return Ls.apply(this,arguments)}(Object.assign(new no,e,{action:Zs.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 Ks(this,"Message")}},no=class t extends Gs{toJSON(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return Hs.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 u(function*(){var i,r,s=Object.assign(new eo,Ki(Vi({},n),{action:(i=n.action,Zs[i||0]||"unknown")}));try{yield function(t,e){return zs.apply(this,arguments)}(s,t)}catch(t){er.logAction(e,er.LOG_ERROR,"WireMessage.decode()",Mr(t)),r=t}return s.expandFields(),{decoded:s,err:r}})()}decode(t,e){var n=this;return u(function*(){var{decoded:i}=yield n.decodeWithErr(t,e);return i})()}toString(){return Ks(this,"WireMessage")}},io=eo,ro=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)}},so=function(){};function oo(t){var e=t||{},{agent:n}=e;return((t,e)=>{var n={};for(var i in t)Hi.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&Fi)for(var i of Fi(t))e.indexOf(i)<0&&Wi.call(t,i)&&(n[i]=t[i]);return n})(e,["agent"])}var ao=class t extends Os{constructor(t,e,n){var i,r,s;super(t.logger),this.X=null,this.Y=0,this.retryCount=0,this.history=function(){var t=u(function*(t){var e=this.client.rest.channelMixin;if(t&&t.untilAttach){if("attached"!==this.state)throw new rr("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new rr("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=>Os.prototype.whenState.call(this,t,this.state),this.name=e,this.channelOptions=ds(null!=(i=t.J)?i:null,this.logger,n),this.client=t,this.tt=t.et?new t.et.RealtimePresence(this):null,t.V&&(this.X=new t.V.RealtimeAnnotations(this)),this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new Os(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this.nt=!1,this.it={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this.rt={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this.st=new Os(this.logger),(null==(r=t.options.plugins)?void 0:r.Push)&&(this.ot=new t.options.plugins.Push.PushChannel(this)),(null==(s=t.options.plugins)?void 0:s.LiveObjects)&&(this.lt=new t.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this.tt||Qr("RealtimePresence"),this.tt}get annotations(){return this.X||Qr("Annotations"),this.X}get push(){return this.ot||Qr("Push"),this.ot}get object(){return this.lt||Qr("LiveObjects"),this.lt}invalidStateError(){return new rr("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 u(function*(){var n,i=e.channelOptions,r=function(t){if(t&&"params"in t&&!ur(t.params))return new rr("options.params must be an object",4e4,400);if(t&&"modes"in t){if(!Array.isArray(t.modes))return new rr("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||!Us.includes(String.prototype.toUpperCase.call(n)))return new rr("Invalid channel mode: "+n,4e4,400)}}}(t);if(r)throw r;if(e.channelOptions=ds(null!=(n=e.client.J)?n:null,e.logger,t),e.it&&(e.it.channelOptions=e.channelOptions),e.ut(t,i))return e.attachImpl(),new Promise((t,n)=>{e.st.once(["attached","update","detached","failed"],function(e){switch(this.event){case"update":case"attached":t();break;default:n(e.reason)}})})})()}ut(t,e){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==t?void 0:t.params){var n=oo(t.params),i=oo(e.params);if(Object.keys(n).length!==Object.keys(i).length)return!0;if(!Jr(i,n))return!0}return!(!(null==t?void 0:t.modes)||e.modes&&Gr(t.modes,e.modes))}publish(){var t=arguments,e=this;return u(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=[io.fromValues({name:r,data:s})],i=t.length<=2?void 0:t[2];else if(ur(r))n=[io.fromValues(r)],i=t.length<=1?void 0:t[1];else{if(!Array.isArray(r))throw new rr("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n=io.fromValuesArray(r),i=t.length<=1?void 0:t[1]}var o=e.client.options.maxMessageSize,a=yield function(t,e){return to.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=Ys(e));return n}(a);if(l>o)throw new rr("Maximum size of messages that can be published at once exceeded (was "+l+" bytes; limit is "+o+" bytes)",40009,400);e.throwIfUnpublishableState();var u=co({action:Ms.MESSAGE,channel:e.name,messages:a,params:i?Ar(i):void 0});return(yield e.sendMessage(u))||{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 u(function*(){return"attached"===t.state?null:new Promise((e,n)=>{t.ht(!1,null,(t,i)=>t?n(t):e(i))})})()}ht(t,e,n){n||(n=t=>{t&&er.logAction(this.logger,er.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 rr("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new rr("Attach request superseded by a subsequent detach request",9e4,409))}})):n(i.getError())}attachImpl(){var t=co({action:Ms.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&t.encodeModesToFlags(zr(this.channelOptions.modes)),this.nt&&t.setFlag("ATTACH_RESUME"),this.rt.decodeFailureRecoveryInProgress&&(t.channelSerial=this.rt.protocolMessageChannelSerial),this.sendMessage(t).catch(so)}detach(){var t=this;return u(function*(){var e=t.connectionManager;switch(t.state){case"suspended":return void t.notifyState("detached");case"detached":return;case"failed":throw new rr("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 rr("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":i(new rr("Detach request superseded by a subsequent attach request",9e4,409))}})})}})()}detachImpl(){var t=co({action:Ms.DETACH,channel:this.name});this.sendMessage(t).catch(so)}subscribe(){var e=arguments,n=this;return u(function*(){for(var i=e.length,r=new Array(i),s=0;s<i;s++)r[s]=e[s];var[o,a]=t.processListenerArgs(r);if("failed"===n.state)throw rr.fromValues(n.invalidStateError());return o&&"object"==typeof o&&!Array.isArray(o)?n.client.K.subscribeFilter(n,o,a):n.subscriptions.on(o,a),!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,o]=t.processListenerArgs(i);"object"==typeof s&&!o||(null==(e=this.filteredSubscriptions)?void 0:e.has(o))?this.client.K.getAndDeleteFilteredSubscriptions(this,s,o).forEach(t=>this.subscriptions.off(t)):this.subscriptions.off(s,o)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new sr("Unable to sync to channel; not attached",4e4)}var t=this.connectionManager;if(!t.activeState())throw t.getError();var e=co({action:Ms.SYNC,channel:this.name});this.syncChannelSerial&&(e.channelSerial=this.syncChannelSerial),t.send(e)}sendMessage(t){var e=this;return u(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 u(function*(){var n=co({action:Ms.PRESENCE,channel:e.name,presence:t});yield e.sendMessage(n)})()}sendState(t){var e=this;return u(function*(){var n=co({action:Ms.OBJECT,channel:e.name,state:t});yield e.sendMessage(n)})()}processMessage(t){var e=this;return u(function*(){t.action!==Ms.ATTACHED&&t.action!==Ms.MESSAGE&&t.action!==Ms.PRESENCE&&t.action!==Ms.OBJECT&&t.action!==Ms.ANNOTATION||e.setChannelSerial(t.channelSerial);var n,i=!1;switch(t.action){case Ms.ATTACHED:e.properties.attachSerial=t.channelSerial,e.Y=t.getMode(),e.params=t.params||{};var r=t.decodeModesFromFlags();e.modes=r&&$r(r)||void 0;var s=t.hasFlag("RESUMED"),o=t.hasFlag("HAS_PRESENCE"),a=t.hasFlag("HAS_BACKLOG"),l=t.hasFlag("HAS_OBJECTS");if("attached"===e.state){s||(e.tt&&e.tt.onAttached(o),e.lt&&e.lt.onAttached(l));var u=new ro(e.state,e.state,s,a,t.error);e.st.emit("update",u),s&&!e.channelOptions.updateOnAttached||e.emit("update",u)}else"detaching"===e.state?e.checkPendingState():e.notifyState("attached",t.error,s,o,a,l);break;case Ms.DETACHED:var h=t.error?rr.fromValues(t.error):new rr("Channel detached",90001,404);"detaching"===e.state?e.notifyState("detached",h):"attaching"===e.state?e.notifyState("suspended",h):"attached"!==e.state&&"suspended"!==e.state||e.requestState("attaching",h);break;case Ms.SYNC:if(i=!0,n=e.syncChannelSerial=t.channelSerial,!t.presence)break;case Ms.PRESENCE:if(!t.presence)break;Vs(t);var d=e.channelOptions;if(e.tt){var c=yield Promise.all(t.presence.map(t=>t.decode(d,e.logger)));e.tt.setPresence(c,i,n)}break;case Ms.OBJECT:case Ms.OBJECT_SYNC:if(!e.lt||!t.state)return;Vs(t);var v=e.client.connection.connectionManager.getActiveTransportFormat(),f=t.state.map(t=>t.decode(e.client,v));t.action===Ms.OBJECT?e.lt.handleObjectMessages(f):e.lt.handleObjectSyncMessages(f,t.channelSerial);break;case Ms.MESSAGE:if("attached"!==e.state)return;Vs(t);var p=t.messages,g=p[0],m=p[p.length-1];if(g.extras&&g.extras.delta&&g.extras.delta.from!==e.rt.messageId){var b='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+e.name+'".';er.logAction(e.logger,er.LOG_ERROR,"RealtimeChannel.processMessage()",b),e.dt(new rr(b,40018,400));break}for(var y=[],w=0;w<p.length;w++){var{decoded:x,err:_}=yield p[w].decodeWithErr(e.it,e.logger);if(y[w]=x,_)switch(_.code){case 40018:return void e.dt(_);case 40019:case 40021:return void e.notifyState("failed",_)}}e.rt.messageId=m.id,e.rt.protocolMessageChannelSerial=t.channelSerial,e.onEvent(y);break;case Ms.ANNOTATION:Vs(t);var k=e.channelOptions;if(e.X){var S=yield Promise.all((t.annotations||[]).map(t=>t.decode(k,e.logger)));e.X.ct(S)}break;case Ms.ERROR:var C=t.error;C&&80016==C.code?e.checkPendingState():e.notifyState("failed",rr.fromValues(C))}})()}dt(t){this.rt.decodeFailureRecoveryInProgress||(this.rt.decodeFailureRecoveryInProgress=!0,this.ht(!0,t,()=>{this.rt.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.tt&&this.tt.actOnChannelState(t,i,e),this.lt&&this.lt.actOnChannelState(t,s),"suspended"===t&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),e&&(this.errorReason=e);var o=new ro(this.state,t,n,r,e),a='Channel state for channel "'+this.name+'"',l=t+(e?"; reason: "+e:"");"failed"===t&&er.logAction(this.logger,er.LOG_ERROR,a,l),"attaching"!==t&&"suspended"!==t&&(this.retryCount=0),"attached"===t&&this.onAttached(),"attached"===t?this.nt=!0:"detaching"!==t&&"failed"!==t||(this.nt=!1),this.state=t,this.st.emit(t,o),this.emit(t,o)}}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 rr("Channel attach timed out",90007,408);this.notifyState("suspended",t);break;case"detaching":var e=new rr("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=Hr(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 rr("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 u(function*(){return t.client.rest.channelMixin.status(t)})()}getMessage(t){var e=this;return u(function*(){return e.client.rest.channelMixin.getMessage(e,t)})()}updateMessage(t,e,n){var i=this;return u(function*(){return i.sendUpdate(t,"message.update",e,n)})()}deleteMessage(t,e,n){var i=this;return u(function*(){return i.sendUpdate(t,"message.delete",e,n)})()}appendMessage(t,e,n){var i=this;return u(function*(){return i.sendUpdate(t,"message.append",e,n)})()}sendUpdate(t,e,n,i){var r=this;return u(function*(){var s,o;if(!t.serial)throw new rr('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 a=io.fromValues(Ki(Vi({},t),{action:e,version:n})),l=yield a.encode(r.channelOptions),u=co({action:Ms.MESSAGE,channel:r.name,messages:[l],params:i?Ar(i):void 0}),h=yield r.sendMessage(u);return{versionSerial:null!=(o=null==(s=null==h?void 0:h.serials)?void 0:s[0])?o:null}})()}getMessageVersions(t,e){var n=this;return u(function*(){return n.client.rest.channelMixin.getMessageVersions(n,t,e)})()}ensureAttached(){var t=this;return u(function*(){switch(t.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":yield t.attach();break;default:throw rr.fromValues(t.invalidStateError())}})()}},lo=Lr;function uo(t){var e=[];if(t)for(var n=0;n<t.length;n++)e.push(t[n].toString());return"[ "+e.join(", ")+" ]"}function ho(t,e,n,i,r,s){return function(t,e,n,i){var r,s,o,a,l;t.error&&(r=rr.fromValues(t.error));t.messages&&(s=no.fromValuesArray(t.messages));e&&t.presence&&(o=e.WirePresenceMessage.fromValuesArray(t.presence));n&&t.annotations&&(a=n.WireAnnotation.fromValuesArray(t.annotations));i&&t.state&&(l=i.WireObjectMessage.fromValuesArray(t.state,nr,Js));return Object.assign(new fo,Ki(Vi({},t),{presence:o,messages:s,annotations:a,state:l,error:r}))}(Nr(t,e,s),n,i,r)}function co(t){return Object.assign(new fo,t)}function vo(t,e,n,i){var r="[ProtocolMessage";void 0!==t.action&&(r+="; action="+Rs[t.action]||t.action);for(var s,o=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],a=0;a<o.length;a++)void 0!==t[s=o[a]]&&(r+="; "+s+"="+t[s]);if(t.messages&&(r+="; messages="+uo(no.fromValuesArray(t.messages))),t.presence&&e&&(r+="; presence="+uo(e.WirePresenceMessage.fromValuesArray(t.presence))),t.annotations&&n&&(r+="; annotations="+uo(n.WireAnnotation.fromValuesArray(t.annotations))),t.state&&i&&(r+="; state="+uo(i.WireObjectMessage.fromValuesArray(t.state,nr,Js))),t.error&&(r+="; error="+rr.fromValues(t.error).toString()),t.auth&&t.auth.accessToken&&(r+="; token="+t.auth.accessToken),t.flags&&(r+="; flags="+Ds.filter(t.hasFlag).join(",")),t.params){var l="";kr(t.params,function(e){l.length>0&&(l+="; "),l+=e+"="+t.params[e]}),l.length>0&&(r+="; params=["+l+"]")}return r+="]"}var fo=class{constructor(){this.hasFlag=t=>(this.flags&Ps[t])>0}setFlag(t){return this.flags=this.flags|Ps[t]}getMode(){return(this.flags||0)&Ps.MODE_ALL}encodeModesToFlags(t){t.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){var t=[];return Us.forEach(e=>{this.hasFlag(e)&&t.push(e)}),t.length>0?t:void 0}},po=class extends Os{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 o=s.message.msgSerial,a=t.serial+t.count;a>o&&(r=i.splice(0,a-o))}}for(var l=0;l<r.length;l++){var u=r[l],h=null==n?void 0:n[l];u.callback(e,h)}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")}},go=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&&[Ms.MESSAGE,Ms.PRESENCE,Ms.ANNOTATION,Ms.OBJECT].includes(n)}},mo=class extends Os{constructor(t){super(t.logger),this.transport=t,this.messageQueue=new po(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){er.logAction(this.logger,er.LOG_ERROR,"Protocol.onNack()","serial = "+t+"; count = "+e+"; err = "+Mr(n)),n||(n=new rr("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(er.LOG_MICRO)&&er.logActionNoStrip(this.logger,er.LOG_MICRO,"Protocol.send()","sending msg; "+vo(t.message,this.transport.connectionManager.realtime.et,this.transport.connectionManager.realtime.V,this.transport.connectionManager.realtime.ft)),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()})}},bo=class{constructor(t,e,n,i){this.previous=t,this.current=e,n&&(this.retryIn=n),i&&(this.reason=i)}},yo={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001};var wo,xo,_o={disconnected:()=>rr.fromValues({statusCode:400,code:yo.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>rr.fromValues({statusCode:400,code:yo.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>rr.fromValues({statusCode:400,code:yo.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>rr.fromValues({statusCode:400,code:yo.CLOSING,message:"Connection closing"}),closed:()=>rr.fromValues({statusCode:400,code:yo.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>rr.fromValues({statusCode:500,code:yo.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>rr.fromValues({statusCode:500,code:yo.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},ko=co({action:Ms.CLOSE}),So=co({action:Ms.DISCONNECT}),Co=class extends Os{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",_o.closed())}disconnect(t){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",t||_o.disconnected())}fail(t){this.isConnected&&this.requestDisconnect(),this.finish("failed",t||_o.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(er.LOG_MICRO)&&er.logActionNoStrip(this.logger,er.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+vo(t,this.connectionManager.realtime.et,this.connectionManager.realtime.V,this.connectionManager.realtime.ft)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),t.action){case Ms.HEARTBEAT:er.logActionNoStrip(this.logger,er.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",t.id);break;case Ms.CONNECTED:this.onConnect(t),this.emit("connected",t.error,t.connectionId,t.connectionDetails,t);break;case Ms.CLOSED:this.onClose(t);break;case Ms.DISCONNECTED:this.onDisconnect(t);break;case Ms.ACK:this.emit("ack",t.msgSerial,t.count,t.res);break;case Ms.NACK:this.emit("nack",t.msgSerial,t.count,t.error);break;case Ms.SYNC:this.connectionManager.onChannelMessage(t,this);break;case Ms.ACTIVATE:break;case Ms.AUTH:Br(this.auth.authorize(),t=>{t&&er.logAction(this.logger,er.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+Mr(t))});break;case Ms.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(ko)}requestDisconnect(){this.send(So)}ping(t){var e={action:Ms.HEARTBEAT};t&&(e.id=t),this.send(co(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";er.logAction(this.logger,er.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new rr(n,80003,408))}else this.setIdleTimer(e+100)}static tryConnect(t,e,n,i,r){var s,o=new t(e,n,i),a=function(t){clearTimeout(s),r({event:this.event,error:t})},l=e.options.timeouts.realtimeRequestTimeout;return s=setTimeout(()=>{o.off(["preconnect","disconnected","failed"]),o.dispose(),a.call({event:"disconnected"},new rr("Timeout waiting for transport to indicate itself viable",5e4,500))},l),o.on(["failed","disconnected"],a),o.on("preconnect",function(){clearTimeout(s),o.off(["failed","disconnected"],a),r(null,o)}),o.connect(),o}static isAvailable(){throw new rr("isAvailable not implemented for transport",5e4,500)}};(xo=wo||(wo={})).WebSocket="web_socket",xo.Comet="comet",xo.XhrPolling="xhr_polling";var Eo="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,To=()=>{var t;return void 0!==Xi.WebStorage&&(null==(t=Xi.WebStorage)?void 0:t.localSupported)},Ao=()=>{var t;return void 0!==Xi.WebStorage&&(null==(t=Xi.WebStorage)?void 0:t.sessionSupported)},Io=function(){},Oo="ably-transport-preference";function Mo(t){try{return JSON.parse(t)}catch(t){return null}}var Ro=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?ar(t):{},n=this.options;switch(this.mode){case"resume":e.resume=this.connectionKey;break;case"recover":var i=Mo(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=fs.protocolVersion,e.agent=us(this.options),void 0!==n.transportParams&&or(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+="]"}},Po=class t extends Os{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 po(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=gr(e.transports||fs.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(wo.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(wo.XhrPolling)?this.baseTransport=wo.XhrPolling:this.transports.includes(wo.Comet)&&(this.baseTransport=wo.Comet),this.domains=fs.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 er.logAction(this.logger,er.LOG_ERROR,"realtime.ConnectionManager()",r),new Error(r)}var s=Xi.Config.addEventListener;s&&(Ao()&&"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=Vi(Vi({},Xi.Transports.bundledImplementations),t);[wo.WebSocket,...Xi.Transports.order].forEach(t=>{var i=n[t];i&&i.isAvailable()&&(e.supportedTransports[t]=i)})}initTransports(){t.initTransports(this.realtime.gt,this)}createTransportParams(t,e){return new Ro(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=Mo(this.options.recover);i&&(this.msgSerial=i.msgSerial)}t(n)})}tryATransport(t,e,n){this.proposedTransport=Co.tryConnect(this.supportedTransports[e],this,this.realtime.auth,t,(i,r)=>{var s,o=this.state;if(o==this.states.closing||o==this.states.closed||o==this.states.failed)return r&&r.close(),void n(!0);i?!Cs.isTokenErr(i.error)||this.errorReason&&Cs.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(yo).includes(s.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:i.error}),n(!0))):(this.errorReason=i.error,Br(this.realtime.auth.M(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&&er.logAction(this.logger,er.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 o=this.activeProtocol;this.activeProtocol=new mo(e),this.host=e.params.host;var a=i.connectionKey;if(a&&this.connectionKey!=a&&this.setConnection(n,i,!!t),this.onConnectionDetailsUpdate(i,e),Xi.Config.nextTick(()=>{e.on("connected",(t,n,i)=>{this.onConnectionDetailsUpdate(i,e),this.emit("update",new bo(s,s,null,t))})}),r.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new bo(s,s,null,t))):(this.notifyState({state:"connected",error:t}),this.errorReason=this.realtime.connection.errorReason=t||null),this.emit("transport.active",e),o)if(o.messageQueue.count()>0&&er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+o.transport.shortName+", new one is "+e.shortName+") finishing with "+o.messageQueue.count()+" messages still pending"),o.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;er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.activateTransport()",l)}else o.finish();return!0}deactivateTransport(t,e,n){var i=this.activeProtocol,r=i&&i.getTransport()===t,s=t===this.pendingTransport,o=this.noTransportsScheduledForActivation();if(n&&n.message,r&&(this.queuePendingMessages(i.getPendingMessages()),i.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",t),r&&o||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 a="failed"===e&&Cs.isTokenErr(n)?"disconnected":e;this.notifyState({state:a,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(Ao()){var t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:Eo.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=sr.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,e;return null==(e=(t=_o)[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&&er.logAction(this.logger,er.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&&Br(this.realtime.http.checkConnectivity(),(t,e)=>{!t&&e||(this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new rr("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&&Cs.isTokenErr(t.error)&&!(this.errorReason&&Cs.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],o=s.retryDelay;"disconnected"===s.state&&(this.disconnectedRetryCount++,o=Hr(s.retryDelay,this.disconnectedRetryCount));var a=new bo(this.state.state,s.state,o,t.error||(null==(n=(e=_o)[s.state])?void 0:n.call(e)));if(r){var l=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},u=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;u&&u<1e3?setTimeout(l,1e3-u):Xi.Config.nextTick(l)}else"disconnected"!==i&&"suspended"!==i||this.startRetryTimer(o);("disconnected"===i&&!r||"suspended"===i||s.terminal)&&Xi.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=i||this.activeProtocol||er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(a),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(i,a.reason),this.failQueuedMessages(a.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 bo(this.state.state,r.state,null,t.error||(null==(n=(e=_o)[r.state])?void 0:n.call(e)));this.enactStateChange(s),"connecting"==i&&Xi.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=Mo(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&&Cs.isTokenErr(this.errorReason)?Br(t.M(null,null),i):Br(t.R(!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(Io),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 rr("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})},o=this.domains.slice(),a=(t,e)=>{i===this.connectCounter&&(r()?e||t||u():e&&e.dispose())},l=o.shift();if(l){e.host=l;var u=()=>{o.length?this.realtime.http.checkConnectivity?Br(this.realtime.http.checkConnectivity(),(n,l)=>{i===this.connectCounter&&r()&&(n?s(n):l?(e.host=Er(o),this.tryATransport(e,t,a)):s(new rr("Unable to connect (network unreachable)",80003,404)))}):s(new sr("Internal error: Http.checkConnectivity not set",null,500)):s(new rr("Unable to connect (and no more fallback hosts to try)",80003,404))};if(this.forceFallbackHost&&o.length)return this.forceFallbackHost=!1,void u();this.tryATransport(e,t,a)}else s(new rr("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=co({action:Ms.AUTH,auth:{accessToken:t.token}});this.send(r);var s=()=>{this.off(o),e(null,t)},o=t=>{"failed"===t.current&&(this.off(s),this.off(o),e(t.reason||this.getStateError()))};this.once("connectiondetails",s),this.on("connectionstate",o);break;case"connecting":this.disconnectAllTransports();default:var a=n=>{switch(n.current){case"connected":this.off(a),e(null,t);break;case"failed":case"closed":case"suspended":this.off(a),e(n.reason||this.getStateError())}};this.on("connectionstate",a),"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||Io;var i=this.state;if(i.sendEvents)this.sendImpl(new go(t,n));else if(e&&i.queueEvents)this.logger.shouldLog(er.LOG_MICRO),this.queue(t,n);else{var r="rejecting event, queueEvent was "+e+", state was "+i.state;n(this.errorReason||new rr(r,9e4,400))}}sendImpl(t){var e=t.message;t.ackRequired&&!t.sendAttempted&&(e.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(t){er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+t.stack)}}queue(t,e){this.queuedMessages.push(new go(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&&(er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+e+" queued messages, err = "+Mr(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=>{er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",t)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}processChannelMessage(t){var e=this;return u(function*(){yield e.realtime.channels.processChannelMessage(t)})()}ping(){var t=this;return u(function*(){var e;if("connected"!==t.state.state)throw new rr("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=Dr();return Zr(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||To()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.get)?void 0:e.call(t,Oo))}persistTransportPreference(t){var e,n;this.transportPreference=t.shortName,To()&&(null==(n=null==(e=Xi.WebStorage)?void 0:e.set)||n.call(e,Oo,t.shortName))}unpersistTransportPreference(){var t,e;this.transportPreference=null,To()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.remove)||e.call(t,Oo))}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===ys.Forbidden){var e="Client configured authentication provider returned 403; failing the connection";er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",e),this.notifyState({state:"failed",error:new rr(e,80019,403,t)})}else{this.notifyState({state:this.state.failState,error:new rr("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.B(n);if(i)return er.logAction(this.logger,er.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||fs.wsConnectivityCheckUrl,e=new Xi.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 Ao()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.getSession)?void 0:e.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var e,n;return Ao()&&(null==(n=null==(e=Xi.WebStorage)?void 0:e.setSession)?void 0:n.call(e,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,e;return Ao()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.removeSession)?void 0:e.call(t,this.sessionRecoveryName()))}},Do=class extends Os{constructor(t,e){super(t.logger),this.whenState=t=>Os.prototype.whenState.call(this,t,this.state),this.ably=t,this.connectionManager=new Po(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;Xi.Config.nextTick(()=>{this.emit(e,t)})}),this.connectionManager.on("update",t=>{Xi.Config.nextTick(()=>{this.emit("update",t)})})}connect(){this.connectionManager.requestState({state:"connecting"})}ping(){var t=this;return u(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()}},Uo=class t extends Qs{constructor(e){var n,i,r,s;if(super(fs.objectifyOptions(e,!1,"BaseRealtime",er.defaultLogger)),"string"==typeof EdgeRuntime)throw new rr('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.gt=t.transportImplementationsFromPlugins(this.options.plugins),this.et=null!=(i=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?i:null,this.ft=null!=(s=null==(r=this.options.plugins)?void 0:r.LiveObjects)?s:null,this.connection=new Do(this,this.options),this.bt=new Bo(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(t){var e={};return(null==t?void 0:t.WebSocketTransport)&&(e[wo.WebSocket]=t.WebSocketTransport),(null==t?void 0:t.XHRPolling)&&(e[wo.XhrPolling]=t.XHRPolling),e}get channels(){return this.bt}get clientId(){return this.auth.clientId}connect(){this.connection.connect()}close(){this.connection.close()}};Uo.EventEmitter=Os;var jo=Uo,Bo=class extends Os{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 xr(this.all,!0)){var n=this.all[e];n.properties.channelSerial&&(t[e]=n.properties.channelSerial)}return t}recoverChannels(t){for(var e of xr(t,!0)){this.get(e).properties.channelSerial=t[e]}}processChannelMessage(t){var e=this;return u(function*(){var n=t.channel;if(void 0!==n){var i=e.all[n];i?yield i.processMessage(t):er.logAction(e.logger,er.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n)}else er.logAction(e.logger,er.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.ht(!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.ut(e,n.channelOptions))throw new rr("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 ao(this.realtime,t,e);return n}getDerived(t,e,n){if(e.filter){var i=Kr(e.filter),r=Vr(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]}}},No=jo,Lo=Uint8Array,$o=Uint32Array,zo=Math.pow,qo=new $o(8),Fo=[],Ho=new $o(64);function Wo(t){return(t-(0|t))*zo(2,32)|0}for(var Jo,Vo,Ko=2,Go=0;Go<64;){for(Jo=!0,Vo=2;Vo<=Ko/2;Vo++)Ko%Vo===0&&(Jo=!1);Jo&&(Go<8&&(qo[Go]=Wo(zo(Ko,.5))),Fo[Go]=Wo(zo(Ko,1/3)),Go++),Ko++}var Xo=!!new Lo(new $o([1]).buffer)[0];function Qo(t){return Xo?t>>>24|(t>>>16&255)<<8|(65280&t)<<8|t<<24:t}function Zo(t,e){return t>>>e|t<<32-e}function Yo(t){var e,n=qo.slice(),i=t.length,r=8*i,s=512-(r+64)%512-1+r+65,o=new Lo(s/8),a=new $o(o.buffer);o.set(t,0),o[i]=128,a[a.length-1]=Qo(r);for(var l=0;l<s/32;l+=16){var u=n.slice();for(e=0;e<64;e++){var h;if(e<16)h=Qo(a[l+e]);else{var d=Ho[e-15],c=Ho[e-2];h=Ho[e-7]+Ho[e-16]+(Zo(d,7)^Zo(d,18)^d>>>3)+(Zo(c,17)^Zo(c,19)^c>>>10)}Ho[e]=h|=0;for(var v=(Zo(u[4],6)^Zo(u[4],11)^Zo(u[4],25))+(u[4]&u[5]^~u[4]&u[6])+u[7]+h+Fo[e],f=(Zo(u[0],2)^Zo(u[0],13)^Zo(u[0],22))+(u[0]&u[1]^u[2]&(u[0]^u[1])),p=7;p>0;p--)u[p]=u[p-1];u[0]=v+f|0,u[4]=u[4]+v|0}for(e=0;e<8;e++)n[e]=n[e]+u[e]|0}return new Lo(new $o(n.map(function(t){return Qo(t)})).buffer)}var ta,ea=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(t){for(var e,n,i,r,s="",o=this.base64CharSet,a=t.byteLength,l=a%3,u=a-l,h=0;h<u;h+=3)e=(258048&(r=t[h]<<16|t[h+1]<<8|t[h+2]))>>12,n=(4032&r)>>6,i=63&r,s+=o[(16515072&r)>>18]+o[e]+o[n]+o[i];return 1==l?(e=(3&(r=t[u]))<<4,s+=o[(252&r)>>2]+o[e]+"=="):2==l&&(e=(1008&(r=t[u]<<8|t[u+1]))>>4,n=(15&r)<<2,s+=o[(64512&r)>>10]+o[e]+o[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&&Xi.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(Xi.Config.TextEncoder){var e=(new Xi.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),o=0;o<r.length;o++)if(r[o]!=s[o])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=Yo(this.toBuffer(t));return this.toArrayBuffer(e)}hmacSha256(t,e){var n=function(t,e){if(t.length>64&&(t=Yo(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 o=new Uint8Array(e.length+64);o.set(i,0),o.set(e,64);var a=new Uint8Array(96);return a.set(r,0),a.set(Yo(o),64),Yo(a)}(this.toBuffer(e),this.toBuffer(t));return this.toArrayBuffer(n)}},na=(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))(na||{}),ia=na;function ra(){return new rr("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var sa=(ta=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)||fs.connectivityCheckUrl,i=null!=(e=null==t?void 0:t.options.connectivityCheckParams)?e:null,r=!(null==t?void 0:t.options.connectivityCheckUrl),s=Vi(Vi({},sa.bundledRequestImplementations),null==t?void 0:t.q),o=s.XHRRequest,a=s.FetchRequest,l=!(!o&&!a);if(!l)throw ra();Xi.Config.xhrSupported&&o?(this.supportsAuthHeaders=!0,this.Request=function(){var e=u(function*(e,n,i,r,s){return new Promise(a=>{var l,u=o.createRequest(n,i,r,s,ia.REQ_SEND,null!=(l=t&&t.options.timeouts)?l:null,this.logger,e);u.once("complete",(t,e,n,i,r)=>a({error:t,body:e,headers:n,unpacked:i,statusCode:r})),u.exec()})});return function(t,n,i,r,s){return e.apply(this,arguments)}}(),(null==t?void 0:t.options.disableConnectivityCheck)?this.checkConnectivity=u(function*(){return!0}):this.checkConnectivity=u(function*(){var t,e,s=yield this.doUri(ms.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)})):Xi.Config.fetchSupported&&a?(this.supportsAuthHeaders=!0,this.Request=function(){var e=u(function*(e,n,i,r,s){return a(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=u(function*(){return!0}):this.checkConnectivity=u(function*(){var t,e=yield this.doUri(ms.Get,n,null,null,null);return!e.error&&"yes"==(null==(t=e.body)?void 0:t.replace(/\n/,""))})):this.Request=u(function*(){return{error:l?new sr("no supported HTTP transports available",null,400):ra()}})}get logger(){var t,e;return null!=(e=null==(t=this.client)?void 0:t.logger)?e:er.defaultLogger}doUri(t,e,n,i,r){var s=this;return u(function*(){return s.Request?s.Request(t,e,n,r,i):{error:new sr("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}},ta.methods=[ms.Get,ms.Delete,ms.Post,ms.Put,ms.Patch],ta.methodsWithoutBody=[ms.Get,ms.Delete],ta.methodsWithBody=[ms.Post,ms.Put,ms.Patch],ta),oa=sa,aa="ablyjs-storage-test",la="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,ua=new class{constructor(){try{la.sessionStorage.setItem(aa,aa),la.sessionStorage.removeItem(aa),this.sessionSupported=!0}catch(t){this.sessionSupported=!1}try{la.localStorage.setItem(aa,aa),la.localStorage.removeItem(aa),this.localSupported=!0}catch(t){this.localSupported=!1}}get(t){return this.yt(t,!1)}getSession(t){return this.yt(t,!0)}remove(t){return this.wt(t,!1)}removeSession(t){return this.wt(t,!0)}set(t,e,n){return this.xt(t,e,n,!1)}setSession(t,e,n){return this.xt(t,e,n,!0)}xt(t,e,n,i){var r={value:e};return n&&(r.expires=Date.now()+n),this.storageInterface(i).setItem(t,JSON.stringify(r))}yt(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}wt(t,e){return this.storageInterface(e).removeItem(t)}storageInterface(t){return t?la.sessionStorage:la.localStorage}},ha=Wr(),da="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||da||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var ca,va,fa={agent:"browser",logTimestamps:!0,userAgent:ha.navigator&&ha.navigator.userAgent.toString(),currentUrl:ha.location&&ha.location.href,binaryType:"arraybuffer",WebSocket:ha.WebSocket,fetchSupported:!!ha.fetch,xhrSupported:ha.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:(va=ha.location,!ha.WebSocket||!va||!va.origin||va.origin.indexOf("http")>-1),useProtocolHeartbeats:!0,supportsBinary:!!ha.TextDecoder,preferBinary:!1,ArrayBuffer:ha.ArrayBuffer,atob:ha.atob,nextTick:"function"==typeof ha.queueMicrotask?t=>ha.queueMicrotask(t):t=>Promise.resolve().then(t),addEventListener:ha.addEventListener,inspect:JSON.stringify,stringByteSize:function(t){return ha.TextDecoder&&(new ha.TextEncoder).encode(t).length||t.length},TextEncoder:ha.TextEncoder,TextDecoder:ha.TextDecoder,getRandomArrayBuffer:(ca=u(function*(t){var e=new Uint8Array(t);return ha.crypto.getRandomValues(e),e.buffer}),function(t){return ca.apply(this,arguments)}),isWebworker:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,push:{platform:"browser",formFactor:"desktop",storage:ua}},pa=fa;wo.XhrPolling;var ga=wo.WebSocket;var ma=class extends Co{constructor(t,e,n){super(t,e,n),this.shortName=ga,n.heartbeats=Xi.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!Xi.Config.WebSocket}createWebSocket(t,e){return this.uri=t+Tr(e),new Xi.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){Co.prototype.connect.call(this);var t=this,e=this.params,n=e.options,i=(n.tls?"wss://":"ws://")+this.wsHost+":"+fs.getPort(n)+"/";Br(this.auth.getAuthParams(),function(n,r){if(!t.isDisposed){for(var s in r)" "+s+": "+r[s]+";";if(n)t.disconnect(n);else{var o=e.getConnectParams(r);try{var a=t.wsConnection=t.createWebSocket(i,o);a.binaryType=Xi.Config.binaryType,a.onopen=function(){t.onWsOpen()},a.onclose=function(e){t.onWsClose(e)},a.onmessage=function(e){t.onWsData(e.data)},a.onerror=function(e){t.onWsError(e)},a.on&&a.on("ping",function(){t.onActivity()})}catch(e){er.logAction(t.logger,er.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(lo(t,this.connectionManager.realtime.F,this.params.format))}catch(t){var n="Exception from ws connection when trying to send: "+Mr(t);er.logAction(this.logger,er.LOG_ERROR,"WebSocketTransport.send()",n),this.finish("disconnected",new rr(n,5e4,500))}else er.logAction(this.logger,er.LOG_ERROR,"WebSocketTransport.send()","No socket connection")}onWsData(t){try{this.onProtocolMessage(ho(t,this.connectionManager.realtime.F,this.connectionManager.realtime.et,this.connectionManager.realtime.V,this.connectionManager.realtime.ft,this.format))}catch(t){er.logAction(this.logger,er.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 rr("Websocket closed",80003,400);this.finish("disconnected",i)}else{var r=new rr("Unclean disconnection of WebSocket ; code = "+n,80003,400);this.finish("disconnected",r)}this.emit("disposed")}onWsError(t){Xi.Config.nextTick(()=>{this.disconnect(Error(t.message))})}dispose(){this.isDisposed=!0;var t=this.wsConnection;t&&(t.onmessage=function(){},delete this.wsConnection,Xi.Config.nextTick(()=>{if(!t)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");t.close()}))}},ba={order:["xhr_polling"],bundledImplementations:{}},ya={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[wo.XhrPolling,wo.WebSocket]};function wa(t,e,n,i,r,s){return xa.apply(this,arguments)}function xa(){return(xa=u(function*(t,e,n,i,r,s){var o,a=new Headers(i||{}),l=t?t.toUpperCase():dr(s)?"GET":"POST",h=new AbortController,d=new Promise(t=>{o=setTimeout(()=>{h.abort(),t({error:new sr("Request timed out",null,408)})},e?e.options.timeouts.httpRequestTimeout:fs.TIMEOUTS.httpRequestTimeout)}),c={method:l,headers:a,body:s,signal:h.signal};Xi.Config.isWebworker||(c.credentials=a.has("authorization")?"include":"same-origin");var v=u(function*(){try{var t=new URLSearchParams(r||{});t.set("rnd",Dr());var e=n+"?"+t,i=yield Wr().fetch(e,c);if(clearTimeout(o),204==i.status)return{error:null,statusCode:i.status};var s,a=i.headers.get("Content-Type");s=a&&a.indexOf("application/x-msgpack")>-1?yield i.arrayBuffer():a&&a.indexOf("application/json")>-1?yield i.json():yield i.text();var l=!!a&&-1===a.indexOf("application/x-msgpack"),u=function(t){var e={};return t.forEach((t,n)=>{e[n]=t}),e}(i.headers);if(i.ok)return{error:null,body:s,headers:u,unpacked:l,statusCode:i.status};var h=function(t,e){if(function(t,e){return!!e.get("x-ably-errorcode")}(0,e))return t.error&&rr.fromValues(t.error)}(s,i.headers)||new sr("Error response received from server: "+i.status+" body was: "+Xi.Config.inspect(s),null,i.status);return{error:h,body:s,headers:u,unpacked:l,statusCode:i.status}}catch(h){return clearTimeout(o),{error:h}}})();return Promise.race([d,v])})).apply(this,arguments)}var _a;function ka(t,e){var n,i,r=null!==(n=t.metadata)&&void 0!==n?n:{},s=null!==(i=e.metadata)&&void 0!==i?i:{};return!s.widgets&&r.T?h({},e,{metadata:h({},s,{T:r.T})}):e}function Sa(t,e,n,i){var r,s,o,a=(s=t.messages.value,o=e.id,s.some(t=>t.id===o));if(t.setMessages(function(t,e){var n=t.findIndex(t=>t.id===e.id);if(-1!==n){var i=t[n],r=ka(i,e);if(function(t,e){return t.id===e.id&&t.channel_id===e.channel_id&&t.sender_type===e.sender_type&&t.sender_id===e.sender_id&&t.sender_name===e.sender_name&&t.sender_avatar_url===e.sender_avatar_url&&t.content===e.content&&t.content_type===e.content_type&&t.created_at===e.created_at&&t.metadata===e.metadata}(i,r))return t;var s=[...t];return s[n]=r,s}if("ai"===e.sender_type){var o=t.findIndex(t=>t.id.startsWith("temp-ai-"));if(-1!==o){var a=ka(t[o],e),l=[...t];return l[o]=a,l}}return ci(t,e)}(t.messages.value,e)),"user"!==e.sender_type||e.sender_id!==n){if(!a){if("ai"===e.sender_type||"agent"===e.sender_type){var l=t.isOpen.value,u=(null===(r=t.channel.value)||void 0===r?void 0:r.id)===e.channel_id;if(l&&u)i.onAgentMessageWhileOpen();else{var d=t.channels.value.findIndex(t=>t.id===e.channel_id);if(-1!==d){var c=[...t.channels.value];c[d]=h({},c[d],{unread_count:(c[d].unread_count||0)+1}),t.channels.value=c}}i.onTrack(e)}t.isTyping.value=!1,t.typingSender.value=null,t.typingSenderType.value=null,i.onMessageDispatched(e)}}else i.onMessageDispatched(e)}Xi.BufferUtils=ea,Xi.Http=oa,Xi.Config=pa,Xi.Transports=ba,Xi.WebStorage=ua,oa.bundledRequestImplementations={},er.initLogHandlers(),Xi.Defaults=(_a=ya,Object.assign(ns,_a)),Xi.Config.agent&&(Xi.Defaults.agent+=" "+Xi.Config.agent);var Ca="chat.ably";function Ea(t,e,n){return Ta.apply(this,arguments)}function Ta(){return(Ta=u(function*(t,e,n){return it(t,nt,{method:"POST",body:JSON.stringify(h({distinct_id:e},n&&{channel_id:n}))})})).apply(this,arguments)}function Aa(){return(Aa=u(function*(t,e){var n=yield Ea(t,e);return(null==n?void 0:n.tokenRequest)?n.clientId&&null!=n.project_id?{tokenRequest:n.tokenRequest,clientId:n.clientId,projectId:n.project_id}:(T().warn(Ca,"token:request:incomplete — missing clientId or project_id"),null):(T().warn(Ca,"token:request:failed (initial)"),null)})).apply(this,arguments)}var Ia="chat.ably";function Oa(t,e){var n=(()=>{if(!e||"object"!=typeof e)return String(e);var t=e,n="string"==typeof t.message?t.message:String(e),i="number"==typeof t.code?t.code:null,r="number"==typeof t.statusCode?t.statusCode:null;return i||r?n+" (code="+(null!=i?i:"-")+", status="+(null!=r?r:"-")+")":n})(),i=n.toLowerCase();return i.includes("timeout for trying fallback hosts")||i.includes("connection failed")||i.includes("network")||i.includes("failed to fetch")?t+" — "+n+" (browser cannot reach Ably hosts (*.ably.io / *.ably-realtime.com) — check ad-blocker, firewall, VPN, or offline state)":t+" — "+n}var Ma=t=>new No(t);class Ra{constructor(t,e,n,i){void 0===i&&(i=Ma),this.instance=t,this.store=e,this.hooks=n,this._t=null,this.kt=null,this.St=null,this.Ct=null,this.Et=null,this.Tt=i}get clientId(){var t,e;return null!==(e=null===(t=this._t)||void 0===t?void 0:t.auth.clientId)&&void 0!==e?e:null}get isLive(){return null!=this._t}get currentChannelId(){return this.store.realtimeChannelId.value}ensureConnected(){var t=this;return u(function*(){if(!t._t){t.store.connectionState.value="connecting",T().debug(Ia,"connect:start");var e=t.hooks.getDistinctId(),n=yield function(t,e){return Aa.apply(this,arguments)}(t.instance,e);if(n){t.store.ablyProjectId.value=n.projectId;var i,r=n.clientId,s=t.Tt({plugins:{WebSocketTransport:ma,FetchRequest:wa},authCallback:(i={instance:t.instance,getDistinctId:()=>t.hooks.getDistinctId(),getChannelScope:()=>{var e,n,i,r;return null!==(r=null!==(n=null!==(e=t.store.pendingRealtimeChannelId.value)&&void 0!==e?e:t.store.realtimeChannelId.value)&&void 0!==n?n:null===(i=t.store.channel.value)||void 0===i?void 0:i.id)&&void 0!==r?r:null},getLiveClientId:()=>{var e,n;return null!==(n=null===(e=t._t)||void 0===e?void 0:e.auth.clientId)&&void 0!==n?n:null},onIdentityChange:()=>t.hooks.onIdentityChange()},function(){var t=u(function*(t,e){try{var n=i.getChannelScope(),r=yield Ea(i.instance,i.getDistinctId(),null!=n?n:void 0);if(!(null==r?void 0:r.tokenRequest))return void e("Failed to refresh token",null);var s=r.tokenRequest.clientId,o=i.getLiveClientId();if(o&&s&&s!==o)return T().warn(Ca,"token:request:clientid-mismatch — recreating connection"),e("clientId changed; recreating connection",null),void i.onIdentityChange();e(null,r.tokenRequest)}catch(t){e(String(t),null)}});return function(e,n){return t.apply(this,arguments)}}()),authMethod:"POST"});t._t=s,s.connection.on("connected",()=>{t.store.connectionState.value="connected",t.At(),T().debug(Ia,"connect:connected")}),s.connection.on("disconnected",()=>{t.store.connectionState.value="disconnected",T().debug(Ia,"connect:disconnected")}),s.connection.on("suspended",()=>{t.store.connectionState.value="suspended",T().debug(Ia,"connect:suspended")}),s.connection.on("failed",()=>{t.store.connectionState.value="failed",T().debug(Ia,"connect:failed")});try{yield s.auth.authorize(n.tokenRequest)}catch(e){return T().error(Ia,Oa("connect:authorize-failed",e)),void(t.store.connectionState.value="failed")}var o=s.connection.state;"connected"===o?(t.store.connectionState.value="connected",t.At(),T().debug(Ia,"connect:connected (sync)")):"disconnected"!==o&&"suspended"!==o&&"failed"!==o||(t.store.connectionState.value=o,T().debug(Ia,"connect:"+o+" (sync)"));var a="chat:"+n.projectId+":notifications";t.kt=s.channels.get(a),t.kt.subscribe("notification",e=>{!function(t,e,n){var i,r,s,{type:o,channel_id:a,data:l}=e;if("new_channel"!==o)if("channel_updated"===o&&l){var u=t.channels.value.findIndex(t=>t.id===a);if(-1!==u){var d={};void 0!==l.last_message_at&&(d.last_message_at=l.last_message_at),void 0!==l.last_message_preview&&(d.last_message_preview=l.last_message_preview),void 0!==l.last_message_sender&&(d.last_message_sender=l.last_message_sender),void 0!==l.user_unread_count&&(t.isOpen.value&&(null===(i=t.channel.value)||void 0===i?void 0:i.id)===a||(d.unread_count=l.user_unread_count)),void 0!==l.status&&(d.status=l.status),void 0!==l.ai_mode&&(d.ai_mode=l.ai_mode),t.patchChannelSummary(a,d)}(null===(r=t.channel.value)||void 0===r?void 0:r.id)===a&&"closed"===l.status&&(t.channel.value=h({},t.channel.value,{status:"closed"}))}else"channel_closed"===o&&(t.patchChannelSummary(a,{status:"closed"}),(null===(s=t.channel.value)||void 0===s?void 0:s.id)===a&&(t.channel.value=h({},t.channel.value,{status:"closed"})));else n.onNewChannel()}(t.store,e.data,{onNewChannel:t.hooks.onNewChannelNotification})}),t.store.lastConnectedDistinctId.value=r.split(":").slice(1).join(":")||e}else t.store.connectionState.value="failed"}})()}refreshToken(t){var e=this;return u(function*(){var n=e._t;if(!n)return!1;if("failed"===n.connection.state)return T().warn(Ia,"token:skip — connection failed"),e.hooks.onIdentityChange(),!1;var i=yield Ea(e.instance,e.hooks.getDistinctId(),t);if(!(null==i?void 0:i.tokenRequest))return T().warn(Ia,"token:request:failed",null!=t?t:"(list)"),!1;var r=i.tokenRequest.clientId,s=n.auth.clientId;if(s&&r&&r!==s)return T().warn(Ia,"token:request:clientid-mismatch — recreating connection"),e.hooks.onIdentityChange(),!1;try{return yield n.auth.authorize(i.tokenRequest),!0}catch(t){return T().warn(Ia,Oa("token:authorize-failed",t)),!1}})()}attachConversation(t){var e=this;return u(function*(){var n;if(yield e.ensureConnected(),e._t&&null!=e.store.ablyProjectId.value){if(e.St||e.Ct||e.Et){var i=null!==(n=e.Et)&&void 0!==n?n:e.It();try{yield i}catch(t){}}if(e.store.pendingRealtimeChannelId.value=t,!(yield e.refreshToken(t)))return T().warn(Ia,"channel:attach:no-capability for",t),void(e.store.pendingRealtimeChannelId.value===t&&(e.store.pendingRealtimeChannelId.value=null));var r="chat:"+e.store.ablyProjectId.value+":"+t,s=r+":typing",o=e._t.channels.get(r),a=e._t.channels.get(s);e.St=o,e.Ct=a;var l=()=>e.St!==o||e.Ct!==a;T().debug(Ia,"channel:attach:start",t);try{if(yield o.attach(),l())return void T().debug(Ia,"channel:attach:superseded",t);if(o.subscribe("message",t=>{e.St===o&&Sa(e.store,t.data,e.hooks.getDistinctId()||null,{onAgentMessageWhileOpen:e.hooks.onAgentMessageWhileOpen,onTrack:e.hooks.onMessageTrack,onMessageDispatched:e.hooks.onMessageDispatched})}),o.subscribe("read",t=>{var n,i;e.St===o&&(n=e.store,"agent"===(i=t.data).reader_type&&(n.agentLastReadAt.value=i.read_at))}),yield a.attach(),l())return void T().debug(Ia,"channel:attach:superseded",t);if(a.subscribe("typing",t=>{e.Ct===a&&function(t,e,n){if("user"!==e.sender_type){t.isTyping.value=e.is_typing,t.typingSenderType.value=e.is_typing?e.sender_type:null;var i="ai"===e.sender_type?null:e.sender_name||("agent"===e.sender_type?"Agent":null);t.typingSender.value=e.is_typing?i:null,n.onTyping(e.is_typing,i||"")}}(e.store,t.data,{onTyping:e.hooks.onTypingDispatched})}),e.store.pendingRealtimeChannelId.value!==t)return void T().debug(Ia,"channel:attach:abandoned (pending cleared)",t);e.store.realtimeChannelId.value=t,e.store.realtimeAttached.value=!0,e.store.pendingRealtimeChannelId.value===t&&(e.store.pendingRealtimeChannelId.value=null),T().debug(Ia,"channel:realtime.attached",{channelId:t})}catch(n){if(l())return void T().debug(Ia,"channel:attach:superseded (after error)",t);T().error(Ia,"channel:attach:failed",n),e.store.realtimeAttached.value=!1,e.store.pendingRealtimeChannelId.value===t&&(e.store.pendingRealtimeChannelId.value=null),yield e.It()}}})()}detachConversation(){var t=this.It().finally(()=>{this.Et===t&&(this.Et=null)});return this.Et=t,t}It(){var t=this._t,e=this.St,n=this.Ct;return this.St=null,this.Ct=null,Promise.all([this.Ot(t,e),this.Ot(t,n)]).then(()=>{})}publishTyping(t){var e=this.Ct;e&&e.publish("typing",t).catch(t=>{T().warn(Ia,"failed to publish typing indicator:",t)})}disconnectAll(){var t=this;return u(function*(){if(t.Et)try{yield t.Et}catch(t){}var e=t._t,n=t.St,i=t.Ct,r=t.kt;if(t.St=null,t.Ct=null,t.kt=null,t.store.realtimeChannelId.value=null,t.store.realtimeAttached.value=!1,null==n||n.unsubscribe(),null==i||i.unsubscribe(),null==r||r.unsubscribe(),e){try{e.close()}catch(t){T().debug(Ia,"disconnect:close:error",t)}t._t=null}t.store.ablyProjectId.value=null,t.store.connectionState.value="disconnected",t.store.lastConnectedDistinctId.value=null})()}At(){var t,e=null===(t=this._t)||void 0===t?void 0:t.auth.clientId,n=this.store.lastConnectedDistinctId.value;if(e&&n){var i=e.split(":").slice(1).join(":")||e;i&&i!==n&&(T().warn(Ia,"identity:drift detected on connected — recreating"),this.hooks.onIdentityChange())}}Ot(t,e){return u(function*(){if(e&&t){e.unsubscribe();try{yield e.detach()}catch(t){}}})()}}var Pa=["delivery_status"];function Da(t,e,n){var i=t.messages.value,r=i.findIndex(t=>t.id===e);if(-1!==r){var s=i[r];if(s.delivery_status!==n){var o=[...i];if(void 0===n){var a=function(t,e){if(null==t)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(-1!==e.indexOf(i))continue;n[i]=t[i]}return n}(s,Pa);o[r]=a}else o[r]=h({},s,{delivery_status:n});t.setMessages(o)}}}function Ua(t,e){return ja.apply(this,arguments)}function ja(){return ja=u(function*(t,e){var n;if(!t.ok)return!1;if(t.headers.get("X-Vtilt-User-Message-Id")===e)return!0;var i=t.headers.get("content-type")||"";if(i.includes("text/plain"))return t.ok;if(i.includes("application/json"))try{var r=yield t.clone().json();return(null===(n=null==r?void 0:r.message)||void 0===n?void 0:n.id)===e}catch(t){return!1}return t.ok}),ja.apply(this,arguments)}function Ba(t,e){return"vtilt-chat-outbox:"+t+":"+e}function Na(t){return t+":last-channel"}class La{constructor(t){this.Mt=t,this.Rt=[]}list(){var t=this.Pt();return t.length>0?(this.Rt=t,t):this.Rt}get(t){return this.list().find(e=>e.messageId===t)}upsert(t){var e=this.list().filter(e=>e.messageId!==t.messageId);e.push(t),this.Dt(e)}patch(t,e){var n=this.list(),i=n.findIndex(e=>e.messageId===t);-1!==i&&(n[i]=h({},n[i],e),this.Dt(n))}remove(t){this.Dt(this.list().filter(e=>e.messageId!==t))}dueEntries(t){return void 0===t&&(t=Date.now()),this.list().filter(e=>"sending"!==e.state&&e.nextRetryAt<=t&&!(e.newChannel&&!e.channelId))}requeueStaleSending(t,e){var n;void 0===t&&(t=3e4),void 0===e&&(e=Date.now());for(var i=this.list(),r=!1,s=0;s<i.length;s++){var o=i[s];if("sending"===o.state){var a=null!==(n=o.sendingSince)&&void 0!==n?n:0;(!a||e-a>=t)&&(i[s]=h({},o,{state:"pending",sendingSince:void 0}),r=!0)}}r&&this.Dt(i)}Pt(){if("undefined"==typeof sessionStorage)return[];try{var t=sessionStorage.getItem(this.Mt);if(!t)return[];var e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(t){return[]}}Dt(t){if(this.Rt=t,"undefined"!=typeof sessionStorage)try{0===t.length?sessionStorage.removeItem(this.Mt):sessionStorage.setItem(this.Mt,JSON.stringify(t))}catch(t){}}}function $a(t,e){return void 0===e&&(e=Date.now()),e+Math.min(6e4,1e3*Math.pow(2,Math.max(0,t-1)))}var za="chat";class qa{constructor(t,e){var n,i,r,s,o,a,l,u,d;void 0===e&&(e={}),this.Ut=null,this.jt=new dt,this.Bt=[],this.Nt=[],this.Lt=[],this.$t=null,this.zt=null,this.qt=null,this.Ft=!1,this.Ht=null,this.Wt=!1,this.Jt=0,this.Vt=0,this.Kt=!1,this.Gt=null,this.Xt=!1,this.Qt=null,this.Zt=null,this.Yt=!1,this.te=null,this.ee=null,this.ne=!1,this.ie=null,this.re=()=>{this.se()},this.oe=()=>{"undefined"!=typeof document&&"visible"===document.visibilityState&&this.se()},this.ae=!1,this._instance=t,this.le=h({enabled:!0,position:"bottom-right",aiMode:!0,preload:!1},e,{theme:h({},yn,e.theme)}),this.ue=new wn,this.ue.isVisible.value=!1!==(null===(n=this.le.bubble)||void 0===n?void 0:n.visible),this.ue.theme.value={primaryColor:null!==(r=null===(i=this.le.theme)||void 0===i?void 0:i.primaryColor)&&void 0!==r?r:yn.primaryColor,fontFamily:null!==(o=null===(s=this.le.theme)||void 0===s?void 0:s.fontFamily)&&void 0!==o?o:yn.fontFamily,borderRadius:null!==(l=null===(a=this.le.theme)||void 0===a?void 0:a.borderRadius)&&void 0!==l?l:yn.borderRadius},this.jt.register(Pe),this.jt.register(He),this.he=new Ra(t,this.ue,{getDistinctId:()=>this.de,onIdentityChange:()=>{this.ce()},onNewChannelNotification:()=>{this.getChannels()},onAgentMessageWhileOpen:()=>{setTimeout(()=>this.ve(),100)},onMessageTrack:t=>{var e,n,i,r;this.fe(t,t.channel_id,null!==(n=null===(e=this.ue.channel.value)||void 0===e?void 0:e.ai_mode)&&void 0!==n&&n),"ai"!==t.sender_type&&"agent"!==t.sender_type||null===(r=(i=this.le).onMessageReceived)||void 0===r||r.call(i,{channelId:t.channel_id,messageId:t.id,senderType:t.sender_type})},onMessageDispatched:t=>{this.Bt.forEach(e=>e(t))},onTypingDispatched:(t,e)=>{this.Nt.forEach(n=>n(t,e))}}),this.ee=this.pe(),this.Gt=this.ue.realtimeReady.subscribe(t=>{if(t&&this.Kt){var e=Date.now()-this.Vt;this.Kt=!1,e<3e3&&(this.Wt=!0,this.ge(!0),this.Jt=Date.now(),this.me())}}),this.Ut=Ni({store:this.ue,controller:this,position:null!==(u=this.le.position)&&void 0!==u?u:"bottom-right",bubbleDraggable:!!(null===(d=this.le.bubble)||void 0===d?void 0:d.draggable)}),this.be(),this.zt=this._instance._emitter.on("user:identified",()=>{this.ce()}),this.qt=this._instance._emitter.on("user:reset",()=>{this.ce()}),this.ye=this.de,this.we=new La(this.xe()),this.we.requeueStaleSending(),this._e(),this.se()}get isOpen(){return this.ue.isOpen.value}get isConnected(){return this.ue.isConnected.value}get isLoading(){return this.ue.isLoading.value}get unreadCount(){return this.ue.unreadCount.value}get channel(){return this.ue.channel.value}get channels(){return this.ue.channels.value}get currentView(){return this.ue.currentView.value}get store(){return this.ue}get widgets(){return this.jt}get theme(){return this.ue.theme.value}get config(){return this.le}open(){var t,e;this.ue.isOpen.value||(this.ue.isVisible.value=!0,this.ue.isOpen.value=!0,this.ue.polledUnreadTotal.value=null,this.te=Date.now(),null===(e=(t=this.le).onWidgetOpen)||void 0===e||e.call(t),this.he.ensureConnected(),0===this.ue.channels.value.length&&this.getChannels())}close(){var t,e,n;if(this.ue.isOpen.value){var i=this.te?Math.round((Date.now()-this.te)/1e3):0;this.te=null,this.ue.isOpen.value=!1,this.stopUserTyping(),this.ae||!1!==(null===(t=this.le.bubble)||void 0===t?void 0:t.visible)||(this.ue.isVisible.value=!1);var r=this.ue.messages.value.filter(t=>"user"===t.sender_type).length;null===(n=(e=this.le).onWidgetClose)||void 0===n||n.call(e,{timeOpenSeconds:i,messagesSent:r}),this.ke()}}ke(){var t=this;return u(function*(){yield t.he.detachConversation(),yield t.he.disconnectAll()})()}applyPolledUnreadCount(t){this.ue.isOpen.value||(this.ue.polledUnreadTotal.value=t)}toggle(){this.ue.isOpen.value?this.close():this.open()}show(){this.ae=!0,this.ue.isVisible.value=!0}hide(){this.ae=!1,this.ue.isVisible.value=!1}getChannels(){var t=this;return u(function*(){t.ue.isLoading.value=!0;try{var e=yield it(t._instance,Y+"?distinct_id="+encodeURIComponent(t.de),{method:"GET"});e&&(t.ue.channels.value=e.channels||[])}catch(t){T().error(za,"failed to fetch channels:",t)}finally{t.ue.isLoading.value=!1}})()}selectChannel(t){var e=this;return u(function*(){var n=e.ue.channels.value.find(e=>e.id===t);e.ue.channel.value=n?e.Se(n):null,e.ue.prepareChannelSwitch();var i=e.ue.getCachedMessages(t);i&&(e.ue.messages.value=i),e.ue.currentView.value="conversation",e.ue.isLoading.value=!0,e.ue.pendingRealtimeChannelId.value=t,e.he.detachConversation();var r=!1,s=!1;try{var o=yield it(e._instance,Y+"/"+t+"?distinct_id="+encodeURIComponent(e.de),{method:"GET"});if(e.ue.pendingRealtimeChannelId.value!==t)return void(s=!0);if(!o)return void T().error(za,"selectChannel: server returned no data for channel",t);e.ue.channel.value=o.channel;var a=o.messages||[];e.ue.messages.value=a,e.ue.cacheMessages(o.channel.id,a),e.ue.agentLastReadAt.value=o.channel.agent_last_read_at||null,e.ue.initialUserReadAt.value=o.channel.user_last_read_at||null,e.he.attachConversation(o.channel.id),e.ue.isOpen.value&&e.ve(),r=!0}catch(t){T().error(za,"failed to select channel:",t)}finally{e.ue.pendingRealtimeChannelId.value===t&&(e.ue.pendingRealtimeChannelId.value=null),e.ue.isLoading.value=!1,s||r||null!==e.ue.channel.value||"conversation"!==e.ue.currentView.value||(e.ue.currentView.value="list")}})()}createChannel(e){var n=this;return u(function*(){var i,r,s,o=!0===(null==e?void 0:e.skipGreeting),a=!0===(null==e?void 0:e.preserveMessages),l=a?n.ue.messages.value.slice():[];n.ue.channel.value=null,a||n.ue.prepareChannelSwitch(),n.ue.currentView.value="conversation",n.ue.isLoading.value=!0,n.he.detachConversation();var u=!1;try{var d=yield it(n._instance,Y,{method:"POST",body:JSON.stringify(h({distinct_id:n.de,page_url:null===(i=null==t?void 0:t.location)||void 0===i?void 0:i.href,page_title:"undefined"!=typeof document?document.title:""},o&&{skip_greeting:!0}))});if(!d)return void T().error(za,"createChannel: server returned no data, channel was not created");n.ue.channel.value=d.channel;var c=d.messages||[];if(l.length>0){var v=new Set(c.map(t=>t.id)),f=l.filter(t=>!v.has(t.id)).map(t=>t.channel_id?t:h({},t,{channel_id:d.channel.id}));n.ue.messages.value=[...c,...f]}else n.ue.messages.value=c;n.ue.agentLastReadAt.value=d.channel.agent_last_read_at||null,n.ue.initialUserReadAt.value=d.channel.user_last_read_at||null;var p={id:d.channel.id,status:d.channel.status,ai_mode:d.channel.ai_mode,last_message_at:d.channel.last_message_at,last_message_preview:d.channel.last_message_preview,last_message_sender:d.channel.last_message_sender,unread_count:0,user_last_read_at:d.channel.user_last_read_at,created_at:d.channel.created_at};n.ue.prependChannelSummary(p),null===(s=(r=n.le).onConversationStart)||void 0===s||s.call(r,{channelId:d.channel.id,aiMode:d.channel.ai_mode}),n.he.attachConversation(d.channel.id),n.Ce(d.channel.id),n.Ee(d.channel.id),u=!0}catch(t){T().error(za,"failed to create channel:",t)}finally{if(n.ue.pendingRealtimeChannelId.value=null,n.ue.isLoading.value=!1,!u&&null===n.ue.channel.value)if(l.length>0){var g=new Set(n.we.list().map(t=>t.messageId)),m=l.filter(t=>g.has(t.id));m.length>0?(n.ue.messages.value=m.map(t=>t.delivery_status?t:h({},t,{delivery_status:"failed"})),n.ue.currentView.value="conversation"):(n.ue.messages.value=[],n.ue.currentView.value="list")}else n.ue.currentView.value="list"}})()}goToChannelList(){var t,e,n,i=this.ue.channel.value;if(i){var r=this.ue.messages.value[this.ue.messages.value.length-1];this.ue.patchChannelSummary(i.id,{last_message_at:null!==(t=null==r?void 0:r.created_at)&&void 0!==t?t:void 0,last_message_preview:r?(n=r.content,n.replace(/\n?<!--vtilt:widget:[\s\S]*?-->/g,"").replace(/<[^>]*>/g,"").trim().substring(0,100)):void 0,last_message_sender:null!==(e=null==r?void 0:r.sender_type)&&void 0!==e?e:void 0,unread_count:0}),this.ue.cacheMessages(i.id,this.ue.messages.value)}this.ue.clearActiveChannel(),this.ue.currentView.value="list",this.he.detachConversation().then(()=>{this.he.isLive&&!this.ue.pendingRealtimeChannelId.value&&this.he.refreshToken()})}Te(){this.Qt&&(this.Qt.abort(),this.Qt=null),this.Zt&&(bi(this.ue,this.Zt),this.Zt=null),this.Ae(),this.Ie()}Ae(){for(var t=this.ue.messages.value,e=-1,n=t.length-1;n>=0;n--)if("user"===t[n].sender_type){e=n;break}if(-1!==e){var i=t.filter((t,n)=>n<=e||"ai"!==t.sender_type);i.length!==t.length&&this.ue.setMessages(i)}}Oe(){this.Yt=!0,this.ue.isTyping.value=!0,this.ue.typingSenderType.value="ai",this.ue.typingSender.value="AI Assistant"}Ie(){this.Yt&&(this.Yt=!1,this.ue.isTyping.value=!1,this.ue.typingSender.value=null,this.ue.typingSenderType.value=null)}sendMessage(t,e){var n=this;return u(function*(){var i,r=ut(t,e);if(r){n.ue.identityChangeInFlight.value&&(yield n.Me());var{content:s,content_type:o,metadata:a}=r,l=!1!==(null==e?void 0:e.open),u="conversation"===n.ue.currentView.value&&null!==n.ue.channel.value,d=null!==(i=null==e?void 0:e.channel)&&void 0!==i?i:u?void 0:"new",c=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();var t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;var e=t=>t.toString(16).padStart(2,"0");return e(t[0])+e(t[1])+e(t[2])+e(t[3])+"-"+e(t[4])+e(t[5])+"-"+e(t[6])+e(t[7])+"-"+e(t[8])+e(t[9])+"-"+e(t[10])+e(t[11])+e(t[12])+e(t[13])+e(t[14])+e(t[15])}(),v=(new Date).toISOString(),f="new"===d;if(n.Re(h({messageId:c,channelId:"",distinctId:n.de,body:s,content_type:o,metadata:a,created_at:v,state:"pending",attempts:0,nextRetryAt:0},f?{newChannel:{skipGreeting:!0}}:{})),n.Pe(c),f){n.ue.currentView.value="conversation",n.ue.channel.value=null;var p={id:c,channel_id:"",sender_type:"user",sender_id:n.de||null,sender_name:null,sender_avatar_url:null,content:s,content_type:o,metadata:a,created_at:v,delivery_status:"pending"};n.ue.setMessages([p]),n.ue.isLoading.value=!0,l&&n.open(),yield n.createChannel({skipGreeting:!0,preserveMessages:!0})}else l&&n.open(),d&&(yield n.selectChannel(d));if(!n.ue.channel.value)throw T().error(za,"cannot send message: no active channel (channel creation or selection failed)"),n.we.patch(c,{state:"failed"}),Da(n.ue,c,"failed"),new Error("No active channel");if("conversation"!==n.ue.currentView.value)throw T().error(za,"cannot send message: not in conversation view"),n.we.patch(c,{state:"failed"}),Da(n.ue,c,"failed"),new Error("Not in conversation view");var g,m=n.ue.channel.value.id;if(n.we.patch(c,{channelId:m,newChannel:void 0}),f){var b=n.ue.messages.value.find(t=>t.id===c);if(!b)throw T().error(za,"sendMessage: optimistic temp message was lost during createChannel"),n.we.patch(c,{state:"failed"}),new Error("Optimistic message lost");g=b}else g={id:c,channel_id:m,sender_type:"user",sender_id:n.de||null,sender_name:null,sender_avatar_url:null,content:s,content_type:o,metadata:a,created_at:v,delivery_status:"pending"},n.ue.setMessages([...n.ue.messages.value,g]);try{yield n.De({messageId:c,channelId:m,body:s,content_type:o,metadata:a,tempMessage:g})}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)throw n.Ue(c),t;throw n.Ie(),T().error(za,"failed to send message:",t),n.Ue(c),n.se(),t}}else T().warn(za,"sendMessage: message is empty")})()}retryFailedMessage(t){var e,n=this.we.get(t);if(n&&"failed"===n.state){this.we.patch(t,{state:"pending",nextRetryAt:0,sendingSince:void 0}),Da(this.ue,t,"pending");var i=n.channelId||(null===(e=this.ue.channel.value)||void 0===e?void 0:e.id)||"";if(i){var r=this.ue.messages.value.find(e=>e.id===t);r?(this.Pe(t),this.De({messageId:t,channelId:i,body:n.body,content_type:n.content_type,metadata:n.metadata,tempMessage:r}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?this.Ue(t):(T().error(za,"retry send failed:",e),this.Ue(t),this.se())})):this.se()}}}markAsRead(){this.ve()}triggerAIAfterWidgetAction(t){var e=this;return u(function*(){try{e.Te();var n=new AbortController;e.Qt=n,e.Oe();var i=e._instance.getConfig(),r=c(i,tt(t)),s=yield fetch(r,{method:"POST",signal:n.signal,headers:h({"Content-Type":"application/json"},v(i)),body:JSON.stringify({channel_id:t,distinct_id:e.de,widget_action_trigger:!0})});if(!s.ok)return void e.Ie();(s.headers.get("content-type")||"").includes("text/plain")&&(yield gi({store:e.ue,response:s,channelId:t,signal:n.signal,isActive:()=>e.Qt===n,onStreamStart:t=>{e.Ie(),e.Qt===n&&(e.Zt=t)},onComplete:()=>{e.Qt===n&&(e.Qt=null,e.Zt=null)}}))}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return}})()}onMessage(t){return this.Bt.push(t),()=>{var e=this.Bt.indexOf(t);e>-1&&this.Bt.splice(e,1)}}onTyping(t){return this.Nt.push(t),()=>{var e=this.Nt.indexOf(t);e>-1&&this.Nt.splice(e,1)}}onConnectionChange(t){return this.Lt.push(t),()=>{var e=this.Lt.indexOf(t);e>-1&&this.Lt.splice(e,1)}}updateConfig(t){var e,n,i,r,s,o,a;this.le=function(t,e){var n,i,r=e.bubble,s=t.bubble;if(r){var o=null===r.offset?void 0:void 0!==r.offset?h({},null===(n=t.bubble)||void 0===n?void 0:n.offset,r.offset):null===(i=t.bubble)||void 0===i?void 0:i.offset;s=h({},t.bubble,r,{offset:o})}return h({},t,e,{theme:e.theme?h({},t.theme,e.theme):t.theme,bubble:s})}(this.le,t),this.ue.theme.value={primaryColor:null!==(n=null===(e=this.le.theme)||void 0===e?void 0:e.primaryColor)&&void 0!==n?n:yn.primaryColor,fontFamily:null!==(r=null===(i=this.le.theme)||void 0===i?void 0:i.fontFamily)&&void 0!==r?r:yn.fontFamily,borderRadius:null!==(o=null===(s=this.le.theme)||void 0===s?void 0:s.borderRadius)&&void 0!==o?o:yn.borderRadius},(null===(a=this.le.bubble)||void 0===a?void 0:a.draggable)||this.be()}be(){var t,e,n,i,r=null===(t=this.Ut)||void 0===t?void 0:t.host;if(r){var s=null!==(e=this.le.position)&&void 0!==e?e:"bottom-right";!function(t,e){t.style.setProperty("--vt-bubble-offset-bottom",e.bottom+"px"),t.style.setProperty("--vt-bubble-offset-right",e.right+"px"),t.style.setProperty("--vt-bubble-offset-left",e.left+"px")}(r,kn(null===(n=this.le.bubble)||void 0===n?void 0:n.offset));var o=null===(i=r.shadowRoot)||void 0===i?void 0:i.querySelector(".vt-container");o instanceof HTMLElement&&o.setAttribute("data-position",s)}}registerWidget(t){this.jt.register(t)}notifyUserTyping(){this.Vt=Date.now(),this.ue.realtimeReady.value?(this.Wt?Date.now()-this.Jt>4e3&&(this.ge(!0),this.Jt=Date.now()):(this.Wt=!0,this.ge(!0),this.Jt=Date.now()),this.me()):this.Kt=!0}stopUserTyping(){this.Kt=!1,this.Ht&&(clearTimeout(this.Ht),this.Ht=null),this.Wt&&this.ue.realtimeReady.value&&this.ge(!1),this.Wt=!1}me(){this.Ht&&clearTimeout(this.Ht),this.Ht=setTimeout(()=>{this.Ht=null,this.Wt&&this.ue.realtimeReady.value&&this.ge(!1),this.Wt=!1},5e3)}destroy(){var t,e,n,i,r;this.je(),this.ie&&(clearTimeout(this.ie),this.ie=null),this.he.disconnectAll(),this.Ht&&(clearTimeout(this.Ht),this.Ht=null),null===(t=this.zt)||void 0===t||t.call(this),this.zt=null,null===(e=this.qt)||void 0===e||e.call(this),this.qt=null,null===(n=this.ee)||void 0===n||n.call(this),this.ee=null,null===(i=this.Gt)||void 0===i||i.call(this),this.Gt=null,null===(r=this.Ut)||void 0===r||r.destroy(),this.Ut=null,this.Bt=[],this.Nt=[],this.Lt=[]}getWidgetContext(t,e){var n,i,r,s=this,o=this._instance.getConfig();return{channelId:null!==(i=null===(n=this.ue.channel.value)||void 0===n?void 0:n.id)&&void 0!==i?i:"",distinctId:this.de,primaryColor:this.ue.theme.value.primaryColor,apiBase:o.api_host||"",token:o.token||"",messageId:t,buildEndpointUrl:t=>c(this._instance.getConfig(),t),dispatch:(r=u(function*(n,i){var r=s.jt.get(e);if(r){var o=s.getWidgetContext(t,e);try{var a=yield r.onAction(n,i,o);(null==a?void 0:a.success)&&s.markWidgetSubmittedAndFollowUp(t,e,i)}catch(t){T().warn(za,"widget action failed:",t)}}}),function(t,e){return r.apply(this,arguments)})}}markWidgetSubmittedAndFollowUp(t,e,n){var i,r,s,o,a=this.ue.messages.value.find(e=>e.id===t);if(a){var l=h({},null!==(i=a.metadata)&&void 0!==i?i:{}),u=(null!==(s=null!==(r=l.T)&&void 0!==r?r:l.widgets)&&void 0!==s?s:[]).map(t=>{if(t.type!==e)return t;var i=h({},t,{submitted:!0});return n.email&&(i.submittedEmail=String(n.email).trim()),n.name&&(i.submittedName=String(n.name).trim()),i});l.widgets=u,l.T&&(l.T=u);var d=this.ue.messages.value.map(e=>e.id===t?h({},e,{metadata:l}):e);this.ue.setMessages(d);var c=null===(o=this.ue.channel.value)||void 0===o?void 0:o.id;"escalate_to_human"!==e&&c&&this.triggerAIAfterWidgetAction(c)}}xe(){return Ba(this._instance.getConfig().token||"unknown",this.de)}Be(){this.we=new La(this.xe()),this.we.requeueStaleSending()}Pe(t){this.we.patch(t,{state:"sending",sendingSince:Date.now()})}Ue(t){var e,n,i=(null!==(n=null===(e=this.we.get(t))||void 0===e?void 0:e.attempts)&&void 0!==n?n:0)+1;this.we.patch(t,{state:"failed",attempts:i,nextRetryAt:$a(i),sendingSince:void 0}),Da(this.ue,t,"failed")}Ce(t){for(var e of this.we.list())e.newChannel&&!e.channelId&&this.we.patch(e.messageId,{channelId:t,newChannel:void 0})}Ee(t){!function(t,e){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(Na(t),JSON.stringify({channelId:e,at:Date.now()}))}catch(t){}}(this.xe(),t)}Ne(t){var e=this.de;if(t&&t!==e){var n=this._instance.getConfig().token||"unknown",i=new La(Ba(n,t)),r=i.list();for(var s of r)this.we.upsert(h({},s,{distinctId:e})),i.remove(s.messageId)}}_e(){"undefined"!=typeof window&&(window.addEventListener("online",this.re),document.addEventListener("visibilitychange",this.oe))}je(){"undefined"!=typeof window&&(window.removeEventListener("online",this.re),document.removeEventListener("visibilitychange",this.oe))}Re(t){this.we.upsert(t)}Le(t,e){var n,i;this.we.remove(t),Da(this.ue,t,void 0),null===(i=(n=this.le).onMessageDelivered)||void 0===i||i.call(n,{channelId:e,messageId:t})}se(){this.ie&&clearTimeout(this.ie),this.ie=setTimeout(()=>{this.ie=null,this.$e()},0)}$e(){var t=this;return u(function*(){if(!t.ne){t.ne=!0,t.we.requeueStaleSending();try{var e=Date.now(),n=function*(e){var n=t.ue.messages.value.some(t=>t.id===e.messageId&&"sending"===t.delivery_status);if(n)return 1;try{yield t.ze(e)}catch(n){T().warn(za,"outbox drain failed:",n);var i=e.attempts+1;t.we.patch(e.messageId,{state:"failed",attempts:i,nextRetryAt:$a(i)}),Da(t.ue,e.messageId,"failed")}};for(var i of t.we.dueEntries(e))yield*n(i)}finally{t.ne=!1;var r=t.we.dueEntries(Date.now());if(r.length>0){var s=Math.max(0,r[0].nextRetryAt-Date.now());t.ie=setTimeout(()=>{t.ie=null,t.$e()},s)}}}})()}ze(t){var e=this;return u(function*(){var n=t.channelId||void 0;if(!n&&t.newChannel){var i=function(t,e){if(void 0===e&&(e=Date.now()),"undefined"==typeof sessionStorage)return null;try{var n=sessionStorage.getItem(Na(t));if(!n)return null;var i=JSON.parse(n);return!(null==i?void 0:i.channelId)||"number"!=typeof i.at||e-i.at>12e4?null:i}catch(t){return null}}(e.xe());i&&(n=i.channelId,e.we.patch(t.messageId,{channelId:n,newChannel:void 0}))}if(!n&&t.newChannel){var r=yield e.qe(t.newChannel.skipGreeting);if(!(n=null!=r?r:void 0))throw new Error("Failed to create channel for outbox entry");e.we.patch(t.messageId,{channelId:n,newChannel:void 0}),e.Ee(n)}if(!n)throw new Error("Outbox entry missing channelId");var s=e.ue.messages.value.find(e=>e.id===t.messageId);if(s)return e.Pe(t.messageId),void(yield e.De({messageId:t.messageId,channelId:n,body:t.body,content_type:t.content_type,metadata:t.metadata,tempMessage:s}));yield e.Fe({messageId:t.messageId,channelId:n,body:t.body,content_type:t.content_type,metadata:t.metadata}),e.Le(t.messageId,n)})()}qe(e){var n=this;return u(function*(){var i,r,s,o=yield it(n._instance,Y,{method:"POST",body:JSON.stringify(h({distinct_id:n.de,page_url:null===(i=null==t?void 0:t.location)||void 0===i?void 0:i.href,page_title:"undefined"!=typeof document?document.title:""},e&&{skip_greeting:!0}))}),a=null!==(s=null===(r=null==o?void 0:o.channel)||void 0===r?void 0:r.id)&&void 0!==s?s:null;return a&&(n.Ce(a),n.Ee(a)),a})()}Fe(t){var e=this;return u(function*(){var n,i=e._instance.getConfig(),r=c(i,tt(t.channelId)),s=yield fetch(r,{method:"POST",keepalive:!0,headers:h({"Content-Type":"application/json"},v(i)),body:JSON.stringify({id:t.messageId,channel_id:t.channelId,distinct_id:e.de,content:t.body,content_type:t.content_type,metadata:t.metadata})});if(!s.ok)throw new Error("API error: "+s.status);if(!(yield Ua(s,t.messageId)))throw new Error("User message not acknowledged");(s.headers.get("content-type")||"").includes("text/plain")&&(yield null===(n=s.body)||void 0===n?void 0:n.cancel().catch(()=>{}))})()}De(t){var e=this;return u(function*(){var n,i,r,s,o,{messageId:a,channelId:l,body:u,content_type:d,metadata:f,tempMessage:p}=t;Da(e.ue,a,"sending"),e.Te();var g=new AbortController;e.Qt=g,!1!==(null===(n=e.ue.channel.value)||void 0===n?void 0:n.ai_mode)&&e.Oe();var m=e._instance.getConfig(),b=c(m,tt(l)),y=yield fetch(b,{method:"POST",keepalive:!0,signal:g.signal,headers:h({"Content-Type":"application/json"},v(m)),body:JSON.stringify({id:a,channel_id:l,distinct_id:e.de,content:u,content_type:d,metadata:f})});if(!y.ok)throw new Error("API error: "+y.status);if(!(yield Ua(y,a)))throw new Error("User message not acknowledged");if(e.Le(a,l),(y.headers.get("content-type")||"").includes("text/plain"))yield gi({store:e.ue,response:y,channelId:l,signal:g.signal,isActive:()=>e.Qt===g,onStreamStart:t=>{e.Ie(),e.Qt===g&&(e.Zt=t)},onComplete:()=>{var t,n,i,r;e.Qt===g&&(e.Qt=null,e.Zt=null),null===(n=(t=e.le).onMessageSent)||void 0===n||n.call(t,{channelId:l,messageId:p.id}),e.fe(p,l,null===(r=null===(i=e.ue.channel.value)||void 0===i?void 0:i.ai_mode)||void 0===r||r)}});else{e.Ie(),e.Qt===g&&(e.Qt=null);var w=yield y.json();if(null==w?void 0:w.message){var x=e.ue.messages.value.findIndex(t=>t.id===w.message.id);if(-1===x&&(x=e.ue.messages.value.findIndex(t=>t.id===a)),-1!==x){var _=[...e.ue.messages.value];_[x]=w.message,e.ue.setMessages(_)}null===(r=(i=e.le).onMessageSent)||void 0===r||r.call(i,{channelId:l,messageId:w.message.id}),e.fe(w.message,l,null!==(o=null===(s=e.ue.channel.value)||void 0===s?void 0:s.ai_mode)&&void 0!==o&&o)}}})()}get de(){return this._instance.getDistinctId()||""}Se(t){return{id:t.id,project_id:"",person_id:"",distinct_id:this.de,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}}ce(){var t=this;return u(function*(){if(!t.Ft){var e=t.de;if(e&&e!==t.ue.lastConnectedDistinctId.value){t.Ft=!0,t.ue.identityChangeInFlight.value=!0,t.ue.clearActiveChannel(),t.ue.currentView.value="list",t.Ne(t.ye),t.Be(),t.ye=e;try{yield t.he.disconnectAll(),t.ue.channels.value=[],t.ue.clearMessagesCache(),yield t.getChannels(),t.ue.isOpen.value&&(yield t.he.ensureConnected()),t.se()}catch(t){T().error(za,"failed to recreate Ably client after identity change:",t)}finally{t.Ft=!1,t.ue.identityChangeInFlight.value=!1}}}})()}Me(){return new Promise(t=>{if(this.ue.identityChangeInFlight.value)var e=this.ue.identityChangeInFlight.subscribe(n=>{n||(e(),t())});else t()})}fe(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(ht,{$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})}ve(){var t,e=this.ue.channel.value;if(e&&!this.Xt){var n=this.ue.messages.value,i=n[n.length-1];if(i){var r=this.ue.initialUserReadAt.value,s=n.some(t=>{return!("agent"!==t.sender_type&&"ai"!==t.sender_type||(e=t.created_at,r&&new Date(e)<=new Date(r)));var e}),o=this.ue.channels.value.find(t=>t.id===e.id),a=(null!==(t=null==o?void 0:o.unread_count)&&void 0!==t?t:0)>0;(s||a)&&(this.Xt=!0,it(this._instance,et(e.id),{method:"POST",body:JSON.stringify({channel_id:e.id,distinct_id:this.de,read_at:i.created_at})}).then(t=>{t&&(this.ue.initialUserReadAt.value=i.created_at,this.ue.patchChannelSummary(e.id,{unread_count:0})),this.Xt=!1}).catch(()=>{this.Xt=!1}))}}}ge(t){this.he.publishTyping({sender_type:"user",sender_name:null,is_typing:t,sender_id:this.de})}pe(){return this.ue.isConnected.subscribe(t=>{this.$t!==t&&(this.$t=t,this.Lt.forEach(e=>e(t)))})}}a.__VTiltExtensions__=a.__VTiltExtensions__||{},a.__VTiltExtensions__.initChat=function(t,e){return new qa(t,e)};var Fa="external-scripts";a.__VTiltExtensions__=a.__VTiltExtensions__||{},a.__VTiltExtensions__.loadExternalDependency=(t,e,n)=>{if(function(t){var e=a.__VTiltExtensions__;if(!e)return!1;switch(t){case"chat":return!!e.initChat;case"recorder":return!!e.initSessionRecording;case"web-vitals":return!!e.webVitalsCallbacks;default:return!1}}(e))n();else{var r=((t,e)=>{var n=t.getConfig();return n.script_host?n.script_host.replace(/\/+$/gm,"")+"/"+e+".js":n.api_host?n.api_host.replace(/\/+$/gm,"")+"/dist/"+e+".js":(T().error(Fa,"cannot load "+e+".js: api_host is required"),"")})(t,e);((t,e,n)=>{if(t.getConfig().disable_external_dependency_loading)return T().warn(Fa,e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=null==i?void 0:i.querySelectorAll("script");if(r)for(var s,o=function(){if(r[a].src===e){var t=r[a];return t.__vtilt_loading_callback_fired?{v:n()}:(t.addEventListener("load",e=>{t.__vtilt_loading_callback_fired=!0,n(void 0,e)}),t.onerror=t=>n(t),{v:void 0})}},a=0;a<r.length;a++)if(s=o())return s.v;var l=()=>{var t;if(!i)return n("document not found");var r=i.createElement("script");r.type="text/javascript",r.crossOrigin="anonymous",r.src=e,r.onload=t=>{r.__vtilt_loading_callback_fired=!0,n(void 0,t)},r.onerror=t=>n(t);var s=i.querySelectorAll("body > script");s.length>0?null===(t=s[0].parentNode)||void 0===t||t.insertBefore(r,s[0]):i.body.appendChild(r)};(null==i?void 0:i.body)?l():null==i||i.addEventListener("DOMContentLoaded",l)})(t,r,n)}};var Ha="1.13.1",Wa="__vt_session",Ja="__vt_window_id",Va="__vt_primary_window",Ka="__vt_user_state",Ga="__vt_device_id",Xa="__vt_anonymous_id",Qa="__vt_remote_config",Za="__vt_distinct_id",Ya="__vt_user_properties",tl="localStorage",el="localStorage+cookie",nl="sessionStorage",il="memory",rl="$initial_person_info",sl="$pageview",ol="$pageleave",al="$identify",ll="$alias",ul="$set",hl="$performance_event",dl="$autocapture",cl="$scroll_depth",vl="$snapshot",fl="$snapshot_items",pl="$$client_ingestion_warning",gl="$current_url",ml="$pathname",bl="$prev_pageview_duration",yl="$prev_pageview_pathname",wl="$prev_pageview_url",xl="$scroll_depth_pct",_l="$scroll_depth_max_pct",kl="$prev_pageview_scroll_depth_pct";function Sl(t,e){var n,i,r=e.bubble,s=null==t?void 0:t.bubble;if(r){var o=null===r.offset?void 0:void 0!==r.offset?h({},null===(n=null==t?void 0:t.bubble)||void 0===n?void 0:n.offset,r.offset):null===(i=null==t?void 0:t.bubble)||void 0===i?void 0:i.offset;s=h({},null==t?void 0:t.bubble,r,{offset:o})}return h({},t,e,{bubble:s})}class Cl{constructor(t){void 0===t&&(t={}),this.config=this.parseConfigFromScript(t)}parseConfigFromScript(t){if(!(null==i?void 0:i.currentScript))return h({token:t.token||""},t);var e=i.currentScript,n=h({token:""},t);n.api_host=e.getAttribute("data-api-host")||e.getAttribute("data-host")||t.api_host,n.script_host=e.getAttribute("data-script-host")||t.script_host,n.token=e.getAttribute("data-token")||t.token||"",n.domain=e.getAttribute("data-domain")||t.domain,n.storage=e.getAttribute("data-storage")||t.storage,n.stringifyPayload="false"!==e.getAttribute("data-stringify-payload");var r="true"===e.getAttribute("data-capture-performance");for(var s of(n.capture_performance=!!r||t.capture_performance,n.globalAttributes=h({},t.globalAttributes),Array.from(e.attributes)))s.name.startsWith("data-vt-")&&(n.globalAttributes[s.name.slice(8).replace(/-/g,"_")]=s.value);return n}getConfig(){return h({},this.config)}updateConfig(t){var e=function(t,e){return void 0===e.chat?e:h({},e,{chat:Sl(t.chat,e.chat)})}(this.config,t);this.config=h({},this.config,e)}}var El=[Xa,Ga,Za,Ka],Tl=31536e3,Al=["herokuapp.com","vercel.app","netlify.app"];function Il(t){var e;if(!t||"undefined"==typeof document)return"";var n=null===(e=document.location)||void 0===e?void 0:e.hostname;if(!n)return"";var i=n.match(/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i);return i?"."+i[0]:""}class Ol{constructor(t){var e,n,i;this.memoryStorage=new Map,this.He=null,this.method=t.method,this.cross_subdomain=null!==(e=t.cross_subdomain)&&void 0!==e?e:function(){var t;if("undefined"==typeof document)return!1;var e=null===(t=document.location)||void 0===t?void 0:t.hostname;if(!e)return!1;var n=e.split(".").slice(-2).join(".");return!Al.includes(n)}(),this.sameSite=null!==(n=t.sameSite)&&void 0!==n?n:"Lax",this.secure=null!==(i=t.secure)&&void 0!==i?i:"undefined"!=typeof location&&"https:"===location.protocol}isLocalStorageSupported(){if(null!==this.He)return this.He;if(void 0===t||!t.localStorage)return this.He=!1,!1;try{var e="__vt_ls_test__";t.localStorage.setItem(e,"1");var n="1"===t.localStorage.getItem(e);return t.localStorage.removeItem(e),this.He=n,n||T().warn("storage","localStorage unavailable, using cookies"),n}catch(t){return this.He=!1,T().warn("storage","localStorage unavailable, using cookies"),!1}}isCriticalProperty(t){return El.includes(t)}get(t){var e;try{switch(this.method){case il:return null!==(e=this.memoryStorage.get(t))&&void 0!==e?e:null;case el:return this.getLocalStoragePlusCookie(t);case tl:return this.getLocalStorage(t);case nl:return this.readFromSessionStorage(t);default:return this.getCookie(t)}}catch(e){return T().warn("storage",'get error for "'+t+'":',e),null}}set(t,e,n){try{switch(this.method){case il:this.memoryStorage.set(t,e);break;case el:this.setLocalStoragePlusCookie(t,e,n);break;case tl:this.setLocalStorage(t,e);break;case nl:this.writeToSessionStorage(t,e);break;default:this.setCookie(t,e,null!=n?n:Tl)}}catch(e){T().warn("storage",'set error for "'+t+'":',e)}}remove(t){try{switch(this.method){case il:this.memoryStorage.delete(t);break;case el:this.removeLocalStoragePlusCookie(t);break;case tl:this.removeLocalStorage(t);break;case nl:this.removeFromSessionStorage(t);break;default:this.removeCookie(t)}}catch(e){T().warn("storage",'remove error for "'+t+'":',e)}}getLocalStoragePlusCookie(e){if(this.isCriticalProperty(e)){var n=this.getCookie(e),i=this.getLocalStorage(e);if(null!==n){if(i!==n&&this.isLocalStorageSupported())try{null==t||t.localStorage.setItem(e,n)}catch(t){}return n}return null!==i?i:this.readFromSessionStorage(e)}return this.getLocalStorage(e)}setLocalStoragePlusCookie(t,e,n){this.setLocalStorage(t,e),this.isCriticalProperty(t)&&(this.setCookie(t,e,null!=n?n:Tl),this.writeToSessionStorage(t,e))}removeLocalStoragePlusCookie(t){this.removeLocalStorage(t),this.isCriticalProperty(t)&&(this.removeCookie(t),this.removeFromSessionStorage(t))}getLocalStorage(e){var n;if(!this.isLocalStorageSupported())return null;try{return null!==(n=null==t?void 0:t.localStorage.getItem(e))&&void 0!==n?n:null}catch(t){return null}}setLocalStorage(e,n){if(this.isLocalStorageSupported())try{null==t||t.localStorage.setItem(e,n)}catch(t){T().warn("storage","localStorage write error:",t)}}removeLocalStorage(e){if(this.isLocalStorageSupported())try{null==t||t.localStorage.removeItem(e)}catch(t){}}readFromSessionStorage(e){var n;try{return null!==(n=null==t?void 0:t.sessionStorage.getItem(e))&&void 0!==n?n:null}catch(t){return null}}writeToSessionStorage(e,n){try{null==t||t.sessionStorage.setItem(e,n)}catch(t){T().warn("storage","sessionStorage write error:",t)}}removeFromSessionStorage(e){try{null==t||t.sessionStorage.removeItem(e)}catch(t){}}getCookie(t){if("undefined"==typeof document)return null;var e=t+"=";for(var n of document.cookie.split(";")){var i=n.trim();if(i.startsWith(e))try{return decodeURIComponent(i.slice(e.length))}catch(t){return i.slice(e.length)}}return null}setCookie(t,e,n){if("undefined"!=typeof document){var i=Il(this.cross_subdomain),r=t+"="+encodeURIComponent(e)+"; Max-Age="+n+"; path=/; SameSite="+this.sameSite;this.secure&&(r+="; Secure"),i&&(r+="; domain="+i),document.cookie=r}}removeCookie(t){if("undefined"!=typeof document){var e=Il(this.cross_subdomain);document.cookie=t+"=; Max-Age=0; path=/"+(e?"; domain="+e:""),document.cookie=t+"=; Max-Age=0; path=/"}}getWithExpiry(t){var e=this.get(t);if(!e)return null;try{var n=JSON.parse(e);return n.expiry&&Date.now()>n.expiry?(this.remove(t),null):n.value}catch(t){return null}}setWithExpiry(t,e,n){var i=h({value:e},n?{expiry:Date.now()+n}:{});this.set(t,JSON.stringify(i))}getJSON(t){var e=this.get(t);if(!e)return null;try{return JSON.parse(e)}catch(t){return null}}setJSON(t,e,n){this.set(t,JSON.stringify(e),n)}canUseSessionStorage(){if(void 0===t||!(null==t?void 0:t.sessionStorage))return!1;try{var e="__vt_ss_test__";return t.sessionStorage.setItem(e,"1"),t.sessionStorage.removeItem(e),!0}catch(t){return!1}}getSessionStorage(){var e;return this.canUseSessionStorage()&&null!==(e=null==t?void 0:t.sessionStorage)&&void 0!==e?e:null}setMethod(t){this.method=t}getMethod(){return this.method}}class Ml{constructor(t,e){void 0===t&&(t="cookie"),this.We=!1,this.storage=new Ol({method:t,cross_subdomain:e,sameSite:"Lax"}),this.Je=void 0,T().debug("session","ctor")}hydrateFromStorage(){T().debug("session","hydrate"),this.Ve()}getSessionId(){var t=this.Ke();return t||(t=J(16),this.Ge(t),this.We=!0),t}setSessionId(){var t=this.Ke(),e=t||J(16);return t||(this.We=!0),this.Ge(e),e}resetSessionId(){this.Xe(),this.We=!0,this.setSessionId(),this.Qe(J(16))}consumeSessionStart(){return!!this.We&&(this.We=!1,!0)}Ke(){return this.storage.get(Wa)}Ge(t){this.storage.set(Wa,t,1800)}Xe(){this.storage.remove(Wa)}getWindowId(){if(this.Je)return this.Je;var t=this.storage.getSessionStorage();if(t){var e=t.getItem(Ja);if(e)return this.Je=e,e}var n=J(16);return this.Qe(n),n}Qe(t){if(t!==this.Je){this.Je=t;var e=this.storage.getSessionStorage();e&&e.setItem(Ja,t)}}Ve(){var t=this.storage.getSessionStorage();if(t){var e=t.getItem(Va),n=t.getItem(Ja);n&&!e?this.Je=n:(n&&t.removeItem(Ja),this.Qe(J(16))),t.setItem(Va,"true"),this.Ze()}else this.Je=J(16)}Ze(){var e=this.storage.getSessionStorage();t&&e&&G(t,"beforeunload",()=>{var t=this.storage.getSessionStorage();t&&t.removeItem(Va)},{capture:!1})}updateStorageMethod(t,e){this.storage=new Ol({method:t,cross_subdomain:e,sameSite:"Lax"})}}function Rl(t){if(!i)return null;var e=i.createElement("a");return e.href=t,e}function Pl(t){try{return decodeURIComponent(t).replace(/\+/g," ")}catch(e){return t.replace(/\+/g," ")}}function Dl(t){for(var e={},n=function(t){return((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"")}(t).split("&"),i=0;i<n.length;i++){var r=n[i];if(r){var s=r.indexOf("="),o=-1===s?r:r.slice(0,s);if(o){var a=Pl(o),l=-1===s?"":r.slice(s+1);e[a]=Pl(l)}}}return e}function Ul(t,e){var n;return null!==(n=Dl(t)[e])&&void 0!==n?n:""}function jl(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[0]||"",s=i[1],o=r.split("?"),a=o[1],l=o[0],u=(a||"").split("&"),h=[],d=0;d<u.length;d++){var c=u[d].split("="),v=c[0],f=c.slice(1).join("=");-1!==e.indexOf(v)?h.push(v+"="+n):v&&h.push(v+(f?"="+f:""))}var p=h.join("&");return l+(p?"?"+p:"")+(s?"#"+s:"")}var Bl="_fbp",Nl="_fbc",Ll=15552e3,$l=7776e3;function zl(){void 0!==i&&(function(){if(ql(Bl))return;var t=Date.now(),e=Math.floor(1e9+9e9*Math.random()),n="fb.1."+t+"."+e;Fl(Bl,n,Ll)}(),function(){if(!(null==r?void 0:r.search))return;try{var t=new URL(r.href).searchParams.get("fbclid");if(!(null==t?void 0:t.trim()))return;var e="fb.1."+Date.now()+"."+t.trim();Fl(Nl,e,$l)}catch(t){}}())}function ql(t){if(void 0===i||!(null==i?void 0:i.cookie))return null;var e=t+"=";for(var n of i.cookie.split(";")){var r=n.trim();if(r.startsWith(e))try{return decodeURIComponent(r.slice(e.length))}catch(t){return r.slice(e.length)}}return null}function Fl(t,e,n){if(void 0!==i){var s=void 0!==r&&"https:"===r.protocol?"; Secure":"";i.cookie=t+"="+encodeURIComponent(e)+"; Max-Age="+n+"; path=/; SameSite=Lax"+s}}var Hl="Mobile",Wl="iOS",Jl="Android",Vl="Tablet",Kl=Jl+" "+Vl,Gl="iPad",Xl="Apple",Ql=Xl+" Watch",Zl="Safari",Yl="BlackBerry",tu="Samsung",eu=tu+"Browser",nu=tu+" Internet",iu="Chrome",ru=iu+" OS",su=iu+" "+Wl,ou="Internet Explorer",au=ou+" "+Hl,lu="Opera",uu=lu+" Mini",hu="Edge",du="Microsoft "+hu,cu="Firefox",vu=cu+" "+Wl,fu="Nintendo",pu="PlayStation",gu="Xbox",mu=Jl+" "+Hl,bu=Hl+" "+Zl,yu="Windows",wu=yu+" Phone",xu="Nokia",_u="Ouya",ku="Generic",Su=ku+" "+Hl.toLowerCase(),Cu=ku+" "+Vl.toLowerCase(),Eu="Konqueror",Tu="(\\d+(\\.\\d+)?)",Au=new RegExp("Version/"+Tu),Iu=new RegExp(gu,"i"),Ou=new RegExp(pu+" \\w+","i"),Mu=new RegExp(fu+" \\w+","i"),Ru=new RegExp(Yl+"|PlayBook|BB10","i"),Pu={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Du(t,e){return t.toLowerCase().includes(e.toLowerCase())}var Uu=(t,e)=>e&&Du(e,Xl)||function(t){return Du(t,Zl)&&!Du(t,iu)&&!Du(t,Jl)}(t),ju=function(t,e){return e=e||"",Du(t," OPR/")&&Du(t,"Mini")?uu:Du(t," OPR/")?lu:Ru.test(t)?Yl:Du(t,"IE"+Hl)||Du(t,"WPDesktop")?au:Du(t,eu)?nu:Du(t,hu)||Du(t,"Edg/")?du:Du(t,"FBIOS")?"Facebook "+Hl:Du(t,"UCWEB")||Du(t,"UCBrowser")?"UC Browser":Du(t,"CriOS")?su:Du(t,"CrMo")||Du(t,iu)?iu:Du(t,Jl)&&Du(t,Zl)?mu:Du(t,"FxiOS")?vu:Du(t.toLowerCase(),Eu.toLowerCase())?Eu:Uu(t,e)?Du(t,Hl)?bu:Zl:Du(t,cu)?cu:Du(t,"MSIE")||Du(t,"Trident/")?ou:Du(t,"Gecko")?cu:""},Bu={[au]:[new RegExp("rv:"+Tu)],[du]:[new RegExp(hu+"?\\/"+Tu)],[iu]:[new RegExp("("+iu+"|CrMo)\\/"+Tu)],[su]:[new RegExp("CriOS\\/"+Tu)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Tu)],[Zl]:[Au],[bu]:[Au],[lu]:[new RegExp("(Opera|OPR)\\/"+Tu)],[cu]:[new RegExp(cu+"\\/"+Tu)],[vu]:[new RegExp("FxiOS\\/"+Tu)],[Eu]:[new RegExp("Konqueror[:/]?"+Tu,"i")],[Yl]:[new RegExp(Yl+" "+Tu),Au],[mu]:[new RegExp("android\\s"+Tu,"i")],[nu]:[new RegExp(eu+"\\/"+Tu)],[ou]:[new RegExp("(rv:|MSIE )"+Tu)],Mozilla:[new RegExp("rv:"+Tu)]},Nu=function(t,e){var n=ju(t,e),i=Bu[n];if(void 0===i)return null;for(var r=0;r<i.length;r++){var s=i[r],o=t.match(s);if(o)return parseFloat(o[o.length-2])}return null},Lu=[[new RegExp(gu+"; "+gu+" (.*?)[);]","i"),t=>[gu,t&&t[1]||""]],[new RegExp(fu,"i"),[fu,""]],[new RegExp(pu,"i"),[pu,""]],[Ru,[Yl,""]],[new RegExp(yu,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[wu,""];if(new RegExp(Hl).test(e)&&!/IEMobile\b/.test(e))return[yu+" "+Hl,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=n[1],r=Pu[i]||"";return/arm/i.test(e)&&(r="RT"),[yu,r]}return[yu,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[Wl,e.join(".")]}return[Wl,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=void 0===t[2]?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Jl+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Jl+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[Jl,e.join(".")]}return[Jl,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ru,""]],[/Linux|debian/i,["Linux",""]]],$u=function(t){return Mu.test(t)?fu:Ou.test(t)?pu:Iu.test(t)?gu:new RegExp(_u,"i").test(t)?_u:new RegExp("("+wu+"|WPDesktop)","i").test(t)?wu:/iPad/.test(t)?Gl:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Ql:Ru.test(t)?Yl:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(xu,"i").test(t)?xu:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?!new RegExp(Hl).test(t)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)?/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Jl:Kl:Jl:new RegExp("(pda|"+Hl+")","i").test(t)?Su:new RegExp(Vl,"i").test(t)&&!new RegExp(Vl+" pc","i").test(t)?Cu:""},zu="https?://(.*)",qu=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Fu=Q(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],qu),Hu="<masked>";function Wu(t,e){var n=Fu.concat([]),i=X({},function(t){var e={};return K(Dl(t),function(t,n){"string"==typeof n&&n.startsWith("utm_")&&t&&(e[n]=t)}),e}(t));return K(n,function(e){if(e.startsWith("utm_")){if(!(e in i)){var n=Ul(t,e);i[e]=n||null}}else{var r=Ul(t,e);i[e]=r||null}}),i}function Ju(t){var e=function(t){return t?0===t.search(zu+"google.([^/?]*)")?"google":0===t.search(zu+"bing.com")?"bing":0===t.search(zu+"yahoo.com")?"yahoo":0===t.search(zu+"duckduckgo.com")?"duckduckgo":null:null}(t),n="yahoo"!==e?"q":"p",r={};if(!function(t){return null===t}(e)){r.$search_engine=e;var s=i?Ul(i.referrer,n):"";s.length&&(r.ph_keyword=s)}return r}function Vu(){if("undefined"!=typeof navigator)return navigator.language||navigator.userLanguage}function Ku(){return(null==i?void 0:i.referrer)||"$direct"}function Gu(){var t;return(null==i?void 0:i.referrer)&&(null===(t=Rl(i.referrer))||void 0===t?void 0:t.host)||"$direct"}function Xu(t){var e=function(t){var e,{r:n,u:i}=t,r={$referrer:n,$referring_domain:null==n?void 0:"$direct"===n?"$direct":null===(e=Rl(n))||void 0===e?void 0:e.host};if(i){r.$current_url=i;var s=Rl(i);r.$host=null==s?void 0:s.host,r.$pathname=null==s?void 0:s.pathname,X(r,Wu(i))}return n&&X(r,Ju(n)),r}(t),n={};return K(e,function(t,e){var i;n["$initial_"+(i=String(e),i.startsWith("$")?i.substring(1):i)]=t}),n}function Qu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return}}function Zu(){try{return(new Date).getTimezoneOffset()}catch(t){return}}function Yu(e,n){if(!o)return{};var i,s,a,l=e?Q([],qu,n||[]):[],[u,h]=function(t){for(var e=0;e<Lu.length;e++){var[n,i]=Lu[e],r=n.exec(t);if(r){var s="function"==typeof i?i(r,t):i;if(s)return s}}return["",""]}(o),d=ql(Bl)||void 0,c=ql(Nl)||void 0;return X(Z({$os:u,$os_version:h,$browser:ju(o,navigator.vendor),$device:$u(o),$device_type:(s=o,a=$u(s),a===Gl||a===Kl||"Kobo"===a||"Kindle Fire"===a||a===Cu?Vl:a===fu||a===gu||a===pu||a===_u?"Console":a===Ql?"Wearable":a?Hl:"Desktop"),$timezone:Qu(),$timezone_offset:Zu(),$fb_browser_id:d,$fb_click_id:c}),{$current_url:jl(null==r?void 0:r.href,l,Hu),$host:null==r?void 0:r.host,$pathname:null==r?void 0:r.pathname,$raw_user_agent:o.length>1e3?o.substring(0,997)+"...":o,$browser_version:Nu(o,navigator.vendor),$browser_language:Vu(),$browser_language_prefix:(i=Vu(),"string"==typeof i?i.split("-")[0]:void 0),$screen_height:null==t?void 0:t.screen.height,$screen_width:null==t?void 0:t.screen.width,$viewport_height:null==t?void 0:t.innerHeight,$viewport_width:null==t?void 0:t.innerWidth,$lib:"web",$lib_version:Ha,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10)})}class th{constructor(t,e){void 0===t&&(t="localStorage"),this.Ye=!1,this.storage=new Ol({method:t,cross_subdomain:e,sameSite:"Lax"}),this.userIdentity=this.generateEphemeralIdentity(),T().debug("user","ctor","ephemeral identity only")}hydrateFromStorage(){T().debug("user","hydrate start"),this.userIdentity=this.loadUserIdentity();var t=this.userIdentity.anonymous_id,e=this.userIdentity.distinct_id;T().debug("user","hydrate done","anonymous_id",t?t.slice(0,12)+"...":"n/a","distinct_id",e?e.slice(0,12)+"...":"null")}generateEphemeralIdentity(){return{distinct_id:null,anonymous_id:this.generateAnonymousId(),device_id:this.generateDeviceId(),properties:{},user_state:"anonymous"}}getUserIdentity(){return h({},this.userIdentity)}getDistinctId(){return this.userIdentity.distinct_id}getAnonymousId(){var t=this.userIdentity.anonymous_id;return t||(this.userIdentity.anonymous_id=this.generateAnonymousId(),this.storage.set(Xa,this.userIdentity.anonymous_id,Tl),T().debug("user","getAnonymousId generated (was missing)",this.userIdentity.anonymous_id.slice(0,12)+"..."),this.userIdentity.anonymous_id)}getUserProperties(){return h({},this.userIdentity.properties)}getEffectiveId(){return this.userIdentity.distinct_id||this.getAnonymousId()}getDeviceId(){return this.userIdentity.device_id}getUserState(){return this.userIdentity.user_state}consumeFirstVisit(){return!!this.Ye&&(this.Ye=!1,!0)}applyUpdate(t){if(void 0!==t.distinct_id&&(this.userIdentity.distinct_id=t.distinct_id),void 0!==t.user_state&&(this.userIdentity.user_state=t.user_state),void 0!==t.device_id&&(this.userIdentity.device_id=t.device_id),t.properties_set&&(this.userIdentity.properties=h({},this.userIdentity.properties,t.properties_set)),t.properties_set_once)for(var e of Object.keys(t.properties_set_once))e in this.userIdentity.properties||(this.userIdentity.properties[e]=t.properties_set_once[e]);this.saveUserIdentity()}reset(t){this.userIdentity={distinct_id:null,anonymous_id:this.generateAnonymousId(),device_id:t?this.generateDeviceId():this.userIdentity.device_id,properties:{$last_vtilt_reset:(new Date).toISOString()},user_state:"anonymous"},this.saveUserIdentity()}set_initial_person_info(t,e){if(!this.getStoredUserProperties()[rl]){var n=function(t,e){var n=t?Q([],qu,e||[]):[],i=null==r?void 0:r.href.substring(0,1e3);return{r:Ku().substring(0,1e3),u:i?jl(i,n,Hu):void 0}}(t,e);this.register_once({[rl]:n},void 0)}}get_initial_props(){var t=this.getStoredUserProperties()[rl];return t?Xu(t):{}}update_referrer_info(){var t={$referrer:Ku(),$referring_domain:Gu()};this.register_once(t,void 0)}loadUserIdentity(){var t=this.storage.get(Xa),e=this.storage.get(Ga),n=this.storage.get(Za),i=this.storage.get(Ka),r=this.getStoredUserProperties(),s=t||this.generateAnonymousId(),o=e||this.generateDeviceId(),a=n||null,l=i||"anonymous";t?T().debug("user","hydrate","loaded from storage",t.slice(0,12)+"..."):(this.Ye=!0,T().debug("user","hydrate","generated new anonymous_id"));var u=s||this.generateAnonymousId();return t||this.storage.set(Xa,u,Tl),e||this.storage.set(Ga,o,Tl),i||this.storage.set(Ka,l,Tl),{distinct_id:a,anonymous_id:u,device_id:o,properties:r,user_state:l}}saveUserIdentity(){this.storage.set(Xa,this.userIdentity.anonymous_id,Tl),this.storage.set(Ga,this.userIdentity.device_id,Tl),this.storage.set(Ka,this.userIdentity.user_state,Tl),this.userIdentity.distinct_id?this.storage.set(Za,this.userIdentity.distinct_id,Tl):this.storage.remove(Za),this.setStoredUserProperties(this.userIdentity.properties)}getStoredUserProperties(){return this.storage.getJSON(Ya)||{}}setStoredUserProperties(t){this.storage.setJSON(Ya,t,Tl)}register_once(t,e){var n=this.getStoredUserProperties(),i=!1;for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(r in n||(n[r]=t[r],i=!0));if(e)for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(s in n||(n[s]=e[s],i=!0));i&&this.setStoredUserProperties(n)}generateAnonymousId(){return"anon_"+J(16)}generateDeviceId(){return"device_"+J(16)}updateStorageMethod(t,e){this.storage=new Ol({method:t,cross_subdomain:e,sameSite:"Lax"})}}var eh=["LCP","CLS","FCP","INP"];class nh{constructor(t,e){this.tn=!1,this.en=!1,this.nn=[],this.rn=!1,this.sn=[],this._instance=t,this.le=e}get isEnabled(){return!1!==this.le.enabled}get isStarted(){return this.tn}get isLoaded(){return!!this.an}ln(t){var e;if(this.an)t(this.an);else if(this.nn.push(t),!this.en){this.en=!0;var n=null===(e=a.__VTiltExtensions__)||void 0===e?void 0:e.loadExternalDependency;if(!n)return T().error("feature",this.name,"loadExternalDependency not available"),this.en=!1,void(this.nn=[]);n(this._instance,this.scriptName,t=>{if(this.en=!1,t)return T().error("feature",this.name,"could not load "+this.scriptName+":",t),void(this.nn=[]);this.an||(this.an=this.un());var e=this.an,n=this.nn;for(var i of(this.nn=[],n))try{i(e)}catch(t){T().error("feature",this.name,"load callback error:",t)}})}}startIfEnabled(){this.isEnabled&&!this.tn&&(this.tn=!0,this.ln(t=>this.hn(t)))}hn(t){}stop(){this.tn=!1}updateConfig(t){this.le=h({},this.le,t)}dn(t){this.rn?t():this.sn.push(t)}cn(){if(!this.rn){this.rn=!0;var t=this.sn;for(var e of(this.sn=[],t))try{e()}catch(t){T().error("feature",this.name,"deferred call error:",t)}}}vn(){this.rn=!1,this.sn=[]}}class ih extends nh{startIfEnabledOrStop(t){if(this.isEnabled){if(this.tn&&this.an)return;this.tn=!0,this.ln(t=>this.hn(t))}else this.stop()}}var rh=9e5,sh="web-vitals";class oh extends nh{static extractConfig(t){var e=t.capture_performance;return"boolean"==typeof e?{web_vitals:e}:"object"==typeof e&&null!==e?e:{web_vitals:!1}}constructor(t,e){super(t,null!=e?e:oh.extractConfig(t.getConfig())),this.name="WebVitals",this.scriptName="web-vitals",this.fn=this.pn()}get isEnabled(){var t=null==r?void 0:r.protocol;return("http:"===t||"https:"===t)&&!0===this.le.web_vitals}startIfEnabled(){if(this.isEnabled&&!this.tn&&t){var e=this.gn();e?(this.tn=!0,this.an=e,this.mn(e)):(this.tn=!0,this.ln(t=>this.hn(t)))}}stop(){this.tn&&(this.bn(),this.yn&&(clearTimeout(this.yn),this.yn=void 0),this.tn=!1)}onConfigUpdate(t){var e=oh.extractConfig(t),n=this.isEnabled;this.le=e,n||!this.isEnabled||this.tn?n&&!this.isEnabled&&this.tn&&this.stop():this.startIfEnabled()}un(){var t=this.gn();if(!t)throw new Error("[vTilt:web-vitals] web-vitals loaded but callbacks not registered");return t}hn(t){this.mn(t)}get allowedMetrics(){return this.le.web_vitals_allowed_metrics||eh}get flushTimeoutMs(){return this.le.web_vitals_delayed_flush_ms||5e3}get maxAllowedValue(){var t=this.le.__web_vitals_max_value;return void 0===t?rh:0===t?0:t<6e4?rh:t}pn(){return{url:void 0,pathname:void 0,metrics:[],firstMetricTimestamp:void 0}}gn(){var t;return null===(t=a.__VTiltExtensions__)||void 0===t?void 0:t.webVitalsCallbacks}mn(t){var e=this.allowedMetrics,n=this.wn.bind(this);e.includes("LCP")&&t.onLCP&&t.onLCP(n),e.includes("CLS")&&t.onCLS&&t.onCLS(n,{reportAllChanges:!0}),e.includes("FCP")&&t.onFCP&&t.onFCP(n),e.includes("INP")&&t.onINP&&t.onINP(n),e.includes("TTFB")&&t.onTTFB&&t.onTTFB(n)}xn(){var e;return null===(e=null==t?void 0:t.location)||void 0===e?void 0:e.href}_n(){return null==r?void 0:r.pathname}wn(e){var n,s,o;try{if(!t||!i||!r)return;if(!(null==e?void 0:e.name)||void 0===(null==e?void 0:e.value))return void T().warn(sh,"invalid metric received",e);if(this.maxAllowedValue>0&&e.value>=this.maxAllowedValue&&"CLS"!==e.name)return void T().warn(sh,"ignoring "+e.name+" with value >= "+this.maxAllowedValue+"ms");var a=this.xn(),l=this._n();if(!a)return void T().warn(sh,"could not determine current URL");this.fn.url&&this.fn.url!==a&&this.bn(),this.fn.url||(this.fn.url=a,this.fn.pathname=l),this.fn.firstMetricTimestamp||(this.fn.firstMetricTimestamp=Date.now());var u=this.kn(e.attribution),d=null!==(o=null===(s=(n=this._instance).getSessionId)||void 0===s?void 0:s.call(n))&&void 0!==o?o:null,c=this.Sn(),v=h({},e,{attribution:u,timestamp:Date.now(),$current_url:a,$session_id:d,$window_id:c}),f=this.fn.metrics.findIndex(t=>t.name===e.name);f>=0?this.fn.metrics[f]=v:this.fn.metrics.push(v),this.Cn(),this.fn.metrics.length>=this.allowedMetrics.length&&this.bn()}catch(t){T().error(sh,"error adding metric to buffer:",t)}}kn(t){if(t){var e=h({},t);return"interactionTargetElement"in e&&delete e.interactionTargetElement,e}}Sn(){var t;try{return(null===(t=this._instance.sessionManager)||void 0===t?void 0:t.getWindowId())||null}catch(t){return null}}Cn(){this.yn&&clearTimeout(this.yn),this.yn=setTimeout(()=>{this.bn()},this.flushTimeoutMs)}bn(){if(this.yn&&(clearTimeout(this.yn),this.yn=void 0),0!==this.fn.metrics.length){try{var t={$pathname:this.fn.pathname,$current_url:this.fn.url};for(var e of this.fn.metrics)t["$web_vitals_"+e.name+"_value"]=e.value,t["$web_vitals_"+e.name+"_event"]={name:e.name,value:e.value,delta:e.delta,rating:e.rating,id:e.id,navigationType:e.navigationType,attribution:e.attribution,$session_id:e.$session_id,$window_id:e.$window_id};this._instance.capture("$web_vitals",t)}catch(t){T().error(sh,"error flushing metrics:",t)}this.fn=this.pn()}}}function ah(t,e,n){try{if(!(e in t))return()=>{};var i=t[e],r=n(i);return b(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__vtilt_wrapped__:{enumerable:!1,value:!0}})),t[e]=r,()=>{t[e]=i}}catch(t){return()=>{}}}class lh{constructor(e,n){var i;this.name="HistoryAutocapture",this.tn=!1,this._instance=e,this.le=n||lh.extractConfig(e.getConfig()),this.En=(null===(i=null==t?void 0:t.location)||void 0===i?void 0:i.pathname)||""}static extractConfig(t){return{enabled:!1!==t.capture_pageview}}get isEnabled(){return!1!==this.le.enabled&&!1!==this._instance.getConfig().capture_pageview}get isStarted(){return this.tn}startIfEnabled(){this.isEnabled&&!this.tn&&this.Tn()}stop(){this.tn&&(this.An&&(this.An(),this.An=void 0),this.tn=!1)}onConfigUpdate(t){this.le=lh.extractConfig(t),this.isEnabled&&!this.tn?this.Tn():!this.isEnabled&&this.tn&&this.stop()}Tn(){t&&r&&(this.En=r.pathname||"",this.In(),this.On(),this.tn=!0,T().info("history-autocapture","started"))}In(){var e,n;if(null==t?void 0:t.history){var i=this;(null===(e=t.history.pushState)||void 0===e?void 0:e.__vtilt_wrapped__)||ah(t.history,"pushState",t=>function(e,n,r){i.Mn(r),t.call(this,e,n,r),i.Rn("pushState")}),(null===(n=t.history.replaceState)||void 0===n?void 0:n.__vtilt_wrapped__)||ah(t.history,"replaceState",t=>function(e,n,r){i.Mn(r),t.call(this,e,n,r),i.Rn("replaceState")})}}Mn(t){var e;if(r){var n=r.pathname||"",i=null!==(e=function(t){if(!r)return null;if(null==t||""===t)return r.pathname||null;try{return new URL(String(t),r.href).pathname}catch(t){return null}}(t))&&void 0!==e?e:n;i!==n&&this._instance.tryCapturePageleave("spa_transition")}}On(){if(!this.An&&t){var e=()=>{this.Rn("popstate")};G(t,"popstate",e),this.An=()=>{null==t||t.removeEventListener("popstate",e)}}}Rn(e){this.isEnabled&&this.tn&&I(()=>{var n,s=null===(n=null==t?void 0:t.location)||void 0===n?void 0:n.pathname;if(s&&r&&i)if(s!==this.En){T().debug("history-autocapture",e,s),this.En=s;var o={navigation_type:e};this._instance.capture(sl,o)}else this.En=s})}}var uh=["a","button","form","input","select","textarea","label"],hh="$copy_autocapture",dh=['[id*="cookie" i]','[class*="cookie" i]','[id*="consent" i]','[class*="consent" i]','[id*="gdpr" i]','[class*="gdpr" i]','[id*="privacy-banner" i]','[class*="privacy-banner" i]','[id*="cookie-banner" i]','[class*="cookie-banner" i]','[id*="cookie-notice" i]','[class*="cookie-notice" i]',"#CybotCookiebotDialog",'[class^="CybotCookiebotDialog"]','[id^="onetrust"]','[class^="onetrust"]','[id^="cc-"]',".cc-banner",".cc-window",".cc-revoke",'[id^="cookieconsent"]','[class^="cookieconsent"]','[id^="gdpr-cookie"]','[id^="qc-cmp"]',"#termly-code-snippet-support",'[id^="iubenda"]','[id^="truste"]','[class^="truste"]',"#consent_blackbar",'[id^="didomi"]','[id^="usercentrics"]',"#uc-center-container",".klaro","#klaro","#cookiescript_injected",".cky-consent-container","#cky-consent","#cmplz-cookiebanner-container","#gdpr-cookie-message",'[class*="fs-cc"]','[class*="fc-cc"]',"[fs-cc]","[fs-cc-checkbox]",'[class*="cookie-preferences"]',"#cookie-preferences",'[role="dialog"][aria-label*="cookie" i]','[role="dialog"][aria-label*="consent" i]','[aria-describedby*="cookie" i]','[aria-label*="Cookie Preferences" i]'];function ch(t){return t.replace(/^\s+|\s+$/g,"")}function vh(t,e){return t.indexOf(e)>-1}function fh(t){return 1===(null==t?void 0:t.nodeType)}function ph(t){return 3===(null==t?void 0:t.nodeType)}function gh(t,e){var n;return(null===(n=null==t?void 0:t.tagName)||void 0===n?void 0:n.toLowerCase())===e}function mh(t){return 11===(null==t?void 0:t.nodeType)}function bh(t){return t?ch(t).split(/\s+/):[]}function yh(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className&&"string"==typeof t.className.baseVal?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return bh(e)}function wh(t){return g(t)?null:ch(t).split(/(\s+)/).filter(t=>Ph(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function xh(t){var e,n="";if(Uh(t)&&!jh(t)&&t.childNodes&&t.childNodes.length)for(var i=0;i<t.childNodes.length;i++){var r=t.childNodes[i];ph(r)&&r.textContent&&(n+=null!==(e=wh(r.textContent))&&void 0!==e?e:"")}return ch(n)}function _h(t){var e,n="";if(t&&t.childNodes&&t.childNodes.length)for(var i=0;i<t.childNodes.length;i++){var r=t.childNodes[i];if(r&&"span"===(null===(e=r.tagName)||void 0===e?void 0:e.toLowerCase()))try{n=(n+" "+xh(r)).trim(),r.childNodes&&r.childNodes.length&&(n=(n+" "+_h(r)).trim())}catch(t){}}return n}function kh(t){var e=xh(t);return Ph(e=(e+" "+_h(t)).trim())?e:""}function Sh(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do{e=e.previousSibling}while(e&&!fh(e));return e}function Ch(t){var e=t.parentNode;return!(!e||!fh(e))&&e}function Eh(e){var n=null==t?void 0:t.location.href;return!!(n&&e&&e.some(t=>n.match(t)))}var Th="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",Ah=new RegExp("^(?:"+Th+")$"),Ih=new RegExp(Th),Oh="\\d{3}-?\\d{2}-?\\d{4}",Mh=new RegExp("^("+Oh+")$"),Rh=new RegExp("("+Oh+")");function Ph(t,e){if(void 0===e&&(e=!0),g(t))return!1;if(f(t)){if(t=ch(t),(e?Ah:Ih).test((t||"").replace(/[- ]/g,"")))return!1;if((e?Mh:Rh).test(t))return!1}return!0}function Dh(t){return!!f(t)&&("_ngcontent"===t.substring(0,10)||"_nghost"===t.substring(0,7))}function Uh(t){for(var e=t;e&&e.parentNode&&!gh(e,"body");e=e.parentNode){var n=yh(e);if(vh(n,"vt-sensitive")||vh(n,"vt-no-capture"))return!1}if(vh(yh(t),"vt-include"))return!0;var i=t.type||"";if(f(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var r=t.name||t.id||"";if(f(r)){if(/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(r.replace(/[^a-zA-Z0-9]/g,"")))return!1}return!0}function jh(t){return!!(gh(t,"input")&&!["button","checkbox","submit","reset","radio"].includes(t.type)||gh(t,"textarea")||"true"===t.getAttribute("contenteditable"))}function Bh(t){if(!Uh(t))return null;if(gh(t,"input")){var e=t,n=(e.type||"text").toLowerCase();if("password"===n||"hidden"===n)return null;if("checkbox"===n||"radio"===n){var i={$el_value:e.checked?"true":"false"},r=function(t){var e=t.closest("label");if(e){var n=ch(e.textContent||"");if(n&&Ph(n))return wh(n)||null}if(t.id)try{var i=null===document||void 0===document?void 0:document.querySelector('label[for="'+t.id+'"]');if(i){var r=ch(i.textContent||"");if(r&&Ph(r))return wh(r)||null}}catch(t){}return null}(e);return r?i.$selected_text=r:e.value&&Ph(e.value)&&(i.$selected_text=e.value),i}var s=e.value;if(s&&Ph(s)){var o=wh(s);if(o)return{$el_value:o}}return null}if(gh(t,"select")){var a=t,l=a.selectedIndex;if(l>=0&&a.options[l]){var u=a.options[l],h={};u.value&&Ph(u.value)&&(h.$el_value=u.value);var d=u.text;if(d&&Ph(d)){var c=wh(d);c&&(h.$selected_text=c)}if(h.$el_value||h.$selected_text)return h}return null}return gh(t,"textarea"),null}function Nh(e,n,i,r,s){if(void 0===i&&(i=void 0),!t)return{capture:!1,reason:"no_window"};if(!e)return{capture:!1,reason:"no_element"};if(gh(e,"html")||!fh(e))return{capture:!1,reason:"html_element"};if((null==i?void 0:i.url_allowlist)&&!Eh(i.url_allowlist))return{capture:!1,reason:"url_allowlist_miss"};if((null==i?void 0:i.url_ignorelist)&&Eh(i.url_ignorelist))return{capture:!1,reason:"url_ignorelist_hit"};if(null==i?void 0:i.dom_event_allowlist){var o=i.dom_event_allowlist;if(o&&!o.some(t=>n.type===t))return{capture:!1,reason:"dom_event_not_allowed"}}for(var a=!1,l=[e],u=!0,h=e;h.parentNode&&!gh(h,"body");)if(mh(h.parentNode))l.push(h.parentNode.host),h=h.parentNode.host;else{if(!(u=Ch(h)))break;if(r||uh.indexOf(u.tagName.toLowerCase())>-1)a=!0;else{var d=t.getComputedStyle(u);d&&"pointer"===d.getPropertyValue("cursor")&&(a=!0)}l.push(u),h=u}if(!function(t,e){var n=null==e?void 0:e.element_allowlist;if(p(n))return!0;var i,r=function(t){if(n.some(e=>t.tagName.toLowerCase()===e))return{v:!0}};for(var s of t)if(i=r(s))return i.v;return!1}(l,i))return{capture:!1,reason:"element_allowlist_miss"};if(!function(t,e){var n=null==e?void 0:e.css_selector_allowlist;if(p(n))return!0;var i,r=function(t){if(n.some(e=>t.matches(e)))return{v:!0}};for(var s of t)if(i=r(s))return i.v;return!1}(l,i))return{capture:!1,reason:"css_selector_allowlist_miss"};if(function(t,e){var n=null==e?void 0:e.css_selector_ignorelist,i=void 0===n?dh:n;if(0===i.length)return!1;for(var r of t)for(var s of i)try{if(r.matches(s))return!0}catch(t){}return!1}(l,i))return{capture:!1,reason:"css_selector_ignorelist_hit"};var c=t.getComputedStyle(e);if(c&&"pointer"===c.getPropertyValue("cursor")&&"click"===n.type)return{capture:!0};var v=e.tagName.toLowerCase();switch(v){case"html":return{capture:!1,reason:"tag_html"};case"form":return(s||["submit"]).indexOf(n.type)>=0?{capture:!0}:{capture:!1,reason:"form_event_not_allowed"};case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(n.type)>=0?{capture:!0}:{capture:!1,reason:"input_event_not_allowed"};default:return a?(s||["click"]).indexOf(n.type)>=0?{capture:!0}:{capture:!1,reason:"dom_event_not_allowed"}:(s||["click"]).indexOf(n.type)>=0&&(uh.indexOf(v)>-1||"true"===e.getAttribute("contenteditable"))?{capture:!0}:{capture:!1,reason:"tag_not_capturable"}}}function Lh(t,e){return e.length>t?e.slice(0,t)+"...":e}function $h(t,e,n,i){var r=t.tagName.toLowerCase(),s={tag_name:r};uh.indexOf(r)>-1&&!n&&(s.$el_text=Lh(1024,"a"===r||"button"===r?kh(t):xh(t)));var o=yh(t);o.length>0&&(s.classes=o.filter(t=>""!==t));for(var a=0;a<t.attributes.length;a++){var l=t.attributes[a];if((!jh(t)||-1!==["name","id","class","aria-label"].indexOf(l.name))&&(!(null==i?void 0:i.includes(l.name))&&!e&&Ph(l.value)&&!Dh(l.name))){var u=l.value;"class"===l.name&&(u=bh(u).join(" ")),s["attr__"+l.name]=Lh(1024,u)}}for(var h=1,d=1,c=t;c=Sh(c);)h++,c.tagName===t.tagName&&d++;return s.nth_child=h,s.nth_of_type=d,s}function zh(t){if(!Uh(t))return{};for(var e={},n=0;n<t.attributes.length;n++){var i=t.attributes[n];if(i.name&&0===i.name.indexOf("data-vt-capture-attribute")){var r=i.name.replace("data-vt-capture-attribute-",""),s=i.value;r&&s&&Ph(s)&&(e[r]=s)}}return e}function qh(t){return t.replace(/"|\\"/g,'\\"')}function Fh(t){var e=t.attr__class;return e?m(e)?e:bh(e):void 0}function Hh(t){return function(t){var e=t.map(t=>{var e,n,i="";if(t.tag_name&&(i+=t.tag_name),t.attr_class)for(var r of(t.attr_class.sort(),t.attr_class))i+="."+r.replace(/"/g,"");var s=h({},t.text?{text:t.text}:{},{"nth-child":null!==(e=t.nth_child)&&void 0!==e?e:0,"nth-of-type":null!==(n=t.nth_of_type)&&void 0!==n?n:0},t.href?{href:t.href}:{},t.attr_id?{attr_id:t.attr_id}:{},t.attributes),o={};return Object.entries(s).sort((t,e)=>{var[n]=t,[i]=e;return n.localeCompare(i)}).forEach(t=>{var[e,n]=t;return o[qh(e.toString())]=qh(String(n))}),(i+=":")+Object.entries(o).map(t=>{var[e,n]=t;return e+'="'+n+'"'}).join("")});return e.join(";")}(function(t){return t.map(t=>{var e,n,i={text:null===(e=t.$el_text)||void 0===e?void 0:e.slice(0,400),tag_name:t.tag_name,href:null===(n=t.attr__href)||void 0===n?void 0:n.slice(0,2048),attr_class:Fh(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return Object.entries(t).filter(t=>{var[e]=t;return 0===e.indexOf("attr__")}).forEach(t=>{var[e,n]=t;return i.attributes[e]=n}),i})}(t))}var Wh=[25,50,75,100];function Jh(t){var e;if(!t)return null;var n=t.milestones,i=!0===n||"object"==typeof n&&null!==n,r="object"==typeof n&&null!==n&&(null===(e=n.thresholds)||void 0===e?void 0:e.length)?[...n.thresholds].sort((t,e)=>t-e):[...Wh],s=!0===t.pageleave;return i||s?{milestones:i,thresholds:r,pageleave:s,scroll_root_selector:t.scroll_root_selector}:null}class Vh{constructor(t){this.Pn=t,this.Dn=0,this.Un=new Set,this.jn=null,this.Bn=null,this.Nn=null,this.Ln=null}start(){this.stop(),this.Bn=function(e){if(!t)return null;if(e){var n=Array.isArray(e)?e:[e];for(var r of n){var s=null==i?void 0:i.querySelector(r);if(s instanceof Element)return s}}return t}(this.Pn.scroll_root_selector),this.Bn&&(this.jn=()=>this.$n(),G(this.Bn,"scroll",this.jn,{passive:!0}),this.zn(),this.Ln=this.Pn.onPageview(()=>this.reset()))}stop(){this.Ln&&(this.Ln(),this.Ln=null),null!=this.Nn&&t&&(t.cancelAnimationFrame(this.Nn),this.Nn=null),this.jn&&this.Bn&&(this.Bn.removeEventListener("scroll",this.jn,{passive:!0}),this.jn=null,this.Bn=null)}reset(){this.Dn=0,this.Un.clear(),this.zn()}getMaxPct(){return this.Dn}$n(){t&&null==this.Nn&&(this.Nn=t.requestAnimationFrame(()=>{this.Nn=null,this.zn()}))}zn(){if(this.Bn){var e=function(e){var n,r,s,o,a,l;if(!e)return 0;if(e===t){var u=null!==(n=t.scrollY)&&void 0!==n?n:0,h=null!==(r=t.innerHeight)&&void 0!==r?r:0,d=null==i?void 0:i.documentElement,c=null==i?void 0:i.body,v=Math.max(null!==(s=null==d?void 0:d.scrollHeight)&&void 0!==s?s:0,null!==(o=null==c?void 0:c.scrollHeight)&&void 0!==o?o:0,null!==(a=null==d?void 0:d.offsetHeight)&&void 0!==a?a:0,null!==(l=null==c?void 0:c.offsetHeight)&&void 0!==l?l:0)-h;return v<=0?100:Math.round(Math.min(100,u/v*100))}var f=e,p=f.scrollHeight-f.clientHeight;return p<=0?100:Math.round(Math.min(100,f.scrollTop/p*100))}(this.Bn);if(e>this.Dn&&(this.Dn=e),this.Pn.milestones&&this.Pn.isUrlAllowed())for(var n of this.Pn.thresholds)this.Dn>=n&&!this.Un.has(n)&&(this.Un.add(n),this.Pn.capture(cl,{[xl]:n,[_l]:this.Dn}))}}}function Kh(t,e){return t.indexOf(e)>-1}class Gh{constructor(){this.clicks=[],this.RAGE_CLICK_THRESHOLD_PX=30,this.RAGE_CLICK_TIMEOUT_MS=1e3,this.RAGE_CLICK_CLICK_COUNT=3}isRageClick(t,e,n){if(this.clicks=this.clicks.filter(t=>n-t.timestamp<this.RAGE_CLICK_TIMEOUT_MS),this.clicks.length>0){var i=this.clicks[this.clicks.length-1];Math.sqrt(Math.pow(t-i.x,2)+Math.pow(e-i.y,2))>this.RAGE_CLICK_THRESHOLD_PX&&(this.clicks=[])}return this.clicks.push({x:t,y:e,timestamp:n}),this.clicks.length>=this.RAGE_CLICK_CLICK_COUNT}}function Xh(e,n){for(var i,r,s,o,{e:a,maskAllElementAttributes:l,maskAllText:u,elementAttributeIgnoreList:h,elementsChainAsString:d,captureElementValues:c}=n,v=[e],f=e;f.parentNode&&!gh(f,"body");)mh(f.parentNode)?(v.push(f.parentNode.host),f=f.parentNode.host):(v.push(f.parentNode),f=f.parentNode);var p,g=[],m={},b=!1,y=!1;for(var w of v){var x=Uh(w);if("a"===w.tagName.toLowerCase()){var _=w.getAttribute("href");b=!!(x&&_&&Ph(_))&&_}Kh(yh(w),"vt-no-capture")&&(y=!0),g.push($h(w,l,u,h));var k=zh(w);Object.assign(m,k)}if(y)return{props:{},explicitNoCapture:y};if(u||("a"===e.tagName.toLowerCase()||"button"===e.tagName.toLowerCase()?g[0].$el_text=kh(e):g[0].$el_text=xh(e)),"change"===a.type&&c){var S=Bh(e);S&&(S.$el_value&&(g[0].$el_value=S.$el_value),S.$selected_text&&(g[0].$selected_text=S.$selected_text))}if(b){g[0].attr__href=b;var C=null===(i=Rl(b))||void 0===i?void 0:i.host,E=null===(r=null==t?void 0:t.location)||void 0===r?void 0:r.host;C&&E&&C!==E&&(p=b)}var T=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return Object.assign({},...e)}({$event_type:a.type,$ce_version:1},d?{}:{$elements:g},{$elements_chain:Hh(g)},(null===(s=g[0])||void 0===s?void 0:s.$el_text)?{$el_text:null===(o=g[0])||void 0===o?void 0:o.$el_text}:{},p&&"click"===a.type?{$external_click_url:p}:{},m);return{props:T}}var Qh=["copy","cut"];class Zh{static extractConfig(t){return{enabled:!1!==t.autocapture}}constructor(t,e){this.name="Autocapture",this.qn=!1,this.Fn=null,this.Hn=null,this.Wn=null,this.Jn=new Gh,this.Vn=!0,this.Kn=null,this.Gn=null,this.Xn=null,this.Qn=null,this.Zn=!1,this.Yn=null,this.ti=null,this._instance=t}get le(){var t=this._instance.getConfig().autocapture;if(t===this.Gn&&this.Kn)return this.Kn;this.Gn=t;var e=function(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}(t)?t:{};return e.url_allowlist&&(e.url_allowlist=e.url_allowlist.map(t=>"string"==typeof t?new RegExp(t):t)),e.url_ignorelist&&(e.url_ignorelist=e.url_ignorelist.map(t=>"string"==typeof t?new RegExp(t):t)),this.Kn=e,e}get isEnabled(){return this.ei().enabled}get isStarted(){return this.qn}startIfEnabled(){var{enabled:t,reason:e}=this.ei();t?this.qn?(this.ni(),this.ii()):(this.ri(),this.qn=!0,T().info("autocapture","started; listening for click/change/submit events")):this.qn?(T().info("autocapture","stopping; reason:",null!=e?e:"unknown"),this.si(),this.qn=!1):(T().debug("autocapture","not started; reason:",null!=e?e:"unknown"),this.oi())}stop(){this.qn&&(this.si(),this.qn=!1,T().info("autocapture","stopped (DOM listeners detached)")),this.oi()}getMaxScrollDepthPctForPageleave(){var t=Jh(this.le.scroll_depth);return(null==t?void 0:t.pageleave)&&this.Yn?this.Yn.getMaxPct():null}onConfigUpdate(t){var e=t;"boolean"==typeof e.elementsChainAsString&&(this.Vn=e.elementsChainAsString),void 0!==e.autocapture_opt_out&&(this.Fn=!!e.autocapture_opt_out),this.startIfEnabled()}updateConfig(t){void 0!==t.enabled&&(this.Hn=t.enabled,t.enabled&&(this.Fn=!1),this.startIfEnabled())}getDiagnostics(){var t,e,n,{enabled:i,reason:r}=this.ei(),s=Jh(this.le.scroll_depth);return{isEnabled:i,isStarted:this.qn,disabledReason:i?null:r,inputs:{configAutocapture:this._instance.getConfig().autocapture,isDisabledServerSide:null!==(t=this.Fn)&&void 0!==t&&t,userOverride:this.Hn,elementsChainAsString:this.Vn,captureCopiedText:!!this.le.capture_copied_text,scrollDepthMilestones:null!==(e=null==s?void 0:s.milestones)&&void 0!==e&&e,scrollDepthPageleave:null!==(n=null==s?void 0:s.pageleave)&&void 0!==n&&n,scrollDepthListenerAttached:null!==this.Yn}}}setElementSelectors(t){this.Wn=t}getElementSelectors(t){var e,n=[];return null===(e=this.Wn)||void 0===e||e.forEach(e=>{var r=null==i?void 0:i.querySelectorAll(e);null==r||r.forEach(i=>{t===i&&n.push(e)})}),n}ei(){if(!1===this.Hn)return{enabled:!1,reason:"user_stop_called"};if(this.Fn)return{enabled:!1,reason:"server_opt_out"};if(!0===this.Hn)return{enabled:!0,reason:null};var t=this._instance.getConfig().autocapture;return!1===t?{enabled:!1,reason:"config_autocapture_false"}:null==t?{enabled:!1,reason:"config_autocapture_undefined"}:{enabled:!0,reason:null}}ri(){this.ai()?t&&i&&(this.Xn=e=>{var n=e||(null==t?void 0:t.event);if(n)try{this.li(n)}catch(t){T().error("autocapture","capture handler threw",t)}},G(i,"submit",this.Xn,{capture:!0}),G(i,"change",this.Xn,{capture:!0}),G(i,"click",this.Xn,{capture:!0}),this.ni(),this.ii()):T().warn("autocapture","browser unsupported (no querySelectorAll)")}si(){i&&(this.Xn&&(i.removeEventListener("submit",this.Xn,!0),i.removeEventListener("change",this.Xn,!0),i.removeEventListener("click",this.Xn,!0),this.Xn=null),this.Qn&&this.Zn&&(i.removeEventListener("copy",this.Qn,!0),i.removeEventListener("cut",this.Qn,!0),this.Zn=!1,this.Qn=null),this.oi())}ii(){var e,n=Jh(this.le.scroll_depth),i=this.isEnabled&&null!==n&&null!==Jh(null==(e=this.le)?void 0:e.scroll_depth);i&&!this.Yn?(this.Yn=new Vh({milestones:n.milestones,pageleave:n.pageleave,thresholds:n.thresholds,scroll_root_selector:n.scroll_root_selector,capture:(t,e)=>this._instance.capture(t,e),isUrlAllowed:()=>{return e=this.le,!(!t||(null==e?void 0:e.url_allowlist)&&!Eh(e.url_allowlist)||(null==e?void 0:e.url_ignorelist)&&Eh(e.url_ignorelist));var e},onPageview:t=>(this.ti&&this.ti(),this.ti=this._instance.on(U,e=>{(null==e?void 0:e.event)===sl&&t()}),()=>{var t;null===(t=this.ti)||void 0===t||t.call(this),this.ti=null})}),this.Yn.start(),T().info("autocapture","scroll depth tracking started",{milestones:n.milestones,pageleave:n.pageleave})):i||this.oi()}oi(){this.Yn&&(this.Yn.stop(),this.Yn=null,T().info("autocapture","scroll depth tracking stopped")),this.ti&&(this.ti(),this.ti=null)}ni(){if(i){var e=!!this.le.capture_copied_text;e&&!this.Zn?(this.Qn=e=>{var n=e||(null==t?void 0:t.event);if(n)try{this.li(n,hh)}catch(t){T().error("autocapture","copy handler threw",t)}},G(i,"copy",this.Qn,{capture:!0}),G(i,"cut",this.Qn,{capture:!0}),this.Zn=!0):!e&&this.Zn&&this.Qn&&(i.removeEventListener("copy",this.Qn,!0),i.removeEventListener("cut",this.Qn,!0),this.Zn=!1,this.Qn=null)}}li(e,n){var i,r,s,o,a,l,u,h;if(void 0===n&&(n="$autocapture"),this.isEnabled)if(e.isTrusted){var d=function(t){var e;return p(t.target)?t.srcElement||null:(null===(e=t.target)||void 0===e?void 0:e.shadowRoot)?t.composedPath()[0]||null:t.target||null}(e);if(ph(d)&&(d=d.parentNode||null),"$autocapture"===n&&"click"===e.type&&e instanceof MouseEvent)this._instance.getConfig().rageclick&&(null===(i=this.Jn)||void 0===i?void 0:i.isRageClick(e.clientX,e.clientY,(new Date).getTime()))&&(T().info("autocapture","$rageclick detected"),this.li(e,"$rageclick"));var c=n===hh;if(d){var v=Nh(d,e,this.le,c,c?[...Qh]:void 0);if(v.capture){var f=this._instance.getConfig(),{props:g,explicitNoCapture:m}=Xh(d,{e:e,maskAllElementAttributes:null!==(o=f.mask_all_element_attributes)&&void 0!==o&&o,maskAllText:null!==(a=f.mask_all_text)&&void 0!==a&&a,elementAttributeIgnoreList:this.le.element_attribute_ignorelist,elementsChainAsString:this.Vn,captureElementValues:null!==(l=this.le.capture_element_values)&&void 0!==l&&l});if(m)return T().debug("autocapture","skip: vt-no-capture class on element chain",{tag:null===(u=d.tagName)||void 0===u?void 0:u.toLowerCase()}),!1;var b=this.getElementSelectors(d);if(b&&b.length>0&&(g.$element_selectors=b),n===hh){var y=wh(null===(h=null==t?void 0:t.getSelection())||void 0===h?void 0:h.toString()),w=e.type||"clipboard";if(!y)return T().debug("autocapture","skip copy: empty selection"),!1;g.$selected_content=y,g.$copy_type=w}return this._instance.capture(n,g),!0}T().debug("autocapture","skip:",null!==(r=v.reason)&&void 0!==r?r:"unknown",{type:e.type,tag:null===(s=d.tagName)||void 0===s?void 0:s.toLowerCase()})}else T().debug("autocapture","skip: no event target",{type:e.type})}else T().debug("autocapture","skip: synthetic event (isTrusted=false)",{type:e.type})}ai(){return b(null==i?void 0:i.querySelectorAll)}}var Yh="replay";class td extends ih{constructor(t,e){super(t,e||td.extractConfig(t.getConfig())),this.name="SessionRecording",this.scriptName="recorder"}static extractConfig(t){var e,n,i,r=t.session_recording||{};return{enabled:null!==(e=r.enabled)&&void 0!==e&&e,sampleRate:r.sampleRate,minimumDurationMs:r.minimumDurationMs,sessionIdleThresholdMs:r.sessionIdleThresholdMs,fullSnapshotIntervalMs:r.fullSnapshotIntervalMs,captureConsole:null!==(n=r.captureConsole)&&void 0!==n&&n,captureNetwork:null!==(i=r.captureNetwork)&&void 0!==i&&i,captureCanvas:r.captureCanvas,blockClass:r.blockClass,blockSelector:r.blockSelector,skipDefaultInvisibleBlocking:r.skipDefaultInvisibleBlocking,ignoreClass:r.ignoreClass,maskTextClass:r.maskTextClass,maskTextSelector:r.maskTextSelector,maskAllInputs:r.maskAllInputs,maskInputOptions:r.maskInputOptions,masking:r.masking,recordHeaders:r.recordHeaders,recordBody:r.recordBody,compressEvents:r.compressEvents,__mutationThrottlerRefillRate:r.__mutationThrottlerRefillRate,__mutationThrottlerBucketSize:r.__mutationThrottlerBucketSize}}get isEnabled(){var e,n=this._instance.getConfig(),i=null!==(e=this.le.enabled)&&void 0!==e&&e,r=!n.disable_session_recording;return!!t&&i&&r}get isStarted(){var t;return this.tn&&!!(null===(t=this.an)||void 0===t?void 0:t.isStarted)}startIfEnabled(){this.startIfEnabledOrStop("recording_initialized")}startIfEnabledOrStop(t){var e;if(!this.isEnabled||!(null===(e=this.an)||void 0===e?void 0:e.isStarted)){var n=void 0!==Object.assign&&void 0!==Array.from;this.isEnabled&&n?(this.tn=!0,this.ln(e=>this.hn(e,t)),T().info(Yh,"starting")):this.stop()}}stop(){I(()=>{var t;null===(t=this.an)||void 0===t||t.stop(),this.tn=!1})}onConfigUpdate(t){var e;this.le=td.extractConfig(t),null===(e=this.an)||void 0===e||e.updateConfig(this.le),this.startIfEnabledOrStop("config_updated")}un(){var t,e=null===(t=a.__VTiltExtensions__)||void 0===t?void 0:t.initSessionRecording;if(!e)throw new Error("[vTilt:replay] initSessionRecording not available after script load");return e(this._instance,this.le)}hn(t,e){t.start(e)}get started(){return this.isStarted}get status(){var t;return(null===(t=this.an)||void 0===t?void 0:t.status)||"lazy_loading"}get sessionId(){var t;return(null===(t=this.an)||void 0===t?void 0:t.sessionId)||""}stopRecording(){this.stop()}log(t,e){var n;void 0===e&&(e="log"),(null===(n=this.an)||void 0===n?void 0:n.log)?this.an.log(t,e):T().warn(Yh,"log called before recorder was ready")}updateConfig(t){var e;this.le=h({},this.le,t),null===(e=this.an)||void 0===e||e.updateConfig(this.le)}}var ed=(t=>(t[t.Mutation=0]="Mutation",t[t.MouseMove=1]="MouseMove",t[t.MouseInteraction=2]="MouseInteraction",t[t.Scroll=3]="Scroll",t[t.ViewportResize=4]="ViewportResize",t[t.Input=5]="Input",t[t.TouchMove=6]="TouchMove",t[t.MediaInteraction=7]="MediaInteraction",t[t.StyleSheetRule=8]="StyleSheetRule",t[t.CanvasMutation=9]="CanvasMutation",t[t.Font=10]="Font",t[t.Log=11]="Log",t[t.Drag=12]="Drag",t[t.StyleDeclaration=13]="StyleDeclaration",t[t.Selection=14]="Selection",t[t.AdoptedStyleSheet=15]="AdoptedStyleSheet",t[t.CustomElement=16]="CustomElement",t))(ed||{});ed.MouseMove,ed.MouseInteraction,ed.Scroll,ed.ViewportResize,ed.Input,ed.TouchMove,ed.MediaInteraction,ed.Drag;var nd=Uint8Array,id=Uint16Array,rd=Int32Array,sd=new nd([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),od=new nd([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ad=new nd([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ld=function(t,e){for(var n=new id(31),i=0;i<31;++i)n[i]=e+=1<<t[i-1];var r=new rd(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return{b:n,r:r}},ud=ld(sd,2),hd=ud.b,dd=ud.r;hd[28]=258,dd[258]=28;for(var cd=ld(od,0).r,vd=new id(32768),fd=0;fd<32768;++fd){var pd=(43690&fd)>>1|(21845&fd)<<1;pd=(61680&(pd=(52428&pd)>>2|(13107&pd)<<2))>>4|(3855&pd)<<4,vd[fd]=((65280&pd)>>8|(255&pd)<<8)>>1}var gd=function(t,e,n){for(var i=t.length,r=0,s=new id(e);r<i;++r)t[r]&&++s[t[r]-1];var o,a=new id(e);for(r=1;r<e;++r)a[r]=a[r-1]+s[r-1]<<1;if(n){o=new id(1<<e);var l=15-e;for(r=0;r<i;++r)if(t[r])for(var u=r<<4|t[r],h=e-t[r],d=a[t[r]-1]++<<h,c=d|(1<<h)-1;d<=c;++d)o[vd[d]>>l]=u}else for(o=new id(i),r=0;r<i;++r)t[r]&&(o[r]=vd[a[t[r]-1]++]>>15-t[r]);return o},md=new nd(288);for(fd=0;fd<144;++fd)md[fd]=8;for(fd=144;fd<256;++fd)md[fd]=9;for(fd=256;fd<280;++fd)md[fd]=7;for(fd=280;fd<288;++fd)md[fd]=8;var bd=new nd(32);for(fd=0;fd<32;++fd)bd[fd]=5;var yd=gd(md,9,0),wd=gd(bd,5,0),xd=function(t){return(t+7)/8|0},_d=function(t,e,n){return(null==n||n>t.length)&&(n=t.length),new nd(t.subarray(e,n))},kd=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>8},Sd=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>8,t[i+2]|=n>>16},Cd=function(t,e){for(var n=[],i=0;i<t.length;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return{t:Rd,l:0};if(1==r){var o=new nd(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(t,e){return t.f-e.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,h=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};h!=r-1;)a=n[n[u].f<n[d].f?u++:d++],l=n[u!=h&&n[u].f<n[d].f?u++:d++],n[h++]={s:-1,f:a.f+l.f,l:a,r:l};var c=s[0].s;for(i=1;i<r;++i)s[i].s>c&&(c=s[i].s);var v=new id(c+1),f=Ed(n[h-1],v,0);if(f>e){i=0;var p=0,g=f-e,m=1<<g;for(s.sort(function(t,e){return v[e.s]-v[t.s]||t.f-e.f});i<r;++i){var b=s[i].s;if(!(v[b]>e))break;p+=m-(1<<f-v[b]),v[b]=e}for(p>>=g;p>0;){var y=s[i].s;v[y]<e?p-=1<<e-v[y]++-1:++i}for(;i>=0&&p;--i){var w=s[i].s;v[w]==e&&(--v[w],++p)}f=e}return{t:new nd(v),l:f}},Ed=function(t,e,n){return-1==t.s?Math.max(Ed(t.l,e,n+1),Ed(t.r,e,n+1)):e[t.s]=n},Td=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new id(++e),i=0,r=t[0],s=1,o=function(t){n[i++]=t},a=1;a<=e;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return{c:n.subarray(0,i),n:e}},Ad=function(t,e){for(var n=0,i=0;i<e.length;++i)n+=t[i]*e[i];return n},Id=function(t,e,n){var i=n.length,r=xd(e+2);t[r]=255&i,t[r+1]=i>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;s<i;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Od=function(t,e,n,i,r,s,o,a,l,u,h){kd(e,h++,n),++r[256];for(var d=Cd(r,15),c=d.t,v=d.l,f=Cd(s,15),p=f.t,g=f.l,m=Td(c),b=m.c,y=m.n,w=Td(p),x=w.c,_=w.n,k=new id(19),S=0;S<b.length;++S)++k[31&b[S]];for(S=0;S<x.length;++S)++k[31&x[S]];for(var C=Cd(k,7),E=C.t,T=C.l,A=19;A>4&&!E[ad[A-1]];--A);var I,O,M,R,P=u+5<<3,D=Ad(r,md)+Ad(s,bd)+o,U=Ad(r,c)+Ad(s,p)+o+14+3*A+Ad(k,E)+2*k[16]+3*k[17]+7*k[18];if(l>=0&&P<=D&&P<=U)return Id(e,h,t.subarray(l,l+u));if(kd(e,h,1+(U<D)),h+=2,U<D){I=gd(c,v,0),O=c,M=gd(p,g,0),R=p;var j=gd(E,T,0);kd(e,h,y-257),kd(e,h+5,_-1),kd(e,h+10,A-4),h+=14;for(S=0;S<A;++S)kd(e,h+3*S,E[ad[S]]);h+=3*A;for(var B=[b,x],N=0;N<2;++N){var L=B[N];for(S=0;S<L.length;++S){var z=31&L[S];kd(e,h,j[z]),h+=E[z],z>15&&(kd(e,h,L[S]>>5&127),h+=L[S]>>12)}}}else I=yd,O=md,M=wd,R=bd;for(S=0;S<a;++S){var q=i[S];if(q>255){Sd(e,h,I[(z=q>>18&31)+257]),h+=O[z+257],z>7&&(kd(e,h,q>>23&31),h+=sd[z]);var F=31&q;Sd(e,h,M[F]),h+=R[F],F>3&&(Sd(e,h,q>>5&8191),h+=od[F])}else Sd(e,h,I[q]),h+=O[q]}return Sd(e,h,I[256]),h+O[256]},Md=new rd([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Rd=new nd(0),Pd=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,i=9;--i;)n=(1&n&&-306674912)^n>>>1;t[e]=n}return t}(),Dd=function(t,e,n,i,r){if(!r&&(r={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),o=new nd(s.length+t.length);o.set(s),o.set(t,s.length),t=o,r.w=s.length}return function(t,e,n,i,r,s){var o=s.z||t.length,a=new nd(i+o+5*(1+Math.ceil(o/7e3))+r),l=a.subarray(i,a.length-r),u=s.l,h=7&(s.r||0);if(e){h&&(l[0]=s.r>>3);for(var d=Md[e-1],c=d>>13,v=8191&d,f=(1<<n)-1,p=s.p||new id(32768),g=s.h||new id(f+1),m=Math.ceil(n/3),b=2*m,y=function(e){return(t[e]^t[e+1]<<m^t[e+2]<<b)&f},w=new rd(25e3),x=new id(288),_=new id(32),k=0,S=0,C=s.i||0,E=0,T=s.w||0,A=0;C+2<o;++C){var I=y(C),O=32767&C,M=g[I];if(p[O]=M,g[I]=O,T<=C){var R=o-C;if((k>7e3||E>24576)&&(R>423||!u)){h=Od(t,l,0,w,x,_,S,E,A,C-A,h),E=k=S=0,A=C;for(var P=0;P<286;++P)x[P]=0;for(P=0;P<30;++P)_[P]=0}var D=2,U=0,j=v,B=O-M&32767;if(R>2&&I==y(C-B))for(var N=Math.min(c,R)-1,L=Math.min(32767,C),z=Math.min(258,R);B<=L&&--j&&O!=M;){if(t[C+D]==t[C+D-B]){for(var q=0;q<z&&t[C+q]==t[C+q-B];++q);if(q>D){if(D=q,U=B,q>N)break;var F=Math.min(B,q-2),H=0;for(P=0;P<F;++P){var W=C-B+P&32767,J=W-p[W]&32767;J>H&&(H=J,M=W)}}}B+=(O=M)-(M=p[O])&32767}if(U){w[E++]=268435456|dd[D]<<18|cd[U];var V=31&dd[D],K=31&cd[U];S+=sd[V]+od[K],++x[257+V],++_[K],T=C+D,++k}else w[E++]=t[C],++x[t[C]]}}for(C=Math.max(C,T);C<o;++C)w[E++]=t[C],++x[t[C]];h=Od(t,l,u,w,x,_,S,E,A,C-A,h),u||(s.r=7&h|l[h/8|0]<<3,h-=7,s.h=g,s.p=p,s.i=C,s.w=T)}else{for(C=s.w||0;C<o+u;C+=65535){var G=C+65535;G>=o&&(l[h/8|0]=u,G=o),h=Id(l,h+1,t.subarray(C,G))}s.i=o}return _d(a,0,i+xd(h)+r)}(t,null==e.level?6:e.level,null==e.mem?r.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):20:12+e.mem,n,i,r)},Ud=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function jd(t,e){e||(e={});var n=function(){var t=-1;return{p:function(e){for(var n=t,i=0;i<e.length;++i)n=Pd[255&n^e[i]]^n>>>8;t=n},d:function(){return~t}}}(),i=t.length;n.p(t);var r=Dd(t,e,function(t){return 10+(t.filename?t.filename.length+1:0)}(e),8),s=r.length;return function(t,e){var n=e.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=e.level<2?4:9==e.level?2:0,t[9]=3,0!=e.mtime&&Ud(t,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),n){t[3]=8;for(var i=0;i<=n.length;++i)t[i+10]=n.charCodeAt(i)}}(r,e),Ud(r,s-8,n.d()),Ud(r,s-4,i),r}var Bd="undefined"!=typeof TextEncoder&&new TextEncoder,Nd="undefined"!=typeof TextDecoder&&new TextDecoder;try{Nd.decode(Rd,{stream:!0})}catch(t){}var Ld="chat";class $d extends nh{constructor(t,e){super(t,e||$d.extractConfig(t.getConfig())),this.name="Chat",this.scriptName="chat",this.ui=null,this.hi=!1,this.di=null,this.ci=null,this.fi=[],this.pi=[],this.Bt=[],this.Nt=[],this.Lt=[],this.ae=!1,this.gi=null,this.mi=()=>{if("visible"===document.visibilityState)return this.bi(),void this.yi();this.wi()}}static extractConfig(t){var e,n=t.chat||{};return{enabled:n.enabled,autoConfig:null===(e=n.autoConfig)||void 0===e||e,position:n.position,greeting:n.greeting,color:n.color,aiMode:n.aiMode,aiGreeting:n.aiGreeting,preload:n.preload,offlineMessage:n.offlineMessage,collectEmailOffline:n.collectEmailOffline,bubble:n.bubble}}get isEnabled(){var t;return!1!==this.le.enabled&&(!0===this.le.enabled||!this._instance.getConfig().disable_chat&&!0===(null===(t=this.ui)||void 0===t?void 0:t.enabled))}startIfEnabled(){T().debug(Ld,"startIfEnabled"),this.xi().catch(t=>{T().error(Ld,"error starting:",t)})}stop(){this.destroy(),this.tn=!1}onConfigUpdate(t){var e,n;this.le=$d.extractConfig(t),this.ki()||this.Si(),this.an&&(null===(n=(e=this.an).updateConfig)||void 0===n||n.call(e,this.getMergedConfig()))}un(){var e,n,i,r=null===(e=a.__VTiltExtensions__)||void 0===e?void 0:e.initChat;if(!r)throw new Error("[vTilt:chat] initChat not available after script load");var s=this.getMergedConfig(),o=r(this._instance,s);this.ae&&o.show(),this.Bt.forEach(t=>o.onMessage(t)),this.Nt.forEach(t=>o.onTyping(t)),this.Lt.forEach(t=>o.onConnectionChange(t)),null===(n=this.ci)||void 0===n||n.destroy(),this.ci=null;var l=null===(i=null==t?void 0:t.document)||void 0===i?void 0:i.getElementById("vtilt-chat-bubble");return l&&!l.closest("#vtilt-chat-container")&&l.remove(),o}hn(t){this.pi.forEach(t=>t()),this.pi=[],t.isOpen||(this.bi(),this.yi()),T().info(Ld,"loaded and ready")}xi(){var t=this;return u(function*(){var e,n;try{if(!1===t.le.enabled)return void T().info(Ld,"disabled by code config");if(t._instance.getConfig().disable_chat)return void T().info(Ld,"disabled by disable_chat config");if(!1!==t.le.autoConfig&&(yield t.Ci()),!t.isEnabled)return void T().info(Ld,"not enabled (check dashboard settings)");T().debug(Ld,"startIfEnabled enabled"),t.tn=!0,!0===t.le.preload&&t.Ei();var i=t.getMergedConfig();(null===(e=t.ui)||void 0===e?void 0:e.enabled)&&!1!==(null===(n=i.bubble)||void 0===n?void 0:n.visible)&&t.Ti(),T().info(Ld,"ready (lazy-load on demand)")}finally{t.cn()}})()}get isOpen(){var t,e;return null!==(e=null===(t=this.an)||void 0===t?void 0:t.isOpen)&&void 0!==e&&e}get isConnected(){var t,e;return null!==(e=null===(t=this.an)||void 0===t?void 0:t.isConnected)&&void 0!==e&&e}get isLoading(){var t,e;return this.en||null!==(e=null===(t=this.an)||void 0===t?void 0:t.isLoading)&&void 0!==e&&e}get unreadCount(){var t,e;return null!==(e=null===(t=this.an)||void 0===t?void 0:t.unreadCount)&&void 0!==e?e:0}get channel(){var t,e;return null!==(e=null===(t=this.an)||void 0===t?void 0:t.channel)&&void 0!==e?e:null}get channels(){var t,e;return null!==(e=null===(t=this.an)||void 0===t?void 0:t.channels)&&void 0!==e?e:[]}get currentView(){var t,e;return null!==(e=null===(t=this.an)||void 0===t?void 0:t.currentView)&&void 0!==e?e:"list"}open(){this.dn(()=>{this.wi(),this.Ai(()=>{var t;return null===(t=this.an)||void 0===t?void 0:t.open()})})}close(){this.dn(()=>{this.an?(this.an.close(),this.bi(),this.yi()):this.Ai(()=>{var t;null===(t=this.an)||void 0===t||t.close(),this.bi(),this.yi()})})}toggle(){this.dn(()=>{this.an?this.an.toggle():this.open()})}show(){this.dn(()=>{this.ae=!0,this.an?this.an.show():this.tn&&this.Ti()})}hide(){this.dn(()=>{var e;if(this.ae=!1,this.an)this.an.hide();else{var n=null===(e=null==t?void 0:t.document)||void 0===e?void 0:e.getElementById("vtilt-chat-bubble");n&&(n.style.display="none")}})}getChannels(){this.dn(()=>{this.Ai(()=>{var t;return null===(t=this.an)||void 0===t?void 0:t.getChannels()})})}selectChannel(t){this.dn(()=>{this.Ai(()=>{var e;return null===(e=this.an)||void 0===e?void 0:e.selectChannel(t)})})}createChannel(){this.dn(()=>{this.Ai(()=>{var t;return null===(t=this.an)||void 0===t?void 0:t.createChannel()})})}goToChannelList(){this.dn(()=>{this.an?this.an.goToChannelList():this.Ai(()=>{var t;return null===(t=this.an)||void 0===t?void 0:t.goToChannelList()})})}sendMessage(t,e){return this.an?this.an.sendMessage(t,e):new Promise((n,i)=>{this.dn(()=>{this.an?this.an.sendMessage(t,e).then(n).catch(i):(this.fi.push({content:t,options:e,resolve:n,reject:i}),this.Ai(()=>{var t,e=this.fi;for(var n of(this.fi=[],e))null===(t=this.an)||void 0===t||t.sendMessage(n.content,n.options).then(n.resolve).catch(n.reject)}))})})}markAsRead(){this.dn(()=>{this.an?this.an.markAsRead():this.Ai(()=>{var t;return null===(t=this.an)||void 0===t?void 0:t.markAsRead()})})}registerWidget(t){this.dn(()=>{var e,n;this.an?null===(n=(e=this.an).registerWidget)||void 0===n||n.call(e,t):this.Ai(()=>{var e,n;null===(n=null===(e=this.an)||void 0===e?void 0:e.registerWidget)||void 0===n||n.call(e,t)})})}onMessage(t){return this.Bt.push(t),this.an?this.an.onMessage(t):()=>{var e=this.Bt.indexOf(t);e>-1&&this.Bt.splice(e,1)}}onTyping(t){return this.Nt.push(t),this.an?this.an.onTyping(t):()=>{var e=this.Nt.indexOf(t);e>-1&&this.Nt.splice(e,1)}}onConnectionChange(t){return this.Lt.push(t),this.an?this.an.onConnectionChange(t):()=>{var e=this.Lt.indexOf(t);e>-1&&this.Lt.splice(e,1)}}ki(){var t;return!0===(null===(t=this.getMergedConfig().bubble)||void 0===t?void 0:t.draggable)}getMergedConfig(){var t,e,n,i,r,s,o,a,l,u,h,d,c,v,f,p,g,m,b,y,w,x,_,k,S,C=this.ui,E=this.le;return{enabled:null!==(e=null!==(t=E.enabled)&&void 0!==t?t:null==C?void 0:C.enabled)&&void 0!==e&&e,autoConfig:null===(n=E.autoConfig)||void 0===n||n,position:null!==(r=null!==(i=E.position)&&void 0!==i?i:null==C?void 0:C.position)&&void 0!==r?r:"bottom-right",greeting:null!==(s=E.greeting)&&void 0!==s?s:null==C?void 0:C.greeting,color:null!==(a=null!==(o=E.color)&&void 0!==o?o:null==C?void 0:C.color)&&void 0!==a?a:"#6366f1",aiMode:null===(u=null!==(l=E.aiMode)&&void 0!==l?l:null==C?void 0:C.ai_enabled)||void 0===u||u,aiGreeting:null!==(h=E.aiGreeting)&&void 0!==h?h:null==C?void 0:C.ai_greeting,preload:null!==(d=E.preload)&&void 0!==d&&d,theme:null!==(c=E.theme)&&void 0!==c?c:{primaryColor:null!==(f=null!==(v=E.color)&&void 0!==v?v:null==C?void 0:C.color)&&void 0!==f?f:"#6366f1"},offlineMessage:null!==(p=E.offlineMessage)&&void 0!==p?p:null==C?void 0:C.offline_message,collectEmailOffline:null===(m=null!==(g=E.collectEmailOffline)&&void 0!==g?g:null==C?void 0:C.collect_email_offline)||void 0===m||m,bubble:{draggable:null!==(w=null!==(y=null===(b=E.bubble)||void 0===b?void 0:b.draggable)&&void 0!==y?y:null==C?void 0:C.bubble_draggable)&&void 0!==w&&w,visible:null===(k=null!==(_=null===(x=E.bubble)||void 0===x?void 0:x.visible)&&void 0!==_?_:null==C?void 0:C.bubble_visible)||void 0===k||k,offset:null===(S=E.bubble)||void 0===S?void 0:S.offset}}}Si(){var t,e,n=this.getMergedConfig(),i=null!==(t=n.position)&&void 0!==t?t:"bottom-right",r=kn(null===(e=n.bubble)||void 0===e?void 0:e.offset),s=document.getElementById("vtilt-chat-bubble");s&&Sn(s,i,r)}destroy(){I(()=>{var e,n,i;this.wi(),document.removeEventListener("visibilitychange",this.mi),null===(e=this.an)||void 0===e||e.destroy(),this.an=void 0,this.ae=!1,this.fi=[],this.pi=[],this.Bt=[],this.Nt=[],this.Lt=[],this.vn(),null===(n=this.ci)||void 0===n||n.destroy(),this.ci=null;var r=null===(i=null==t?void 0:t.document)||void 0===i?void 0:i.getElementById("vtilt-chat-bubble");r&&r.remove()})}Ci(){var t=this;return u(function*(){if(!t.hi){var e=t._instance.getConfig();if(!e.token)return T().warn(Ld,"cannot fetch settings: missing token"),void(t.hi=!0);try{var n=c(e,"/api/chat/settings"),i=yield fetch(n,{headers:v(e)});if(!i.ok)return T().warn(Ld,"failed to fetch settings: "+i.status),void(t.hi=!0);t.ui=yield i.json(),t.hi=!0,T().info(Ld,"loaded settings from dashboard")}catch(e){T().warn(Ld,"error fetching settings:",e),t.hi=!0}}})()}bi(){var t=this;return u(function*(){var e,n,i,r,s,o,a=t._instance.getConfig(),l=a.token,u=null!==(i=null===(n=(e=t._instance).getDistinctId)||void 0===n?void 0:n.call(e))&&void 0!==i?i:"";if(T().debug("chat","fetchUnread","distinctId",u?u.slice(0,12)+"...":"empty"),l&&u)try{var h=c(a,"/api/chat/widget/unread"),d=h.includes("?")?"&":"?",f=""+h+d+"distinct_id="+encodeURIComponent(u),p=yield fetch(f,{headers:v(a)});if(!p.ok)return;var g=yield p.json(),m=Number(null!==(r=g.unread_count)&&void 0!==r?r:0);null===(o=null===(s=t.an)||void 0===s?void 0:s.applyPolledUnreadCount)||void 0===o||o.call(s,m);var b=document.getElementById("vtilt-chat-bubble");if(!b)return;var y=b.querySelector(".vtilt-chat-bubble-badge");if(!y)return;m>0?(y.style.display="flex",y.textContent=m>99?"99+":String(m)):y.style.display="none"}catch(t){}else{var w=l?"missing distinctId":"missing token";T().debug("chat","fetchUnread skip","reason",w)}})()}Ti(){var e,n,i,r;if(null==t?void 0:t.document){var s=document.getElementById("vtilt-chat-bubble");if(s)return s.style.display="flex",void this.Si();var o=this.getMergedConfig(),a=null!==(e=o.position)&&void 0!==e?e:"bottom-right",l=kn(null===(n=o.bubble)||void 0===n?void 0:n.offset),u=o.color||"#6366f1",h=document.createElement("div");h.id="vtilt-chat-bubble",h.setAttribute("style",("\n position: fixed;\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: "+u+";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n transition: transform 0.2s, box-shadow 0.2s;\n z-index: 999999;\n ").trim()),Sn(h,a,l),h.innerHTML='\n <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">\n <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>\n </svg>\n <div class="vtilt-chat-bubble-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 ';var d=!0===(null===(i=o.bubble)||void 0===i?void 0:i.draggable);d||(h.addEventListener("mouseenter",()=>{h.style.transform="scale(1.05)",h.style.boxShadow="0 6px 16px rgba(0, 0, 0, 0.2)"}),h.addEventListener("mouseleave",()=>{h.style.transform="scale(1)",h.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.15)"})),h.addEventListener("click",()=>{this.open()}),document.body.appendChild(h),d&&(null===(r=this.ci)||void 0===r||r.destroy(),this.ci=In(h)),this.bi(),this.yi(),document.addEventListener("visibilitychange",this.mi)}}Ii(){return"undefined"!=typeof document&&("visible"===document.visibilityState&&(!!document.getElementById("vtilt-chat-bubble")||!(!this.an||this.an.isOpen)))}yi(){this.Ii()&&null===this.gi&&(this.gi=setInterval(()=>{this.bi()},3e4))}wi(){null!==this.gi&&(clearInterval(this.gi),this.gi=null)}Ei(){"undefined"!=typeof requestIdleCallback?requestIdleCallback(()=>this.ln(()=>{}),{timeout:5e3}):setTimeout(()=>this.ln(()=>{}),3e3)}Ai(t){this.an?t():(this.pi.push(t),this.ln(t=>this.hn(t)))}}function zd(t,e){t("js",new Date);var{tagIds:n,configParams:i,sendPageView:r,debugMode:s,conversionLinker:o,linkerDomains:a}=e,l=h({},i||{});for(var u of(!1===r&&(l.send_page_view=!1),s&&(l.debug_mode=!0),!1===o&&(l.conversion_linker=!1),a&&a.length>0&&(l.linker={domains:a,decorate_forms:!0}),n))u&&t("config",u,l)}function qd(e,n){var i,r=(e.tagIds||[]).filter(t=>!!t);if(0===r.length)return null;var s,o,a,l=null!==(i=e.proxyMode)&&void 0!==i?i:"proxied";if("direct"===l)s=Hd,o=Hd,a="";else{var u=function(e){var n,i=void 0!==t&&(null===(n=null==t?void 0:t.location)||void 0===n?void 0:n.origin)?t.location.origin:"";if(!e)return i?{base:i,absoluteBase:i}:null;var r=e.replace(/\/+$/g,"");if(!r)return i?{base:i,absoluteBase:i}:null;try{var s=new URL(r),o=s.pathname.replace(/\/$/,""),a=""+s.origin+o;return{base:a,absoluteBase:a}}catch(t){}if(r.startsWith("/"))return{base:r,absoluteBase:i?""+i+r:r};return i?{base:i,absoluteBase:i}:null}(n);if(!u)return null;s=u.base,o=u.absoluteBase,a=Fd}var h={};if("direct"!==l){var d=function(t){if(!t)return"";var e=t.startsWith("/")?t:"/"+t;return e.replace(/\/$/,"")}(a);h.transport_url=""+o.replace(/\/$/,"")+d}return{origin:s,gatewayPath:a,primaryTagId:r.find(t=>t.startsWith("G-"))||r[0]||"",tagIds:r,configParams:h,sendPageView:!1!==e.capturePageview,debugMode:!!e.debugMode,conversionLinker:!1!==e.conversionLinker,linkerDomains:e.linkerDomains}}var Fd="/gt",Hd="https://www.googletagmanager.com";function Wd(t,e){var n=!0===t.advertising,i={ad_storage:n?"granted":"denied",ad_user_data:n?"granted":"denied",ad_personalization:n?"granted":"denied",analytics_storage:!0===t.analytics?"granted":"denied"};if(!e)return i;var r=h({},i);return Object.keys(i).forEach(n=>{var i=e[n];void 0!==i&&(r[n]=function(t,e){return"granted"===e?"granted":"denied"===e?"denied":"follow_advertising"===e?!0===t.advertising?"granted":"denied":"follow_analytics"===e&&!0===t.analytics?"granted":"denied"}(t,i))}),r}function Jd(t){if(null==t)return null;var e=String(t).trim().toLowerCase();return e||null}function Vd(t,e){if(t&&e){var n=e.split("."),i=t;for(var r of n){if(null==i||"object"!=typeof i)return;i=i[r]}return i}}function Kd(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&""!==t.trim()){var e=Number(t);if(Number.isFinite(e))return e}}function Gd(t){if(null!=t)return"string"==typeof t?t:"number"==typeof t||"boolean"==typeof t?String(t):void 0}function Xd(t){var{mapping:e,payload:n}=t,i={send_to:e.send_to},r=e.value_param_path||"value",s=e.currency_param_path||"currency",o=Kd(Vd(n,r));void 0!==o&&(i.value=o);var a=Gd(Vd(n,s))||e.default_currency||void 0;if(a&&(i.currency=a),!1!==e.send_transaction_id){var l=Gd(Vd(n,e.transaction_id_param_path||"transaction_id"));l&&(i.transaction_id=l)}return{send_to:e.send_to,params:i}}var Qd=[{source:"$pageview",destination:"page_view",buildParams:t=>{var e,n={},i=Gd(t.$current_url);i&&(n.page_location=i);var r=Gd(t.$pathname);r&&(n.page_path=r);var s=null!==(e=Gd(t.title))&&void 0!==e?e:Gd(t.$title);s&&(n.page_title=s);var o=Gd(t.$referrer);return o&&(n.page_referrer=o),n}},{source:"$pageleave",destination:"user_engagement",buildParams:t=>{var e,n,i={},r=Kd(null!==(n=null!==(e=t.$dwell_time_ms)&&void 0!==e?e:t.engagement_time_msec)&&void 0!==n?n:t.$time_on_page_ms);return void 0!==r&&(i.engagement_time_msec=Math.round(r)),i}}];function Zd(t,e,n){var i=e.split(".").filter(Boolean);if(0!==i.length)if(1!==i.length){for(var r=t,s=0;s<i.length-1;s++){var o=i[s],a=i[s+1];if(null==r||"object"!=typeof r||Array.isArray(r))return;var l=r;if(/^\d+$/.test(a)){var u=Array.isArray(l[o])?l[o]:[];Array.isArray(l[o])||(l[o]=u);for(var h=parseInt(a,10);u.length<=h;)u.push({});if(s+1===i.length-1)return void(u[h]=n);var d=u[h];d&&"object"==typeof d&&!Array.isArray(d)||(d={},u[h]=d),r=d,s++}else{var c=l[o];c&&"object"==typeof c&&!Array.isArray(c)||(c={},l[o]=c),r=c}}var v=i[i.length-1];r&&"object"==typeof r&&!Array.isArray(r)&&(r[v]=n)}else t[i[0]]=n}var Yd=new Set(["client_id","user_id","first_visit","session_start"]);function tc(t,e,n,i){if(!function(t,e){return!(e&&(Array.isArray(e.exclude)&&e.exclude.includes(t)||Array.isArray(e.include)&&e.include.length>0&&!e.include.includes(t)))}(e,i.eventFilter))return{fired:!1};var r=(i.eventMappings||[]).find(t=>(null==t?void 0:t.source)===e);if(r&&r.destination){var{name:s,params:o}=function(t,e){var n={},i=Array.isArray(t.param_mappings)?t.param_mappings:[];for(var r of i){var s=null==r?void 0:r.source,o=null==r?void 0:r.destination;if(s&&o){var a=Vd(e,s);void 0!==a&&(o.includes(".")?Zd(n,o,a):n[o]=a)}}return{name:t.destination,params:n}}(r,n);return t("event",s,o),{fired:!0,eventName:s,params:o,source:"mapping"}}if(!1===i.autoForward)return{fired:!1};var a=Qd.find(t=>t.source===e);if(a){var l=a.buildParams(n);return t("event",a.destination,l),{fired:!0,eventName:a.destination,params:l,source:"preset"}}if(e.startsWith("$"))return{fired:!1};var u=function(t){var e={};for(var[n,i]of Object.entries(t))n.startsWith("$")||Yd.has(n)||void 0!==i&&(e[n]=i);return e}(n);return t("event",e,u),{fired:!0,eventName:e,params:u,source:"auto"}}function ec(){var t=null,e=[],n=[];return{call:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];if((t=>{n.push(t),n.length>50&&n.shift()})(r),t)try{t(...r)}catch(t){}else e.push(r)},flush(n){for(t=n;e.length;){var i=e.shift();try{n(...i)}catch(t){}}},getRecentCalls:()=>n.slice()}}function nc(t){return ic.apply(this,arguments)}function ic(){return ic=u(function*(t){try{var e="undefined"!=typeof crypto&&crypto.subtle?crypto.subtle:null;if(!e)return null;var n=(new TextEncoder).encode(t),i=yield e.digest("SHA-256",n),r=Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("");return r}catch(t){return null}}),ic.apply(this,arguments)}function rc(){return(rc=u(function*(t){var e={},n=function(t){if(!t)return null;var e=String(t).trim().toLowerCase();if(!e)return null;if(!e.includes("@"))return null;var[n,i]=e.split("@");if(!n||!i)return null;if("gmail.com"===i||"googlemail.com"===i){var r=n.split("+")[0].replace(/\./g,"");return r?r+"@"+i:null}return n+"@"+i}(t.email),i=function(t){if(!t)return null;var e=String(t).trim();if(!e)return null;if(e.startsWith("+")){var n=e.slice(1).replace(/\D/g,"");return n?"+"+n:null}return null}(t.phone),r=Jd(t.first_name),s=Jd(t.last_name),o=Jd(t.street),a=Jd(t.city),l=Jd(t.region),u=function(t){if(!t)return null;var e=String(t).trim().toUpperCase().replace(/\s+/g,"");return e||null}(t.postal_code),h=Jd(t.country);if(n){var d=yield nc(n);d&&(e.sha256_email_address=d)}if(i){var c=yield nc(i);c&&(e.sha256_phone_number=c)}var v={};if(r){var f=yield nc(r);f&&(v.sha256_first_name=f)}if(s){var p=yield nc(s);p&&(v.sha256_last_name=p)}if(o){var g=yield nc(o);g&&(v.sha256_street=g)}return a&&(v.city=a),l&&(v.region=l),u&&(v.postal_code=u),h&&(v.country=h),Object.keys(v).length>0&&(e.address=v),0===Object.keys(e).length?null:e})).apply(this,arguments)}class sc{constructor(t){void 0===t&&(t=Number.POSITIVE_INFINITY),this.Oi=t,this.Mi=[]}get length(){return this.Mi.length}enqueue(t){return!(this.Mi.length>=this.Oi)&&(this.Mi.push(t),!0)}takeAll(){if(0===this.Mi.length)return[];var t=this.Mi;return this.Mi=[],t}clear(){this.Mi=[]}}var oc="google-tag";class ac{constructor(t,e){this.name="GoogleTagGateway",this.tn=!1,this.Ri=!1,this.Pi=!1,this.Di=!1,this.Ui=null,this.ji=null,this.Bi=null,this.Ni=null,this.Li=[],this.$i=100,this.zi=new sc(100),this._instance=t,this.le=e||ac.extractConfig(t.getConfig()),this.qi=ec(),this.Fi()}static extractConfig(t){if(t.disable_google_tag)return{enabled:!1};var e=t.google_tag;return e?{enabled:(e.tagIds||[]).some(t=>!!t),remote:e}:{enabled:!1}}get isEnabled(){return!1!==this.le.enabled&&!!this.le.remote}get isStarted(){return this.tn}get gtag(){return this.qi.call}get deliveryLog(){return this.Li.slice()}startIfEnabled(){this.tn||this.isEnabled&&this._instance.getConfig().__remote_config_loaded&&this.Tn()}stop(){var t;this.tn&&(null===(t=this.Ni)||void 0===t||t.call(this),this.Ni=null,this.tn=!1)}onConfigUpdate(t){var e=ac.extractConfig(t),n=this.isEnabled;this.le=e;var i=!0===t.__remote_config_loaded;if(n&&!this.isEnabled)this.stop();else if(this.tn&&e.remote&&this.ji){var r=qd(e.remote,this._instance.getConfig().api_host);r&&(this.ji=r,zd(this.Ui,r))}i&&!this.isEnabled&&this.zi.clear(),i&&this.isEnabled&&!this.tn&&this.startIfEnabled()}setUserData(t){var e=this;return u(function*(){var n=e.le.remote;if(n&&n.enhancedConversions){var i=yield function(t){return rc.apply(this,arguments)}(t);i&&e.qi.call("set","user_data",i)}})()}getRecentPublicCalls(){return this.qi.getRecentCalls()}Tn(){var e=this.le.remote;if(e){var n=qd(e,this._instance.getConfig().api_host);if(n){this.ji=n;var{gtag:i}=function(){var t,e,n=a,i=null!==(t=(e=n).dataLayer)&&void 0!==t?t:e.dataLayer=[],r=n.gtag;if(r)return{gtag:r,dataLayer:i};var s=function(){i.push(arguments)};return n.gtag=s,{gtag:s,dataLayer:i}}();this.Ui=i,this.qi.flush(i),this.Hi(),zd(i,n),this.Ri||(this.Ri=!0,function(e,n,i){var r=null==t?void 0:t.document;if(!r)return null;var{origin:s,gatewayPath:o,primaryTagId:a}=e;if(!s||!a)return null;var l=""+s.replace(/\/$/,"")+(o?o.startsWith("/")?o.replace(/\/$/,""):"/"+o.replace(/\/$/,""):"")+"/gtag/js?id="+encodeURIComponent(a)+"&l=dataLayer",u=r.querySelector('script[data-vtilt-gtag-loader="'+a+'"]');if(u)return u;var h=r.createElement("script");h.async=!0,h.src=l,h.setAttribute("data-vtilt-gtag-loader",a),h.onload=()=>null==n?void 0:n(),h.onerror=()=>{var t=new Error("[GoogleTagGateway] failed to load "+l);null==i||i(t)},(r.head||r.body||r.documentElement).appendChild(h)}(n,()=>{this.Pi=!0},t=>{T().warn(oc,t.message)})),this.Wi(),this.tn=!0,this.Ji()}else T().warn(oc,"skipped — missing tag_ids or resolvable origin")}}Ji(){for(var t of this.zi.takeAll())this.Vi(t.event,t.payload)}Hi(){var t;if(!this.Di&&this.Ui){var e=I(()=>this._instance.consentManager.getConsent());!function(t,e,n){t("consent","default",h({},Wd(e,n),{wait_for_update:500}))}(this.Ui,e||{},null===(t=this.le.remote)||void 0===t?void 0:t.consentOverride),this.Di=!0}}Fi(){if(!this.Bi){this.Bi=this._instance._emitter.on(U,t=>{var e=t;e&&"string"==typeof e.event&&this.Vi(e.event,e.payload||{})})}}Vi(t,e){var n=this._instance.getConfig();if(!n.disable_google_tag)if(n.__remote_config_loaded){if(this.isEnabled&&(this.tn||this.startIfEnabled(),this.Ui&&this.le.remote&&this.tn)){var i=this.le.remote,r=i.tagIds||[],s=tc(this.Ui,t,e,i);if(s.fired&&s.eventName&&this.Ki({ts:Date.now(),tag_ids:r,event_name:t,send_to:"ga4:"+s.eventName,status:"fired",reason:s.source}),!1!==i.sendAdsConversions){var o=function(t,e,n,i){var r=(i.conversions||[]).filter(t=>t.event_name===e);if(0===r.length)return[];var s=[];for(var o of r){var a=Xd({mapping:o,payload:n});t("event","conversion",a.params),s.push(a)}return s}(this.Ui,t,e,i);for(var a of o)this.Ki({ts:Date.now(),tag_ids:r,event_name:t,send_to:a.send_to,status:"fired"})}}}else this.zi.enqueue({event:t,payload:e})}Wi(){if(!this.Ni){this.Ni=this._instance._emitter.on(D,t=>{var e;if(this.Ui){var n,i,r,s=t;n=this.Ui,i=s.consent||{},r=null===(e=this.le.remote)||void 0===e?void 0:e.consentOverride,n("consent","update",Wd(i,r))}})}}Ki(t){this.Li.push(t),this.Li.length>this.$i&&this.Li.shift()}}var lc="vtd-overlay";class uc{constructor(t,e){this.name="VtdOverlay",this.tn=!1,this.Gi=null,this.Xi=null,this.en=!0,this.Qi=null,this.Zi=null,this.Yi=null,this._instance=t,this.le=e||uc.extractConfig(t.getConfig())}static extractConfig(t){return{enabled:!1!==t.vtd_overlay}}get isEnabled(){return!1!==this.le.enabled}get isStarted(){return this.tn}startIfEnabled(){}stop(){this.tn&&I(()=>{this.tr(),this.tn=!1})}onConfigUpdate(t){this.le=uc.extractConfig(t),!this.isEnabled&&this.tn&&this.stop()}setDestinationUrl(e){var n;if(this.isEnabled)if(null==e?void 0:e.trim()){var i=e;try{i=decodeURIComponent(e)}catch(t){i=e}if(this.er(i)){var r=this.nr(i);this.Xi=i,this.Gi=r,this.en=!0,this.ir(),this.tn=!0,this._instance.capture("$vtd_view",{$vtd_url:i,$vtd_embed_url:r!==i?r:void 0,$current_url:null===(n=null==t?void 0:t.location)||void 0===n?void 0:n.href})}else T().warn(lc,"invalid URL: "+i)}else T().warn(lc,"empty URL provided");else T().warn(lc,"feature is disabled")}getDestinationUrl(){return this.Gi}close(){this._instance.capture("$vtd_close",{$vtd_url:this.Xi}),this.Qi?(this.Qi.classList.add("vtilt-vtd-closing"),setTimeout(()=>{this.tr(),this.tn=!1,this.Gi=null,this.Xi=null},200)):(this.tr(),this.tn=!1,this.Gi=null,this.Xi=null)}er(t){try{var e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol}catch(t){return!1}}nr(t){try{var e=new URL(t),n=e.hostname.toLowerCase();if("youtube.com"===n||"www.youtube.com"===n||"m.youtube.com"===n){var i=e.searchParams.get("v");if(i){var r=e.searchParams.get("t"),s="https://www.youtube.com/embed/"+i+"?autoplay=1";return r&&(s+="&start="+r.replace("s","")),s}}if("youtu.be"===n){var o=e.pathname.slice(1);if(o){var a=e.searchParams.get("t"),l="https://www.youtube.com/embed/"+o+"?autoplay=1";return a&&(l+="&start="+a.replace("s","")),l}}if("vimeo.com"===n||"www.vimeo.com"===n){var u=e.pathname.match(/^\/(\d+)/);if(u)return"https://player.vimeo.com/video/"+u[1]+"?autoplay=1"}if("loom.com"===n||"www.loom.com"===n){var h=e.pathname.match(/^\/share\/([a-zA-Z0-9]+)/);if(h)return"https://www.loom.com/embed/"+h[1]+"?autoplay=1"}if(n.endsWith("wistia.com")){var d=e.pathname.match(/^\/medias\/([a-zA-Z0-9]+)/);if(d)return"https://fast.wistia.net/embed/iframe/"+d[1]+"?autoplay=1"}if("dailymotion.com"===n||"www.dailymotion.com"===n){var c=e.pathname.match(/^\/video\/([a-zA-Z0-9]+)/);if(c)return"https://www.dailymotion.com/embed/video/"+c[1]+"?autoplay=1"}if("open.spotify.com"===n){var v=e.pathname.match(/^\/(track|album|playlist|episode|show)\/([a-zA-Z0-9]+)/);if(v)return"https://open.spotify.com/embed/"+v[1]+"/"+v[2]}return"drive.google.com"===n&&e.pathname.includes("/view")?t.replace("/view","/preview"):t}catch(e){return t}}rr(t){try{return new URL(t).hostname}catch(e){return t}}sr(t){try{return"https://www.google.com/s2/favicons?domain="+new URL(t).hostname+"&sz=32"}catch(t){return""}}ir(){if(i&&this.Gi){this.tr(),this.Qi=i.createElement("div"),this.Qi.id="vtilt-vtd-overlay",this.Qi.className="vtilt-vtd-opening",this.Qi.setAttribute("style",this.ar());var t=i.createElement("div");t.className="vtilt-vtd-modal",t.setAttribute("style",this.lr());var e=i.createElement("div");e.className="vtilt-vtd-header",e.setAttribute("style",this.ur()),e.innerHTML=this.hr(),t.appendChild(e);var n=i.createElement("div");n.className="vtilt-vtd-iframe-wrapper",n.setAttribute("style",this.dr()),this.Yi=i.createElement("div"),this.Yi.className="vtilt-vtd-loading",this.Yi.setAttribute("style",this.cr()),this.Yi.innerHTML=this.vr(),n.appendChild(this.Yi),this.Zi=i.createElement("iframe"),this.Zi.id="vtilt-vtd-iframe",this.Zi.className="vtilt-vtd-iframe",this.Zi.setAttribute("style",this.pr()),this.Zi.setAttribute("frameborder","0"),this.Zi.setAttribute("allowfullscreen","true"),this.Zi.setAttribute("allow","accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share");var r=()=>{this.en=!1,this.Yi&&(this.Yi.style.opacity="0",setTimeout(()=>{var t;(null===(t=this.Yi)||void 0===t?void 0:t.parentNode)&&(this.Yi.style.display="none")},300)),this.Zi&&(this.Zi.style.opacity="1")};this.Zi.onload=r,this.Zi.onerror=r,setTimeout(()=>{this.en&&r()},5e3),n.appendChild(this.Zi),this.Zi.src=this.Gi,t.appendChild(n),this.Qi.appendChild(t);var s=i.createElement("style");s.id="vtilt-vtd-styles",s.textContent=this.gr(),i.head.appendChild(s),i.body.appendChild(this.Qi),this.mr(),i.body.style.overflow="hidden"}}tr(){var t;(null===(t=this.Qi)||void 0===t?void 0:t.parentNode)&&(this.Qi.parentNode.removeChild(this.Qi),this.Qi=null,this.Zi=null,this.Yi=null);var e=null==i?void 0:i.getElementById("vtilt-vtd-styles");(null==e?void 0:e.parentNode)&&e.parentNode.removeChild(e),(null==i?void 0:i.body)&&(i.body.style.overflow="")}mr(){var e,n,r,s=null===(e=this.Qi)||void 0===e?void 0:e.querySelector(".vtilt-vtd-close");null==s||s.addEventListener("click",()=>this.close());var o=null===(n=this.Qi)||void 0===n?void 0:n.querySelector(".vtilt-vtd-open");null==o||o.addEventListener("click",()=>{this.Xi&&(null==t||t.open(this.Xi,"_blank"))}),null===(r=this.Qi)||void 0===r||r.addEventListener("click",t=>{t.target===this.Qi&&this.close()});var a=t=>{"Escape"===t.key&&(this.close(),null==i||i.removeEventListener("keydown",a))};null==i||i.addEventListener("keydown",a)}ar(){return'\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483647;\n background: rgba(0, 0, 0, 0.85);\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n '}lr(){return"\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n background: #0a0a0a;\n overflow: hidden;\n "}ur(){return"\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0 16px;\n height: 56px;\n background: linear-gradient(180deg, rgba(20, 20, 20, 1) 0%, rgba(15, 15, 15, 1) 100%);\n border-bottom: 1px solid rgba(255, 255, 255, 0.08);\n flex-shrink: 0;\n gap: 16px;\n "}hr(){var t=this.Xi||this.Gi,e=t?this.rr(t):"";return'\n <div style="display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0;">\n <img \n src="'+(t?this.sr(t):"")+'" \n alt="" \n style="width: 20px; height: 20px; border-radius: 4px; flex-shrink: 0;"\n onerror="this.style.display=\'none\'"\n />\n <div style="\n display: flex;\n flex-direction: column;\n min-width: 0;\n gap: 2px;\n ">\n <div style="\n color: rgba(255, 255, 255, 0.95);\n font-size: 14px;\n font-weight: 500;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n line-height: 1.2;\n ">'+this.br(e)+'</div>\n <div style="\n color: rgba(255, 255, 255, 0.45);\n font-size: 12px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n line-height: 1.2;\n ">'+this.br(this.yr(t||"",50))+'</div>\n </div>\n </div>\n <div style="display: flex; align-items: center; gap: 8px; flex-shrink: 0;">\n <button class="vtilt-vtd-open vtilt-vtd-btn" title="Open in new tab">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>\n <polyline points="15 3 21 3 21 9"></polyline>\n <line x1="10" y1="14" x2="21" y2="3"></line>\n </svg>\n <span class="vtilt-vtd-btn-text">Open</span>\n </button>\n <button class="vtilt-vtd-close vtilt-vtd-btn vtilt-vtd-btn-primary" title="Close (Esc)">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <line x1="18" y1="6" x2="6" y2="18"></line>\n <line x1="6" y1="6" x2="18" y2="18"></line>\n </svg>\n <span class="vtilt-vtd-btn-text">Close</span>\n </button>\n </div>\n '}dr(){return"\n flex: 1;\n position: relative;\n background: #000;\n overflow: hidden;\n "}cr(){return"\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background: #0a0a0a;\n z-index: 1;\n transition: opacity 0.3s ease;\n "}vr(){var t=this.Xi||this.Gi,e=t?this.rr(t):"";return'\n <div class="vtilt-vtd-spinner"></div>\n <div style="\n margin-top: 20px;\n color: rgba(255, 255, 255, 0.7);\n font-size: 14px;\n font-weight: 500;\n ">Loading '+this.br(e)+'...</div>\n <div style="\n margin-top: 8px;\n color: rgba(255, 255, 255, 0.35);\n font-size: 12px;\n ">Press <kbd style="\n display: inline-block;\n padding: 2px 6px;\n background: rgba(255, 255, 255, 0.1);\n border-radius: 4px;\n font-family: inherit;\n font-size: 11px;\n ">Esc</kbd> to close</div>\n '}pr(){return"\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: none;\n background: white;\n opacity: 0;\n transition: opacity 0.3s ease;\n "}gr(){return"\n /* Animations */\n @keyframes vtilt-vtd-fade-in {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes vtilt-vtd-fade-out {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n \n @keyframes vtilt-vtd-scale-in {\n from { opacity: 0; transform: scale(0.96); }\n to { opacity: 1; transform: scale(1); }\n }\n \n @keyframes vtilt-vtd-spin {\n to { transform: rotate(360deg); }\n }\n \n /* Container animations */\n #vtilt-vtd-overlay.vtilt-vtd-opening {\n animation: vtilt-vtd-fade-in 0.2s ease-out forwards;\n }\n \n #vtilt-vtd-overlay.vtilt-vtd-opening .vtilt-vtd-modal {\n animation: vtilt-vtd-scale-in 0.25s ease-out forwards;\n }\n \n #vtilt-vtd-overlay.vtilt-vtd-closing {\n animation: vtilt-vtd-fade-out 0.2s ease-in forwards;\n }\n \n /* Loading spinner */\n .vtilt-vtd-spinner {\n width: 40px;\n height: 40px;\n border: 3px solid rgba(255, 255, 255, 0.1);\n border-top-color: rgba(255, 255, 255, 0.8);\n border-radius: 50%;\n animation: vtilt-vtd-spin 0.8s linear infinite;\n }\n \n /* Button base styles */\n .vtilt-vtd-btn {\n background: rgba(255, 255, 255, 0.08);\n border: 1px solid rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.9);\n padding: 8px 14px;\n border-radius: 8px;\n cursor: pointer;\n font-size: 13px;\n font-weight: 500;\n display: flex;\n align-items: center;\n gap: 6px;\n transition: all 0.15s ease;\n -webkit-tap-highlight-color: transparent;\n outline: none;\n }\n \n .vtilt-vtd-btn:hover {\n background: rgba(255, 255, 255, 0.14);\n border-color: rgba(255, 255, 255, 0.18);\n }\n \n .vtilt-vtd-btn:active {\n background: rgba(255, 255, 255, 0.18);\n transform: scale(0.98);\n }\n \n .vtilt-vtd-btn:focus-visible {\n box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.3);\n }\n \n /* Primary button variant */\n .vtilt-vtd-btn-primary {\n background: rgba(255, 255, 255, 0.95);\n border-color: transparent;\n color: #0a0a0a;\n }\n \n .vtilt-vtd-btn-primary:hover {\n background: rgba(255, 255, 255, 1);\n border-color: transparent;\n }\n \n .vtilt-vtd-btn-primary:active {\n background: rgba(255, 255, 255, 0.85);\n }\n \n /* Desktop responsive - modal with margin */\n @media (min-width: 768px) {\n #vtilt-vtd-overlay {\n padding: 32px;\n }\n \n .vtilt-vtd-modal {\n max-width: 1200px;\n max-height: 90vh;\n width: 100%;\n height: auto;\n min-height: 500px;\n border-radius: 16px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.1);\n }\n \n .vtilt-vtd-header {\n border-radius: 16px 16px 0 0;\n }\n \n .vtilt-vtd-iframe-wrapper {\n border-radius: 0 0 16px 16px;\n min-height: 400px;\n }\n }\n \n /* Large desktop - bigger modal */\n @media (min-width: 1400px) {\n #vtilt-vtd-overlay {\n padding: 48px;\n }\n \n .vtilt-vtd-modal {\n max-width: 1400px;\n max-height: 85vh;\n }\n }\n \n /* Tablet */\n @media (min-width: 768px) and (max-width: 1024px) {\n #vtilt-vtd-overlay {\n padding: 24px;\n }\n \n .vtilt-vtd-modal {\n max-width: 95%;\n max-height: 90vh;\n }\n }\n \n /* Mobile - fullscreen */\n @media (max-width: 767px) {\n #vtilt-vtd-overlay {\n padding: 0 !important;\n background: #0a0a0a !important;\n }\n \n .vtilt-vtd-modal {\n width: 100% !important;\n height: 100% !important;\n max-width: none !important;\n max-height: none !important;\n border-radius: 0 !important;\n }\n \n .vtilt-vtd-header {\n border-radius: 0 !important;\n padding: 0 12px !important;\n height: 52px !important;\n }\n \n .vtilt-vtd-btn {\n padding: 8px 10px !important;\n }\n \n .vtilt-vtd-btn-text {\n display: none !important;\n }\n \n .vtilt-vtd-iframe-wrapper {\n border-radius: 0 !important;\n }\n }\n \n /* Reduced motion */\n @media (prefers-reduced-motion: reduce) {\n #vtilt-vtd-overlay,\n #vtilt-vtd-overlay *,\n .vtilt-vtd-spinner {\n animation-duration: 0.01ms !important;\n transition-duration: 0.01ms !important;\n }\n }\n "}yr(t,e){return t.length<=e?t:t.substring(0,e-3)+"..."}br(t){if(void 0===i)return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var e=i.createElement("div");return e.textContent=t,e.innerHTML}}var hc,dc="text/plain",cc=61440;!function(t){t.GZipJS="gzip-js",t.Base64="base64",t.None="none"}(hc||(hc={}));var vc=function(t,e){void 0===e&&(e="binary");var{data:n,compression:i}=t;if(n){var r=(t=>JSON.stringify(t,(t,e)=>"bigint"==typeof e?e.toString():e))(n),s=new Blob([r]).size;if(i===hc.GZipJS&&s>=1024)try{var o=jd(function(t,e){if(Bd)return Bd.encode(t);for(var n=t.length,i=new nd(t.length+(t.length>>1)),r=0,s=function(t){i[r++]=t},o=0;o<n;++o){if(r+5>i.length){var a=new nd(r+8+(n-o<<1));a.set(i),i=a}var l=t.charCodeAt(o);l<128||e?s(l):l<2048?(s(192|l>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&t.charCodeAt(++o))>>18),s(128|l>>12&63),s(128|l>>6&63),s(128|63&l)):(s(224|l>>12),s(128|l>>6&63),s(128|63&l))}return _d(i,0,r)}(r),{mtime:0});if("text-base64"===e){var a=function(t){if("undefined"==typeof btoa)throw new Error("btoa is not available in this environment");for(var e="",n=0;n<t.length;n+=32768){var i=Math.min(n+32768,t.length),r=t.subarray(n,i);e+=String.fromCharCode.apply(null,r)}return btoa(e)}(o);if(a.length>0&&a.length<.95*s)return{contentType:dc,body:a,estimatedSize:a.length,compressionApplied:hc.Base64}}else{var l=new Blob([o],{type:dc});if(l.size>0&&l.size<.95*s)return{contentType:dc,body:l,estimatedSize:l.size,compressionApplied:hc.GZipJS}}}catch(t){}return{contentType:"application/json",body:r,estimatedSize:s,compressionApplied:null}}};function fc(t,e){return e.compressionApplied?(n=t.url,i=e.compressionApplied,r=n.includes("?")?"&":"?",""+n+r+"compression="+i):t.url;var n,i,r}function pc(t,e){var n={};return e&&(n["Content-Type"]=e),t.headers&&Object.assign(n,t.headers),t.projectToken&&(n[d]=t.projectToken),n}var gc=[{name:"fetch",isAvailable:()=>"undefined"!=typeof fetch,method:t=>{var e=vc(t,"binary");if(e){var{contentType:n,body:i,estimatedSize:r}=e,s=fc(t,e),o=pc(t,n),a=new AbortController,l=t.timeout?setTimeout(()=>a.abort(),t.timeout):null;fetch(s,{method:t.method||"POST",headers:o,body:i,keepalive:r<cc,signal:a.signal}).then(function(){var e=u(function*(e){var n,i=yield e.text(),r={statusCode:e.status,text:i};if(200===e.status){F();try{r.json=JSON.parse(i)}catch(t){}}null===(n=t.callback)||void 0===n||n.call(t,r)});return function(t){return e.apply(this,arguments)}}()).catch(()=>{var e;q("capture"),null===(e=t.callback)||void 0===e||e.call(t,{statusCode:0})}).finally(()=>{l&&clearTimeout(l)})}}},{name:"XHR",isAvailable:()=>"undefined"!=typeof XMLHttpRequest,method:t=>{var e=vc(t,"binary");if(e){var{contentType:n,body:i}=e,r=fc(t,e),s=pc(t,n),o=new XMLHttpRequest;for(var[a,l]of(o.open(t.method||"POST",r,!0),Object.entries(s)))o.setRequestHeader(a,l);t.timeout&&(o.timeout=t.timeout),o.onreadystatechange=()=>{var e;if(4===o.readyState){var n={statusCode:o.status,text:o.responseText};if(200===o.status){F();try{n.json=JSON.parse(o.responseText)}catch(t){}}null===(e=t.callback)||void 0===e||e.call(t,n)}},o.onerror=()=>{var e;q("capture"),null===(e=t.callback)||void 0===e||e.call(t,{statusCode:0})},o.send(i)}}},{name:"sendBeacon",isAvailable:()=>"undefined"!=typeof navigator&&!!navigator.sendBeacon,method:t=>{var e=vc(t,"text-base64");if(e){var{contentType:n,body:i,estimatedSize:r}=e;if(0!==r){var s=fc(t,e),o=t.projectToken?function(t,e){if(!e||/[?&]token=/.test(t))return t;var n=t.includes("?")?"&":"?";return""+t+n+"token="+e}(s,t.projectToken):s;if(r<=cc)try{var a="string"==typeof i?new Blob([i],{type:n}):i;if("undefined"!=typeof navigator&&navigator.sendBeacon)if(navigator.sendBeacon(o,a))return}catch(t){}try{var l="string"==typeof i?new Blob([i],{type:n}):i,u=h({"Content-Type":n},t.headers||{});fetch(o,{method:t.method||"POST",headers:u,body:l,keepalive:r<cc}).catch(()=>{})}catch(t){}}}}}],mc=t=>{var e,n;if(H())null===(e=t.callback)||void 0===e||e.call(t,{statusCode:0});else{var i=t.transport||"fetch",r=gc.find(t=>t.name===i&&t.isAvailable())||gc.find(t=>t.isAvailable());if(!r)return T().error("request","no available transport method"),void(null===(n=t.callback)||void 0===n||n.call(t,{statusCode:0}));r.method(t)}};class bc{constructor(t,e){var n,i,r,s;this.wr=!0,this._r=[],this.kr=(n=(null==e?void 0:e.flush_interval_ms)||3e3,i=250,r=5e3,s=3e3,"number"!=typeof n||isNaN(n)?s:Math.min(Math.max(n,i),r)),this.Sr=t}get length(){return this._r.length}enqueue(t){this._r.push(t),this.Cr||this.Er()}unload(){if(this.Tr(),0!==this._r.length){var t=this.Ar();for(var e in t){var n=t[e];this.Sr(h({},n,{transport:"sendBeacon"}))}}}enable(){this.wr=!1,this.Er()}pause(){this.wr=!0,this.Tr()}flush(){this.Tr(),this.Ir(),this.Er()}Er(){this.wr||(this.Cr=setTimeout(()=>{this.Tr(),this.Ir(),this._r.length>0&&this.Er()},this.kr))}Tr(){this.Cr&&(clearTimeout(this.Cr),this.Cr=void 0)}Ir(){if(0!==this._r.length){var t=this.Ar(),e=Date.now();for(var n in t){var i=t[n];i.events.forEach(t=>{var n=new Date(t.timestamp).getTime();t.$offset=Math.abs(n-e)}),this.Sr(i)}}}Ar(){var t={};return this._r.forEach(e=>{var n=e.batchKey||e.url;t[n]||(t[n]={url:e.url,events:[],batchKey:e.batchKey}),t[n].events.push(e.event)}),this._r=[],t}}class yc{constructor(e){this.Or=!1,this.Mr=3e3,this._r=[],this.Rr=!0,this.Sr=e.sendRequest,this.Pr=e.sendBeacon,t&&void 0!==n&&"onLine"in n&&(this.Rr=n.onLine,G(t,"online",()=>{this.Rr=!0,this.bn()}),G(t,"offline",()=>{this.Rr=!1}))}get length(){return this._r.length}enqueue(t,e){if(void 0===e&&(e=0),e>=10)T().error("retry","request failed after 10 retries, giving up");else if(!H()){var n=function(t){var e=3e3*Math.pow(2,t),n=e/2,i=Math.min(18e5,e),r=(Math.random()-.5)*(i-n);return Math.ceil(i+r)}(e),i=Date.now()+n;this._r.push({retryAt:i,request:t,retriesPerformedSoFar:e+1});var r="enqueued failed request for retry in "+Math.round(n/1e3)+"s";this.Rr||(r+=" (browser is offline)"),T().warn("retry",r),this.Or||(this.Or=!0,this.Dr())}}retriableRequest(t){var e=this;return u(function*(){try{var n=yield e.Sr(t);200!==n.statusCode&&(n.statusCode<400||n.statusCode>=500)&&e.enqueue(t,0)}catch(n){e.enqueue(t,0)}})()}Dr(){this.Ur&&clearTimeout(this.Ur),this.Ur=setTimeout(()=>{this.Rr&&this._r.length>0&&this.bn(),this._r.length>0?this.Dr():this.Or=!1},this.Mr)}bn(){var t=this,e=Date.now(),n=[],i=[];this._r.forEach(t=>{t.retryAt<e?i.push(t):n.push(t)}),this._r=n,i.forEach(function(){var e=u(function*(e){var{request:n,retriesPerformedSoFar:i}=e;try{var r=yield t.Sr(n);200!==r.statusCode&&(r.statusCode<400||r.statusCode>=500)&&t.enqueue(n,i)}catch(e){t.enqueue(n,i)}});return function(t){return e.apply(this,arguments)}}())}unload(){this.Ur&&(clearTimeout(this.Ur),this.Ur=void 0),this._r.forEach(t=>{var{request:e}=t;try{this.Pr(e)}catch(t){T().error("retry","failed to send beacon on unload",t)}}),this._r=[]}}var wc="vt_rate_limit";class xc{constructor(t){var e,n;void 0===t&&(t={}),this.lastEventRateLimited=!1,this.eventsPerSecond=null!==(e=t.eventsPerSecond)&&void 0!==e?e:10,this.eventsBurstLimit=Math.max(null!==(n=t.eventsBurstLimit)&&void 0!==n?n:10*this.eventsPerSecond,this.eventsPerSecond),this.persistence=t.persistence,this.captureWarning=t.captureWarning,this.lastEventRateLimited=this.checkRateLimit(!0).isRateLimited}checkRateLimit(t){var e,n,i,r;void 0===t&&(t=!1);var s=Date.now(),o=null!==(n=null===(e=this.persistence)||void 0===e?void 0:e.get(wc))&&void 0!==n?n:{tokens:this.eventsBurstLimit,last:s},a=(s-o.last)/1e3;o.tokens+=a*this.eventsPerSecond,o.last=s,o.tokens>this.eventsBurstLimit&&(o.tokens=this.eventsBurstLimit);var l=o.tokens<1;return l||t||(o.tokens=Math.max(0,o.tokens-1)),!l||this.lastEventRateLimited||t||null===(i=this.captureWarning)||void 0===i||i.call(this,"vTilt client rate limited. Config: "+this.eventsPerSecond+" events/second, "+this.eventsBurstLimit+" burst limit."),this.lastEventRateLimited=l,null===(r=this.persistence)||void 0===r||r.set(wc,o),{isRateLimited:l,remainingTokens:o.tokens}}shouldAllowEvent(){return!this.checkRateLimit(!1).isRateLimited}getRemainingTokens(){return this.checkRateLimit(!0).remainingTokens}}class _c{constructor(t){this.jr=null,this.Br=null,this.Nr=t}get config(){return this.jr}onApply(t){this.Lr=t}onLoad(t){this.$r=t}load(){var e,n=this.Nr.getConfig();if(n.token){if(this.Br||(this.Br=h({},n)),null===(e=n.bootstrap)||void 0===e?void 0:e.remoteConfig)return this.jr=n.bootstrap.remoteConfig,this.zr(this.jr),void this.qr();var i=I(()=>t.__VTILT_BOOTSTRAP__);if(null==i?void 0:i.remoteConfig)return this.jr=i.remoteConfig,this.zr(this.jr),void this.qr();I(()=>{var t=localStorage.getItem(Qa+"_"+n.token);t&&(this.jr=JSON.parse(t),this.zr(this.jr,!0))}),this.qr()}}qr(){var t=this.Nr.getConfig();if(t.token)if(H())this.Nr.updateConfig({__remote_config_loaded:!0});else{var e=this.Nr.buildEndpointUrl("/api/d"),n=new AbortController,i=setTimeout(()=>n.abort(),3e3);(s||fetch)(e,{method:"GET",signal:n.signal,headers:h({Accept:"application/json"},v(t))}).then(t=>t.json()).then(e=>{var n;clearTimeout(i),F(),this.jr=e,I(()=>{localStorage.setItem(Qa+"_"+t.token,JSON.stringify(e))}),this.zr(e),null===(n=this.$r)||void 0===n||n.call(this,e)}).catch(()=>{clearTimeout(i),q("config"),this.Nr.updateConfig({__remote_config_loaded:!0})})}}zr(t,e){var n,i,r,s;void 0===e&&(e=!1);var o=this.Br||this.Nr.getConfig(),a={};for(var[,l]of this.Nr.featureManager.getDescriptors())if(l.remoteConfig&&l.configKey){var u=t[l.remoteConfig.key];u&&void 0===o[l.configKey]&&(a[l.configKey]=l.remoteConfig.map(u))}if(t.analytics&&!e&&(void 0!==t.analytics.capturePageview&&void 0===o.capture_pageview&&(a.capture_pageview=t.analytics.capturePageview),void 0!==t.analytics.capturePageleave&&void 0===o.capture_pageleave&&(a.capture_pageleave=!!t.analytics.capturePageleave),void 0!==t.analytics.capturePerformance&&void 0===o.capture_performance&&(a.capture_performance=t.analytics.capturePerformance),void 0===o.autocapture)){var d=t.analytics.autocapture,c=t.analytics.scrollDepthMilestones,v=t.analytics.scrollDepthPageleave;void 0!==d&&(a.autocapture=d&&(c||v)?{scroll_depth:h({},c?{milestones:!0}:{},v?{pageleave:!0}:{})}:d)}e||(a.__remote_config_loaded=!0),void 0!==(null===(n=t.privacy)||void 0===n?void 0:n.respectDnt)&&void 0===o.respect_dnt&&(a.respect_dnt=t.privacy.respectDnt),void 0!==(null===(i=t.privacy)||void 0===i?void 0:i.requireConsent)&&void 0===o.require_consent&&(a.require_consent=t.privacy.requireConsent),void 0!==t.autocapture_opt_out&&(a.autocapture_opt_out=t.autocapture_opt_out),void 0!==t.elementsChainAsString&&(a.elementsChainAsString=t.elementsChainAsString),(null===(r=t.diagnostics)||void 0===r?void 0:r.defaultLogLevel)&&T().setLevelFromRemote(t.diagnostics.defaultLogLevel),Object.keys(a).length>0&&this.Nr.updateConfig(a),null===(s=this.Lr)||void 0===s||s.call(this,t)}}var kc=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"];function Sc(t,e){if(void 0===e&&(e=[]),!t)return!1;var n=t.toLowerCase();return[...kc,...e].some(t=>-1!==n.indexOf(t.toLowerCase()))}function Cc(t,e){var n;if(void 0===e&&(e=[]),!t)return!1;var i=t.userAgent;if(i&&Sc(i,e))return!0;try{var r=t.userAgentData;if(null===(n=null==r?void 0:r.brands)||void 0===n?void 0:n.some(t=>Sc(null==t?void 0:t.brand,e)))return!0}catch(t){}return!!t.webdriver}var Ec=36e5;function Tc(){var e,n,i;return null!==(i=null===(n=null===(e=null==t?void 0:t.performance)||void 0===e?void 0:e.now)||void 0===n?void 0:n.call(e))&&void 0!==i?i:Date.now()}class Ac{constructor(){this.Fr=Tc(),this.Hr=null,this.Wr=Tc(),this.Jr="",this.Vr="",this.Kr="",this.Gr=""}onAfterPageview(){var t=Tc();this.Fr=t,this.Hr=t,this.Gr="",r&&(this.Jr=r.href||"",this.Vr=r.pathname||""),i&&(this.Kr=i.title||"")}peekEngagementSinceLastCaptureMs(){var t,e=Tc(),n=null!==(t=this.Hr)&&void 0!==t?t:this.Wr,i=Math.round(e-n);return i<1&&(i=1),i>Ec&&(i=Ec),i}commitCaptureClock(){this.Hr=Tc()}Xr(){return this.Jr+"\0"+this.Vr}clearLeaveDedupe(){this.Gr=""}tryCapturePageleave(t,e,n,i){if(function(t){var e=t.capture_pageleave;return!1!==e&&(!0===e||!1!==t.capture_pageview)}(t)){var r=this.Xr();if((this.Jr||this.Vr)&&r&&this.Gr!==r){this.Gr=r;var s=Tc(),o=Math.round(s-this.Fr);o<1&&(o=1),o>Ec&&(o=Ec);var a={navigation_type:n,engagement_time_msec:o,[gl]:this.Jr,[ml]:this.Vr,[bl]:Math.round(o/1e3),[yl]:this.Vr,[wl]:this.Jr},l=this.Jr?function(t){try{return new URL(t).host}catch(t){return""}}(this.Jr):"";l&&(a.$host=l),this.Kr&&(a.title=this.Kr),i&&Object.assign(a,i),e(ol,a,{skip_engagement:!0})}}}}var Ic=[al,ll,ul,ol,vl,fl,hl,pl],Oc=new Set([al,ll,ul]),Mc=new Set([ol,pl,vl,fl,hl]);class Rc{constructor(t){this.Qr=!1,this.Zr=!1,this.Yr=null,this.es=null,this.ns=new Ac,this.Nr=t}setVtPersonId(t){this.es=t}capture(t,e,i){var r,s,o;this.Nr.sessionManager.setSessionId();var a=this.Nr.getConfig();if(a.opt_out_useragent_filter||!Cc(n,null!==(r=a.custom_blocked_useragents)&&void 0!==r?r:[]))if((null==n?void 0:n.userAgent)&&function(t){return!(t&&"string"==typeof t&&t.length>500)}(n.userAgent))if((null==i?void 0:i.skip_client_rate_limiting)||Ic.includes(t)||this.Nr.rateLimiter.shouldAllowEvent())if(!this.Nr.getConfig().require_consent||Oc.has(t)||(null===(s=this.Nr.consentManager)||void 0===s?void 0:s.hasConsent())){var l=this.Nr.buildUrl(),u=!0===(null==i?void 0:i.skip_engagement)||Mc.has(t),d=h({},e);u||"number"==typeof d.engagement_time_msec||(d=h({},d,{engagement_time_msec:this.ns.peekEngagementSinceLastCaptureMs()}));var c=h({},this.rs(t,d),a.globalAttributes),v=JSON.stringify(c);if(!(f=v)||"string"!=typeof f||f.length<2||f.length>V)T().debug("capture","dropped",t,{reason:"payload_invalid_size",bytes:v.length,limitBytes:V,hint:t===dl?"Trim global / event properties; $elements is already off by default in compact mode.":"Trim event properties; payload exceeded the runaway-guard cap."});else{var f,p=t===al?this.Nr.userManager.getAnonymousId():null!==(o=this.Nr.userManager.getDistinctId())&&void 0!==o?o:this.Nr.userManager.getAnonymousId(),g={timestamp:(new Date).toISOString(),event:t,payload:c,distinct_id:p,anonymous_id:this.Nr.userManager.getAnonymousId()};this.Nr.bufferEvent(t,l,g),T().debug("capture","enqueued",t,h({distinct_id:p,$current_url:c.$current_url,$session_id:c.$session_id,$debug:c.$debug},t===dl&&"object"==typeof c&&null!==c?{$event_type:c.$event_type}:{})),this.es&&(this.es=null),t===sl?this.ns.onAfterPageview():this.ns.commitCaptureClock()}}else T().debug("capture","dropped",t,{reason:"require_consent_and_no_consent"});else T().debug("capture","dropped",t,{reason:"client_rate_limited",hint:"Token bucket (~10/s, burst ~100). $autocapture counts toward the same limit as custom events."});else T().debug("capture","dropped",t,{reason:"invalid_or_missing_user_agent"});else T().debug("capture","dropped",t,{reason:"bot"})}captureInternal(t,e){this.capture(t,e,{skip_client_rate_limiting:!0})}captureInitialPageview(){i&&("visible"===i.visibilityState?this.Zr||(this.Zr=!0,setTimeout(()=>{i&&r&&!1!==this.Nr.getConfig().capture_pageview&&this.capture(sl,{navigation_type:"initial_load"})},300),this.Yr&&(i.removeEventListener("visibilitychange",this.Yr),this.Yr=null)):this.Yr||(this.Yr=()=>this.captureInitialPageview(),G(i,"visibilitychange",this.Yr)))}tryCapturePageleave(t,e){this.ns.tryCapturePageleave(this.Nr.getConfig(),(t,e,n)=>this.capture(t,e,n),t,e)}resetPageleaveDedupe(){this.ns.clearLeaveDedupe()}ss(){if(this.Nr.getConfig().debug)return!0;try{if(null==r?void 0:r.search)if("1"===new URLSearchParams(r.search).get("vtilt_debug"))return!0}catch(t){}return!1}rs(t,e){var n,r,s=this.Nr.getConfig(),o=s.mask_personal_data_properties,a=s.custom_personal_data_properties,l=Yu(o,a),u=Z(function(t,e,n){if(!i)return{};var r=e?Q([],qu,n||[]):[];return X({},Wu(jl(i.URL,r,Hu)))}(0,o,a)),d=this.Nr.userManager.getUserProperties(),c=this.Nr.userManager.get_initial_props(),v=this.Nr.sessionManager.getSessionId(),f=this.Nr.sessionManager.getWindowId(),p={};!this.Qr&&Object.keys(c).length>0&&Object.assign(p,c),e.$set_once&&Object.assign(p,e.$set_once);var g=h({},l,u,d,null!==(r=null===(n=this.Nr.consentManager)||void 0===n?void 0:n.getConsentProperties())&&void 0!==r?r:{},{$session_id:v,$window_id:f},this.es?{$vt:this.es}:{},Object.keys(p).length>0?{$set_once:p}:{},e.$set?{$set:e.$set}:{},e);!this.Qr&&Object.keys(c).length>0&&(this.Qr=!0),t===sl&&i&&(g.title=i.title),this.ss()&&(g.$debug=!0);var m=this.Nr.sessionManager.consumeSessionStart(),b=this.Nr.userManager.consumeFirstVisit();return m&&(g.$session_start=!0),b&&(g.$first_visit=!0),g}}var Pc=["null","undefined","false","true","anonymous","anon","user","test","guest","visitor","unknown","none","demo","example","sample","placeholder"];function Dc(t){return!(!t||"string"!=typeof t)&&Pc.includes(t.toLowerCase().trim())}class Uc{constructor(t){this.ls=null,this.us=null,this.Nr=t}identify(t,e,n){var i;if("number"==typeof t&&(t=String(t),T().warn("identify","first argument should be a string, not a number")),t)if(Dc(t))T().error("identify",'"'+t+'" appears to be a hardcoded string');else if("COOKIELESS_SENTINEL_VALUE"!==t){var r=JSON.stringify([t,e,n]);if(this.ls!==r){var s=this.Nr.userManager,o=s.getDistinctId(),a=s.getAnonymousId(),l=s.getDeviceId();if(!("identified"===s.getUserState())&&a!==t||t!==o){this.Nr.capture(al,{distinct_id:t,$set:e||{},$set_once:n||{}});var u={user_state:"identified",distinct_id:t,properties_set:e,properties_set_once:n};if(!l){var d=o||a;u.device_id=d,u.properties_set=h({$had_persisted_distinct_id:!0,$device_id:d},u.properties_set||{})}s.applyUpdate(u),null===(i=this.Nr._emitter)||void 0===i||i.emit("user:identified",{distinctId:t})}else(e||n)&&this.setUserProperties(e,n);this.ls=r}}else T().error("identify","cannot use sentinel value as distinct_id");else T().error("identify","unique user id is required")}setUserProperties(t,e){var n,i;if(t||e){var r=this.Nr.userManager,s=JSON.stringify([null!==(n=r.getDistinctId())&&void 0!==n?n:r.getAnonymousId(),t,e]);this.us!==s&&(r.applyUpdate({properties_set:t,properties_set_once:e}),this.Nr.capture(ul,{$set:t||{},$set_once:e||{}}),null===(i=this.Nr._emitter)||void 0===i||i.emit("user:properties_set",{properties:t}),this.us=s)}}resetUser(t){var e;this.Nr.sessionManager.resetSessionId(),this.Nr.userManager.reset(t),this.ls=null,this.us=null,null===(e=this.Nr._emitter)||void 0===e||e.emit("user:reset")}alias(t,e){var n;if(t&&!Dc(t)){var i=this.Nr.userManager,r=null!==(n=null!=e?e:i.getDistinctId())&&void 0!==n?n:i.getAnonymousId();r&&!Dc(r)?t!==r?this.Nr.capture(ll,{$original_id:r,$alias_id:t}):this.identify(t):T().warn("alias","invalid original distinct ID")}else T().warn("alias","invalid alias")}getUserIdentity(){return this.Nr.userManager.getUserIdentity()}getDeviceId(){return this.Nr.userManager.getDeviceId()}getUserState(){return this.Nr.userManager.getUserState()}getDistinctId(){var t;return null!==(t=this.Nr.userManager.getDistinctId())&&void 0!==t?t:this.Nr.userManager.getAnonymousId()}getAnonymousId(){return this.Nr.userManager.getAnonymousId()}}var jc="_vtilt_consent";class Bc{constructor(t){this.hs={},this.ds=!1,this.Nr=t,this.cs()}setConsent(t){var e;this.hs=h({},this.hs,t),this.ds=!0,this.vs(),null===(e=this.Nr._emitter)||void 0===e||e.emit("consent:updated",{consent:this.hs})}getConsent(){return h({},this.hs)}hasConsent(){return this.ds}setDefaultGranted(){this.ds||(this.hs={analytics:!0,marketing:!0,advertising:!0},this.ds=!0)}getConsentProperties(){var t={};return void 0!==this.hs.analytics&&(t.$consent_analytics=this.hs.analytics),void 0!==this.hs.marketing&&(t.$consent_marketing=this.hs.marketing),void 0!==this.hs.advertising&&(t.$consent_advertising=this.hs.advertising),t}reset(){this.hs={},this.ds=!1,this.fs()}cs(){if(void 0!==i&&(null==i?void 0:i.cookie)){var t=jc+"=";for(var e of i.cookie.split(";")){var n=e.trim();if(n.startsWith(t)){try{var r=decodeURIComponent(n.slice(15)),s=JSON.parse(r);s&&"object"==typeof s&&(this.hs=s,this.ds=!0)}catch(t){}return}}}}vs(){if(void 0!==i){var t=encodeURIComponent(JSON.stringify(this.hs)),e="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";i.cookie=jc+"="+t+"; Max-Age=31536000; path=/; SameSite=Lax"+e}}fs(){void 0!==i&&(i.cookie=jc+"=; Max-Age=0; path=/")}}class Nc{constructor(t){this.ps=new Map,this.gs=new Map,this.Nr=t}register(t){this.ps.set(t.name,t)}createInstances(){var t=this,e=this.Nr.getConfig(),n=function(n,i){return t.gs.has(n)||t.bs(e,i)?0:void I(()=>{var r=i.FeatureClass.extractConfig(e),s=new i.FeatureClass(t.Nr,r);t.gs.set(n,s)})};for(var[i,r]of this.ps)n(i,r)}initAll(){this.createInstances();var t=function(t){I(()=>{t.isStarted||t.startIfEnabled()})};for(var[,e]of this.gs)t(e)}notifyAll(t){var e=function(e){e.onConfigUpdate&&I(()=>e.onConfigUpdate(t))};for(var[,n]of this.gs)e(n)}get(t){return this.gs.get(t)}set(t,e){this.gs.set(t,e)}getDescriptors(){return this.ps}bs(t,e){if(e.disableKey&&!0===t[e.disableKey])return!0;if(e.configKey){var n=t[e.configKey];if(n&&"object"==typeof n&&!1===n.enabled)return!0}return!1}}class Lc{constructor(t){this._r=new sc,this.ys=!1,this.ws=!1,this.Nr=t,this.xs(),this.ys||(this._s=setTimeout(()=>this.forceFlush(),5e3))}push(t){this.ys?this.ks(t):this._r.enqueue(t)}markConfigReady(){this.ws||(this.ws=!0,this.Ss())}forceFlush(){this.Cs(),this.bn(),this.ys=!0}xs(){this.ys=this.ws}Ss(){this.xs(),this.ys&&(this.Cs(),this.bn())}bn(){var t=this._r.takeAll();for(var e of t)this.ks(e);t.length>0&&this.Nr.requestQueue.flush()}ks(t){if(this.ws){if(this.Es(t.name))return}else this.Ts(t.event);this.Nr.sendRequest(t.url,t.event)}Es(t){var e=this.Nr.getConfig();switch(t){case sl:return!1===e.capture_pageview;case ol:return!1===e.capture_pageleave;case hl:return!1===e.capture_performance;case dl:case cl:return!1===e.autocapture;default:return!1}}Ts(t){"object"==typeof t.payload&&null!==t.payload&&(t.payload.$config_pending=!0)}Cs(){void 0!==this._s&&(clearTimeout(this._s),this._s=void 0)}}var $c="vt";class zc{constructor(t){void 0===t&&(t={}),this.version=Ha,this.__loaded=!1,this.As=!1,this.Is=!1,this.Os=[],this.Ms=!1,T().debug("ctor","start"),this._emitter=new O,this.configManager=new Cl(t);var e=this.configManager.getConfig();A(e),this.sessionManager=new Ml(e.storage||"cookie",e.cross_subdomain_cookie),this.userManager=new th(e.persistence||"localStorage+cookie",e.cross_subdomain_cookie),this.rateLimiter=new xc({eventsPerSecond:10,eventsBurstLimit:100,captureWarning:t=>{this.Rs.captureInternal(pl,{$$client_ingestion_warning_message:t})}}),this.retryQueue=new yc({sendRequest:t=>this.Ps(t),sendBeacon:t=>this.Ds(t)}),this.requestQueue=new bc(t=>this.Us(t),{flush_interval_ms:3e3}),this.consentManager=new Bc(this),this.Rs=new Rc(this),this.js=new Uc(this),this.Bs=new Nc(this),this.Ns=new _c(this),this.Ls(),this.Ns.onLoad(t=>{this._emitter.emit(P,{config:t})}),this.$s(),T().debug("ctor","boot gate installed")}Ls(){this.Bs.register({name:"HistoryAutocapture",configKey:"capture_pageview",FeatureClass:lh}),this.Bs.register({name:"Autocapture",configKey:"autocapture",FeatureClass:Zh}),this.Bs.register({name:"WebVitals",configKey:"capture_performance",FeatureClass:oh}),this.Bs.register({name:"SessionRecording",configKey:"session_recording",disableKey:"disable_session_recording",remoteConfig:{key:"sessionRecording",map:t=>({enabled:t.enabled,sampleRate:t.sampleRate,minimumDurationMs:t.minimumDurationMs,fullSnapshotIntervalMs:t.fullSnapshotIntervalMs,maskAllInputs:t.maskAllInputs,captureConsole:t.captureConsole,captureCanvas:t.captureCanvas})},FeatureClass:td}),this.Bs.register({name:"Chat",configKey:"chat",disableKey:"disable_chat",remoteConfig:{key:"chat",map:t=>({enabled:t.enabled,position:t.widgetPosition,color:t.widgetColor})},FeatureClass:$d}),this.Bs.register({name:"GoogleTagGateway",configKey:"google_tag",disableKey:"disable_google_tag",remoteConfig:{key:"googleTag",map:t=>t},FeatureClass:ac})}$s(){var t=this,e=function(e){var n=t[e];t[e]=function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];if(t.Is)return n.apply(t,r);t.Os.push([e,...r])}};for(var n of zc.BOOT_GATED_METHODS)e(n)}zs(){if(!this.Is){for(var t of(this.Is=!0,T().debug("boot","start"),zc.BOOT_GATED_METHODS))delete this[t];T().debug("boot","gate removed"),this.__loaded&&!this.Ms?(T().debug("boot","running _runPostBootInit"),this.qs()):T().debug("boot","skipping _runPostBootInit","loaded?",this.__loaded,"postBootDone?",this.Ms),T().debug("boot","flush pendingCalls",this.Os.length),this._execute_array(this.Os),this.Os=[]}}init(t,e,n){var i;if(n&&n!==$c){var r=null!==(i=Hc[n])&&void 0!==i?i:new zc;return r._init(t,e,n),Hc[n]=r,Hc[$c][n]=r,r}return this._init(t,e,n)}_init(t,e,n){if(void 0===e&&(e={}),this.__loaded)return T().warn("init","already initialized; re-initializing is a no-op"),this;this.configManager.updateConfig(h({},e,{token:t||e.token,name:n}));var r=this.configManager.getConfig();return A(r),this.__loaded=!0,T().debug("init","start","token present?",!!r.token,"name",null!=n?n:"vt"),this.Bs.createInstances(),this.Is||void 0===i||"interactive"!==i.readyState&&"complete"!==i.readyState||(T().debug("init","self-boot?",i.readyState),this.zs()),this.Is&&!this.Ms&&this.qs(),T().debug("init","postBootInitDone",this.Ms),this}qs(){if(!this.Ms){this.Ms=!0,T().debug("postBoot","start");var t=this.configManager.getConfig();this.sessionManager=new Ml(t.storage||"cookie",t.cross_subdomain_cookie),this.sessionManager.hydrateFromStorage(),T().debug("postBoot","sessionManager hydrated");var e=t.persistence||"localStorage+cookie";this.userManager.updateStorageMethod(e,t.cross_subdomain_cookie),this.userManager.hydrateFromStorage(),T().debug("postBoot","userManager hydrated"),t.require_consent||this.consentManager.hasConsent()||this.consentManager.setDefaultGranted(),!0===this.consentManager.getConsent().advertising&&zl(),this._emitter.on("consent:updated",t=>{var e=t.consent;!0===e.advertising?zl():!1===e.advertising&&void 0!==i&&(i.cookie=Bl+"=; Max-Age=0; path=/",i.cookie=Nl+"=; Max-Age=0; path=/")}),this.Fs(),this.userManager.set_initial_person_info(t.mask_personal_data_properties,t.custom_personal_data_properties),this.Hs=new Lc({sendRequest:(t,e)=>this.sendRequest(t,e),requestQueue:this.requestQueue,getConfig:()=>this.configManager.getConfig()}),this.Bs.initAll(),T().debug("postBoot","features inited"),this.Ns.load(),this.Ws(),this.Js();var n=this.configManager.getConfig();!1!==n.capture_pageview&&this.Rs.captureInitialPageview(),this.Bs.notifyAll(n),this._emitter.emit(M,{config:n}),T().debug("postBoot","done"),T().info("init","SDK ready")}}startAutocapture(){var t=this.Bs.get("Autocapture");if(!t){var e=Zh.extractConfig(this.configManager.getConfig());t=new Zh(this,e),this.Bs.set("Autocapture",t)}t.updateConfig({enabled:!0})}stopAutocapture(){var t=this.Bs.get("Autocapture");t&&t.updateConfig({enabled:!1})}isAutocaptureActive(){var t,e;return null!==(e=null===(t=this.Bs.get("Autocapture"))||void 0===t?void 0:t.isStarted)&&void 0!==e&&e}getAutocaptureDiagnostics(){var t,e;return null!==(e=null===(t=this.Bs.get("Autocapture"))||void 0===t?void 0:t.getDiagnostics())&&void 0!==e?e:null}startSessionRecording(){var t=this.Bs.get("SessionRecording");t||(t=new td(this),this.Bs.set("SessionRecording",t)),t.updateConfig({enabled:!0}),t.startIfEnabledOrStop("recording_initialized"),this._emitter.emit(j)}stopSessionRecording(){var t;null===(t=this.Bs.get("SessionRecording"))||void 0===t||t.stop(),this._emitter.emit(B)}isRecordingActive(){var t;return"active"===(null===(t=this.Bs.get("SessionRecording"))||void 0===t?void 0:t.status)}getSessionRecordingId(){var t;return(null===(t=this.Bs.get("SessionRecording"))||void 0===t?void 0:t.sessionId)||null}openChat(){var t=this.Bs.get("Chat");t?t.open():T().warn("chat","openChat: feature not available")}closeChat(){var t=this.Bs.get("Chat");t?t.close():T().warn("chat","closeChat: feature not available")}toggleChat(){var t=this.Bs.get("Chat");t?t.toggle():T().warn("chat","toggleChat: feature not available")}showChat(){var t=this.Bs.get("Chat");t?t.show():T().warn("chat","showChat: feature not available")}hideChat(){var t=this.Bs.get("Chat");t?t.hide():T().warn("chat","hideChat: feature not available")}sendChatMessage(t,e){var n=this.Bs.get("Chat");return n?n.sendMessage(t,e):(T().warn("chat","sendChatMessage: feature not available"),Promise.resolve())}gtag(){for(var t=this.Bs.get("GoogleTagGateway"),e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];t?t.gtag(...n):this.Os.push(["gtag",...n])}setGoogleUserData(t){var e=this.Bs.get("GoogleTagGateway");return e?e.setUserData(t):Promise.resolve()}get featureManager(){return this.Bs}on(t,e){return this._emitter.on(t,e)}once(t,e){return this._emitter.once(t,e)}off(t){this._emitter.off(t)}_is_bot(){var t,e=this.getConfig();return!e.opt_out_useragent_filter&&Cc(n,null!==(t=e.custom_blocked_useragents)&&void 0!==t?t:[])}capture(t,e,n){this.Rs.capture(t,e,n),this._emitter.emit(U,{event:t,payload:e})}tryCapturePageleave(t){var e,n=null===(e=this.Bs.get("Autocapture"))||void 0===e?void 0:e.getMaxScrollDepthPctForPageleave(),i=null!=n?{[kl]:n}:void 0;this.Rs.tryCapturePageleave(t,i)}identify(t,e,n){this.js.identify(t,e,n)}setUserProperties(t,e){this.js.setUserProperties(t,e)}resetUser(t){this.js.resetUser(t)}alias(t,e){this.js.alias(t,e)}setConsent(t){this.consentManager.setConsent(t)}getConsent(){return this.consentManager.getConsent()}getUserIdentity(){return this.js.getUserIdentity()}getDeviceId(){return this.js.getDeviceId()}getUserState(){return this.js.getUserState()}getConfig(){return this.configManager.getConfig()}getRemoteConfig(){return this.Ns.config}getSessionId(){return this.sessionManager.getSessionId()}getDistinctId(){return this.js.getDistinctId()}getAnonymousId(){return this.js.getAnonymousId()}toString(){var t,e=null!==(t=this.configManager.getConfig().name)&&void 0!==t?t:$c;return e!==$c&&(e="vt."+e),e}updateConfig(t){var e,n=this.configManager.getConfig();this.configManager.updateConfig(t);var i=this.configManager.getConfig();!n.__remote_config_loaded&&i.__remote_config_loaded&&(null===(e=this.Hs)||void 0===e||e.markConfigReady()),this.Bs.notifyAll(i),this._emitter.emit(R,{config:i})}buildUrl(){return this.buildEndpointUrl("/api/e")}buildEndpointUrl(t){return c(this.configManager.getConfig(),t)}sendRequest(t,e){this.Vs()&&this.requestQueue.enqueue({url:t,event:e})}bufferEvent(t,e,n){t!==vl&&t!==fl?this.Hs.push({name:t,url:e,event:n}):this.sendRequest(e,n)}Vs(){return!!this.configManager.getConfig().token||(this.As||(T().warn("config","token is required for tracking"),this.As=!0),!1)}Us(t){"sendBeacon"!==t.transport?this.retryQueue.retriableRequest(t):this.Ds(t)}Ps(t){return new Promise(e=>{var{url:n,events:i}=t,r=this.configManager.getConfig(),s=1===i.length?i[0]:{events:i},o=r.disable_compression?hc.None:hc.GZipJS;mc({url:n,data:s,method:"POST",transport:"XHR",compression:o,projectToken:r.token,callback:t=>e({statusCode:t.statusCode})})})}Ds(t){var{url:e,events:n}=t,i=this.configManager.getConfig(),r=1===n.length?n[0]:{events:n},s=i.disable_compression?hc.None:hc.GZipJS;mc({url:e,data:r,method:"POST",transport:"sendBeacon",compression:s,projectToken:i.token})}Ks(t){this.sendRequest(t.url,t.event)}Ws(){if(t){var e=()=>{this.Hs.forceFlush(),this.requestQueue.unload(),this.retryQueue.unload()};G(t,"beforeunload",e),G(t,"pagehide",()=>{this.Rs.tryCapturePageleave("pagehide"),e()}),i&&G(i,"visibilitychange",()=>{i&&("hidden"===i.visibilityState?this.Rs.tryCapturePageleave("visibility_hidden"):"visible"===i.visibilityState&&this.Rs.resetPageleaveDedupe())})}}Js(){this.requestQueue.enable()}Fs(){I(()=>{var e,n;if(void 0!==r&&r.search){var i=new URL(r.href),s=i.searchParams.get("vt"),o=i.searchParams.get("vtd");if((null==s?void 0:s.trim())&&(this.Rs.setVtPersonId(s.trim()),i.searchParams.delete("vt")),(null==o?void 0:o.trim())&&(this.Gs(o.trim()),i.searchParams.delete("vtd")),(null==s?void 0:s.trim())||(null==o?void 0:o.trim())){var a=i.pathname+(i.search||"")+i.hash;null===(n=null===(e=null==t?void 0:t.history)||void 0===e?void 0:e.replaceState)||void 0===n||n.call(e,{},"",a)}}})}Gs(t){this.vtdOverlay||(this.vtdOverlay=new uc(this),this.vtdOverlay.setDestinationUrl(t))}_execute_array(t){m(t)&&t.forEach(t=>{if(t&&m(t)&&t.length>0){var e=t[0],n=t.slice(1);"function"==typeof this[e]&&I(()=>this[e](...n))}})}_dom_loaded(){this.Js()}}zc.BOOT_GATED_METHODS=["capture","identify","setUserProperties","resetUser","alias","setConsent","startAutocapture","stopAutocapture","startSessionRecording","stopSessionRecording","openChat","closeChat","toggleChat","showChat","hideChat","sendChatMessage"];var qc,Fc,Hc={};qc=Hc[$c]=new zc,(Fc=a.vt)&&K(Fc._i,function(t){if(t&&m(t)){var e=qc.init(t[0],t[1],t[2]),n=Fc[t[2]||"vt"]||Fc;e&&e._execute_array(n)}}),a.vt=qc,function(){function e(){if(!e.done){e.done=!0,T().debug("dom","handler fired");var t=Object.keys(Hc);T().debug("boot","instance count",t.length),K(Hc,(t,e)=>{T().debug("boot","instance",e),t.zs(),t._dom_loaded()})}}if(i&&"function"==typeof i.addEventListener)return T().debug("dom","readyState",i.readyState),void("complete"===i.readyState||"interactive"===i.readyState?(T().debug("dom","running handler sync"),e()):(T().debug("dom","registered DOMContentLoaded listener"),G(i,"DOMContentLoaded",e,{capture:!1})));t&&T().error("dom","browser doesn't support document.addEventListener")}()}();
|
|
2
|
+
//# sourceMappingURL=array.chat.js.map
|