From 9936f6355792ba0ed250fb1bb89f796f9155f447 Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Wed, 11 Nov 2026 17:26:28 -0400 Subject: [PATCH] tracking: add an option to stop sending events --- README.md | 1 + __tests__/hellotext_test.js | 12 ++++++++++++ dist/hellotext.js | 2 +- dist/webchat-emoji-en.js | 2 +- dist/webchat-emoji-es.js | 2 +- dist/webchat-emoji.js | 2 +- index.d.ts | 1 + lib/core/configuration.cjs | 2 ++ lib/core/configuration.js | 2 ++ lib/hellotext.cjs | 1 + lib/hellotext.js | 1 + src/core/configuration.js | 2 ++ src/hellotext.js | 2 ++ 13 files changed, 28 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a7d74ade..2e1d7b4a 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ Hellotext.initialize('HELLOTEXT_BUSINESS_ID', configurationOptions) | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------- | | session | A valid Hellotext session which was stored previously. When not set, Hellotext attempts to retrieve the stored value from `document.cookie` when available, otherwise it creates a new session. | String | null | | autoGenerateSession | Whether the library should automatically generate a session when no session is found in the query or the cookies | Boolean | true | +| tracking | Whether `Hellotext.track` sends events. Pass `false` when the visitor refused analytics: popups, webchat and forms keep working. | Boolean | true | | forms | An object that controls how Hellotext should control the forms on the page. See [Forms](/docs/forms.md) documentation for more information. | Object | { autoMount: true, successMessage: true } | | popup | Options for the dashboard popup, or `false` to disable automatic popup mounting. See [Popups](/docs/popups.md). | Object \| false | Dashboard popup when configured | | webchat | An object that overrides the dashboard webchat configuration, or `false` to disable automatic webchat mounting. See [Webchat](/docs/webchat.md). | Object \| false | Dashboard webchat when configured | diff --git a/__tests__/hellotext_test.js b/__tests__/hellotext_test.js index 14ce6a1c..af9a54a0 100644 --- a/__tests__/hellotext_test.js +++ b/__tests__/hellotext_test.js @@ -670,6 +670,18 @@ describe("when the class is initialized successfully", () => { expect(response.succeeded).toEqual(true) }); + it("sends nothing when the visitor refused tracking", async () => { + global.fetch = jest.fn() + Configuration.assign({ tracking: false }) + + try { + await expect(Hellotext.track("page.viewed")).resolves.toBeUndefined() + expect(global.fetch).not.toHaveBeenCalled() + } finally { + Configuration.assign({ tracking: true }) + } + }); + it("records supported popup activity only after the server accepts it", async () => { global.fetch = jest.fn().mockResolvedValue({ json: jest.fn().mockResolvedValue({received: "success"}), diff --git a/dist/hellotext.js b/dist/hellotext.js index d2fd2539..43f9e423 100644 --- a/dist/hellotext.js +++ b/dist/hellotext.js @@ -1,2 +1,2 @@ /*! For license information please see hellotext.js.LICENSE.txt */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hellotext=t():e.Hellotext=t()}(Object("undefined"!=typeof self?self:this),()=>(()=>{"use strict";var e={891(e,t,s){s.d(t,{lg:()=>G,xI:()=>ne});class i{constructor(e,t,s){this.eventTarget=e,this.eventName=t,this.eventOptions=s,this.unorderedBindings=new Set}connect(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)}disconnect(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)}bindingConnected(e){this.unorderedBindings.add(e)}bindingDisconnected(e){this.unorderedBindings.delete(e)}handleEvent(e){const t=function(e){if("immediatePropagationStopped"in e)return e;{const{stopImmediatePropagation:t}=e;return Object.assign(e,{immediatePropagationStopped:!1,stopImmediatePropagation(){this.immediatePropagationStopped=!0,t.call(this)}})}}(e);for(const e of this.bindings){if(t.immediatePropagationStopped)break;e.handleEvent(t)}}hasBindings(){return this.unorderedBindings.size>0}get bindings(){return Array.from(this.unorderedBindings).sort((e,t)=>{const s=e.index,i=t.index;return si?1:0})}}class n{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach(e=>e.connect()))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach(e=>e.disconnect()))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce((e,t)=>e.concat(Array.from(t.values())),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,s={}){this.application.handleError(e,`Error ${t}`,s)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:s,eventOptions:i}=e,n=this.fetchEventListenerMapForEventTarget(t),r=this.cacheKey(s,i);n.delete(r),0==n.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:s,eventOptions:i}=e;return this.fetchEventListener(t,s,i)}fetchEventListener(e,t,s){const i=this.fetchEventListenerMapForEventTarget(e),n=this.cacheKey(t,s);let r=i.get(n);return r||(r=this.createEventListener(e,t,s),i.set(n,r)),r}createEventListener(e,t,s){const n=new i(e,t,s);return this.started&&n.connect(),n}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const s=[e];return Object.keys(t).sort().forEach(e=>{s.push(`${t[e]?"":"!"}${e}`)}),s.join(":")}}const r={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:s})=>!t||s===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function o(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function c(e){return o(e.replace(/--/g,"-").replace(/__/g,"_"))}function l(e){return e.charAt(0).toUpperCase()+e.slice(1)}function h(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function u(e){return null!=e}function d(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const p=["meta","ctrl","alt","shift"];class m{constructor(e,t,s,i){this.element=e,this.index=t,this.eventTarget=s.eventTarget||e,this.eventName=s.eventName||function(e){const t=e.tagName.toLowerCase();if(t in g)return g[t](e)}(e)||f("missing event name"),this.eventOptions=s.eventOptions||{},this.identifier=s.identifier||f("missing identifier"),this.methodName=s.methodName||f("missing method name"),this.keyFilter=s.keyFilter||"",this.schema=i}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let s=t[2],i=t[3];return i&&!["keydown","keyup","keypress"].includes(s)&&(s+=`.${i}`,i=""),{eventTarget:(n=t[4],"window"==n?window:"document"==n?document:void 0),eventName:s,eventOptions:t[7]?(r=t[7],r.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||i};var n,r}(e.content),t)}toString(){const e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;const t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;const s=t.filter(e=>!p.includes(e))[0];return!!s&&(d(this.keyMappings,s)||f(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[s].toLowerCase()!==e.key.toLowerCase())}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;const t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){const e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(const{name:s,value:i}of Array.from(this.element.attributes)){const n=s.match(t),r=n&&n[1];r&&(e[o(r)]=y(i))}return e}get eventTargetName(){return(e=this.eventTarget)==window?"window":e==document?"document":void 0;var e}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){const[s,i,n,r]=p.map(e=>t.includes(e));return e.metaKey!==s||e.ctrlKey!==i||e.altKey!==n||e.shiftKey!==r}}const g={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function f(e){throw new Error(e)}function y(e){try{return JSON.parse(e)}catch(t){return e}}class b{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){const t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){const e=this.controller[this.methodName];if("function"==typeof e)return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){const{element:t}=this.action,{actionDescriptorFilters:s}=this.context.application,{controller:i}=this.context;let n=!0;for(const[r,a]of Object.entries(this.eventOptions))if(r in s){const o=s[r];n=n&&o({name:r,value:a,event:e,element:t,controller:i})}return n}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:s}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:s,action:this.methodName})}catch(t){const{identifier:s,controller:i,element:n,index:r}=this,a={identifier:s,controller:i,element:n,index:r,event:e};this.context.handleError(t,`invoking action "${this.action}"`,a)}}willBeInvokedByEvent(e){const t=e.target;return!(e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e))&&!(e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e))&&(this.element===t||(t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element)))}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}}class v{constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver(e=>this.processMutations(e))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){const e=new Set(this.matchElementsInTree());for(const t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(const t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){"attributes"==e.type?this.processAttributeChange(e.target,e.attributeName):"childList"==e.type&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.processTree(e,this.removeElement)}}processAddedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.elementIsActive(e)&&this.processTree(e,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(const s of this.matchElementsInTree(e))t.call(this,s)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected==this.element.isConnected&&this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}}class w{constructor(e,t,s){this.attributeName=t,this.delegate=s,this.elementObserver=new v(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){const t=this.matchElement(e)?[e]:[],s=Array.from(e.querySelectorAll(this.selector));return t.concat(s)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}}function T(e,t){let s=e.get(t);return s||(s=new Set,e.set(t,s)),s}class S{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce((e,t)=>e.concat(Array.from(t)),[])}get size(){return Array.from(this.valuesByKey.values()).reduce((e,t)=>e+t.size,0)}add(e,t){!function(e,t,s){T(e,t).add(s)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,s){T(e,t).delete(s),function(e,t){const s=e.get(t);null!=s&&0==s.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const s=this.valuesByKey.get(e);return null!=s&&s.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some(t=>t.has(e))}getValuesForKey(e){const t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter(([t,s])=>s.has(e)).map(([e,t])=>e)}}class C{constructor(e,t,s,i){this._selector=t,this.details=i,this.elementObserver=new v(e,this),this.delegate=s,this.matchesByElement=new S}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){const{selector:t}=this;if(t){const s=e.matches(t);return this.delegate.selectorMatchElement?s&&this.delegate.selectorMatchElement(e,this.details):s}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const s=this.matchElement(e)?[e]:[],i=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return s.concat(i)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const s of t)this.selectorUnmatched(e,s)}elementAttributeChanged(e,t){const{selector:s}=this;if(s){const t=this.matchElement(e),i=this.matchesByElement.has(s,e);t&&!i?this.selectorMatched(e,s):!t&&i&&this.selectorUnmatched(e,s)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}}class A{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver(e=>this.processMutations(e))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(const e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){const t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){const s=this.delegate.getStringMapKeyForAttribute(e);if(null!=s){this.stringMap.has(e)||this.stringMapKeyAdded(s,e);const i=this.element.getAttribute(e);if(this.stringMap.get(e)!=i&&this.stringMapValueChanged(i,s,t),null==i){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(s,e,t)}else this.stringMap.set(e,i)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,s){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,s)}stringMapKeyRemoved(e,t,s){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,s)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map(e=>e.name)}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}}class E{constructor(e,t,s){this.attributeObserver=new w(e,t,this),this.delegate=s,this.tokensByElement=new S}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){const[t,s]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(s)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach(e=>this.tokenMatched(e))}tokensUnmatched(e){e.forEach(e=>this.tokenUnmatched(e))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){const t=this.tokensByElement.getValuesForKey(e),s=this.readTokensForElement(e),i=function(e,t){const s=Math.max(e.length,t.length);return Array.from({length:s},(s,i)=>[e[i],t[i]])}(t,s).findIndex(([e,t])=>{return i=t,!((s=e)&&i&&s.index==i.index&&s.content==i.content);var s,i});return-1==i?[[],[]]:[t.slice(i),s.slice(i)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,s){return e.trim().split(/\s+/).filter(e=>e.length).map((e,i)=>({element:t,attributeName:s,content:e,index:i}))}(e.getAttribute(t)||"",e,t)}}class O{constructor(e,t,s){this.tokenListObserver=new E(e,t,this),this.delegate=s,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){const{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).set(e,s),this.delegate.elementMatchedValue(t,s))}tokenUnmatched(e){const{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,s))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(e){return{error:e}}}}class x{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new O(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){const t=new b(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){const t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach(e=>this.delegate.bindingDisconnected(e,!0)),this.bindingsByAction.clear()}parseValueForToken(e){const t=m.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class k{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new A(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){const s=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,s.writer(this.receiver[e]),s.writer(s.defaultValue))}stringMapValueChanged(e,t,s){const i=this.valueDescriptorNameMap[t];null!==e&&(null===s&&(s=i.writer(i.defaultValue)),this.invokeChangedCallback(t,e,s))}stringMapKeyRemoved(e,t,s){const i=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,i.writer(this.receiver[e]),s):this.invokeChangedCallback(e,i.writer(i.defaultValue),s)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:s,writer:i}of this.valueDescriptors)null==s||this.controller.data.has(e)||this.invokeChangedCallback(t,i(s),void 0)}invokeChangedCallback(e,t,s){const i=`${e}Changed`,n=this.receiver[i];if("function"==typeof n){const i=this.valueDescriptorNameMap[e];try{const e=i.reader(t);let r=s;s&&(r=i.reader(s)),n.call(this.receiver,e,r)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${i.name}" - ${e.message}`),e}}}get valueDescriptors(){const{valueDescriptorMap:e}=this;return Object.keys(e).map(t=>e[t])}get valueDescriptorNameMap(){const e={};return Object.keys(this.valueDescriptorMap).forEach(t=>{const s=this.valueDescriptorMap[t];e[s.name]=s}),e}hasValue(e){const t=`has${l(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class M{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new S}start(){this.tokenListObserver||(this.tokenListObserver=new E(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var s;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(s=this.tokenListObserver)||void 0===s||s.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var s;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(s=this.tokenListObserver)||void 0===s||s.pause(()=>this.delegate.targetDisconnected(e,t)))}disconnectAllTargets(){for(const e of this.targetsByName.keys)for(const t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}}function I(e,t){const s=P(e);return Array.from(s.reduce((e,s)=>(function(e,t){const s=e[t];return Array.isArray(s)?s:[]}(s,t).forEach(t=>e.add(t)),e),new Set))}function P(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class L{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new S,this.outletElementsByName=new S,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach(e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)}),this.started=!0,this.dependentContexts.forEach(e=>e.refresh()))}refresh(){this.selectorObserverMap.forEach(e=>e.refresh()),this.attributeObserverMap.forEach(e=>e.refresh())}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach(e=>e.stop()),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach(e=>e.stop()),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:s}){const i=this.getOutlet(e,s);i&&this.connectOutlet(i,e,s)}selectorUnmatched(e,t,{outletName:s}){const i=this.getOutletFromMap(e,s);i&&this.disconnectOutlet(i,e,s)}selectorMatchElement(e,{outletName:t}){const s=this.selector(t),i=this.hasOutlet(e,t),n=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!s&&i&&n&&e.matches(s)}elementMatchedAttribute(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementAttributeValueChanged(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementUnmatchedAttribute(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}connectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)||(this.outletsByName.add(s,e),this.outletElementsByName.add(s,t),null===(i=this.selectorObserverMap.get(s))||void 0===i||i.pause(()=>this.delegate.outletConnected(e,t,s)))}disconnectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)&&(this.outletsByName.delete(s,e),this.outletElementsByName.delete(s,t),null===(i=this.selectorObserverMap.get(s))||void 0===i||i.pause(()=>this.delegate.outletDisconnected(e,t,s)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const s of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(s,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),s=new C(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,s),s.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),s=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,s),s.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find(t=>this.attributeNameForOutletName(t)===e)}get outletDependencies(){const e=new S;return this.router.modules.forEach(t=>{I(t.definition.controllerConstructor,"outlets").forEach(s=>e.add(s,t.identifier))}),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){const e=this.dependentControllerIdentifiers;return this.router.contexts.filter(t=>e.includes(t.identifier))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find(t=>t.element===e)}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}}class _{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:s,controller:i,element:n}=this;t=Object.assign({identifier:s,controller:i,element:n},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new x(this,this.dispatcher),this.valueObserver=new k(this,this.controller),this.targetObserver=new M(this,this),this.outletObserver=new L(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(e){this.handleError(e,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,s={}){const{identifier:i,controller:n,element:r}=this;s=Object.assign({identifier:i,controller:n,element:r},s),this.application.handleError(e,`Error ${t}`,s)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,s){this.invokeControllerMethod(`${c(s)}OutletConnected`,e,t)}outletDisconnected(e,t,s){this.invokeControllerMethod(`${c(s)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const s=this.controller;"function"==typeof s[e]&&s[e](...t)}}const N="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,D=(()=>{function e(e){function t(){return Reflect.construct(e,arguments,new.target)}return t.prototype=Object.create(e.prototype,{constructor:{value:t}}),Reflect.setPrototypeOf(t,e),t}try{return function(){const t=e(function(){this.a.call(this)});t.prototype.a=function(){},new t}(),e}catch(e){return e=>class extends e{}}})();class R{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const s=D(e),i=function(e,t){return N(t).reduce((s,i)=>{const n=function(e,t,s){const i=Object.getOwnPropertyDescriptor(e,s);if(!i||!("value"in i)){const e=Object.getOwnPropertyDescriptor(t,s).value;return i&&(e.get=i.get||e.get,e.set=i.set||e.set),e}}(e,t,i);return n&&Object.assign(s,{[i]:n}),s},{})}(e.prototype,t);return Object.defineProperties(s.prototype,i),s}(t,function(e){return I(e,"blessings").reduce((t,s)=>{const i=s(e);for(const e in i){const s=t[e]||{};t[e]=Object.assign(s,i[e])}return t},{})}(t)))};var t}(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){const t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){const t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new _(this,e),this.contextsByScope.set(e,t)),t}}class F{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){return(this.data.get(this.getDataKey(e))||"").match(/[^\s]+/g)||[]}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}}class ${constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){const t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){const s=this.getAttributeNameForKey(e);return this.element.setAttribute(s,t),this.get(e)}has(e){const t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){const t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${h(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,s){let i=this.warnedKeysByObject.get(e);i||(i=new Set,this.warnedKeysByObject.set(e,i)),i.has(t)||(i.add(t),this.logger.warn(s,e))}}function V(e,t){return`[${e}~="${t}"]`}class j{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce((e,t)=>e||this.findTarget(t)||this.findLegacyTarget(t),void 0)}findAll(...e){return e.reduce((e,t)=>[...e,...this.findAllTargets(t),...this.findAllLegacyTargets(t)],[])}findTarget(e){const t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){const t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){return V(this.schema.targetAttributeForScope(this.identifier),e)}findLegacyTarget(e){const t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){const t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map(t=>this.deprecate(t,e))}getLegacySelectorForTargetName(e){const t=`${this.identifier}.${e}`;return V(this.schema.targetAttribute,t)}deprecate(e,t){if(e){const{identifier:s}=this,i=this.schema.targetAttribute,n=this.schema.targetAttributeForScope(s);this.guide.warn(e,`target:${t}`,`Please replace ${i}="${s}.${t}" with ${n}="${t}". The ${i} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class q{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce((e,t)=>e||this.findOutlet(t),void 0)}findAll(...e){return e.reduce((e,t)=>[...e,...this.findAllOutlets(t)],[])}getSelectorForOutletName(e){const t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){const t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){const t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter(s=>this.matchesElement(s,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(s=>this.matchesElement(s,e,t))}matchesElement(e,t,s){const i=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&i.split(" ").includes(s)}}class U{constructor(e,t,s,i){this.targets=new j(this),this.classes=new F(this),this.data=new $(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=s,this.guide=new B(i),this.outlets=new q(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return V(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new U(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class z{constructor(e,t,s){this.element=e,this.schema=t,this.delegate=s,this.valueListObserver=new O(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){const{element:t,content:s}=e;return this.parseValueForElementAndIdentifier(t,s)}parseValueForElementAndIdentifier(e,t){const s=this.fetchScopesByIdentifierForElement(e);let i=s.get(t);return i||(i=this.delegate.createScopeForElementAndIdentifier(e,t),s.set(t,i)),i}elementMatchedValue(e,t){const s=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,s),1==s&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const s=this.scopeReferenceCounts.get(t);s&&(this.scopeReferenceCounts.set(t,s-1),1==s&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}}class W{constructor(e){this.application=e,this.scopeObserver=new z(this.element,this.schema,this),this.scopesByIdentifier=new S,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce((e,t)=>e.concat(t.contexts),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);const t=new R(this.application,e);this.connectModule(t);const s=e.controllerConstructor.afterLoad;s&&s.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const s=this.modulesByIdentifier.get(t);if(s)return s.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const s=this.scopeObserver.parseValueForElementAndIdentifier(e,t);s?this.scopeObserver.elementMatchedValue(s.element,s):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,s){this.application.handleError(e,t,s)}createScopeForElementAndIdentifier(e,t){return new U(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(t=>e.connectContextForScope(t))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(t=>e.disconnectContextForScope(t))}}const K={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:e=>`data-${e}-target`,outletAttributeForScope:(e,t)=>`data-${e}-${t}-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},H("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),H("0123456789".split("").map(e=>[e,e])))};function H(e){return e.reduce((e,[t,s])=>Object.assign(Object.assign({},e),{[t]:s}),{})}class G{constructor(e=document.documentElement,t=K){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,s={})=>{this.debug&&this.logFormattedMessage(e,t,s)},this.element=e,this.schema=t,this.dispatcher=new n(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},r)}static start(e,t){const s=new this(e,t);return s.start(),s}async start(){await new Promise(e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",()=>e()):e()}),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(e=>{e.controllerConstructor.shouldLoad&&this.router.loadDefinition(e)})}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(e=>this.router.unloadIdentifier(e))}get controllers(){return this.router.contexts.map(e=>e.controller)}getControllerForElementAndIdentifier(e,t){const s=this.router.getContextForElementAndIdentifier(e,t);return s?s.controller:null}handleError(e,t,s){var i;this.logger.error("%s\n\n%o\n\n%o",t,e,s),null===(i=window.onerror)||void 0===i||i.call(window,t,"",0,0,e)}logFormattedMessage(e,t,s={}){s=Object.assign({application:this},s),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},s)),this.logger.groupEnd()}}function J(e,t,s){return e.application.getControllerForElementAndIdentifier(t,s)}function Y(e,t,s){let i=J(e,t,s);return i||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,s),i=J(e,t,s),i||void 0)}function Z([e,t],s){return function(e){const{token:t,typeDefinition:s}=e,i=`${h(t)}-value`,n=function(e){const{controller:t,token:s,typeDefinition:i}=e,n=function(e){const{controller:t,token:s,typeObject:i}=e,n=u(i.type),r=u(i.default),a=n&&r,o=n&&!r,c=!n&&r,l=X(i.type),h=Q(e.typeObject.default);if(o)return l;if(c)return h;if(l!==h)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${s}`:s}" must match the defined type "${l}". The provided default value of "${i.default}" is of type "${h}".`);return a?l:void 0}({controller:t,token:s,typeObject:i}),r=Q(i),a=X(i),o=n||r||a;if(o)return o;throw new Error(`Unknown value type "${t?`${t}.${i}`:s}" for "${s}" value`)}(e);return{type:n,key:i,name:o(i),get defaultValue(){return function(e){const t=X(e);if(t)return ee[t];const s=d(e,"default"),i=d(e,"type"),n=e;if(s)return n.default;if(i){const{type:e}=n,t=X(e);if(t)return ee[t]}return e}(s)},get hasCustomDefaultValue(){return void 0!==Q(s)},reader:te[n],writer:se[n]||se.default}}({controller:s,token:e,typeDefinition:t})}function X(e){switch(e){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function Q(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}return Array.isArray(e)?"array":"[object Object]"===Object.prototype.toString.call(e)?"object":void 0}const ee={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},te={array(e){const t=JSON.parse(e);if(!Array.isArray(t))throw new TypeError(`expected value of type "array" but instead got value "${e}" of type "${Q(t)}"`);return t},boolean:e=>!("0"==e||"false"==String(e).toLowerCase()),number:e=>Number(e.replace(/_/g,"")),object(e){const t=JSON.parse(e);if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(`expected value of type "object" but instead got value "${e}" of type "${Q(t)}"`);return t},string:e=>e},se={default:function(e){return`${e}`},array:ie,object:ie};function ie(e){return JSON.stringify(e)}class ne{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:s={},prefix:i=this.identifier,bubbles:n=!0,cancelable:r=!0}={}){const a=new CustomEvent(i?`${i}:${e}`:e,{detail:s,bubbles:n,cancelable:r});return t.dispatchEvent(a),a}}ne.blessings=[function(e){return I(e,"classes").reduce((e,t)=>{return Object.assign(e,(s=t,{[`${s}Class`]:{get(){const{classes:e}=this;if(e.has(s))return e.get(s);{const t=e.getAttributeName(s);throw new Error(`Missing attribute "${t}"`)}}},[`${s}Classes`]:{get(){return this.classes.getAll(s)}},[`has${l(s)}Class`]:{get(){return this.classes.has(s)}}}));var s},{})},function(e){return I(e,"targets").reduce((e,t)=>{return Object.assign(e,(s=t,{[`${s}Target`]:{get(){const e=this.targets.find(s);if(e)return e;throw new Error(`Missing target element "${s}" for "${this.identifier}" controller`)}},[`${s}Targets`]:{get(){return this.targets.findAll(s)}},[`has${l(s)}Target`]:{get(){return this.targets.has(s)}}}));var s},{})},function(e){const t=function(e,t){return P(e).reduce((e,s)=>(e.push(...function(e,t){const s=e[t];return s?Object.keys(s).map(e=>[e,s[e]]):[]}(s,t)),e),[])}(e,"values"),s={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const s=Z(t,this.identifier),i=this.data.getAttributeNameForKey(s.key);return Object.assign(e,{[i]:s})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=Z(e,void 0),{key:s,name:i,reader:n,writer:r}=t;return{[i]:{get(){const e=this.data.get(s);return null!==e?n(e):t.defaultValue},set(e){void 0===e?this.data.delete(s):this.data.set(s,r(e))}},[`has${l(i)}`]:{get(){return this.data.has(s)||t.hasCustomDefaultValue}}}}(t)),s)},function(e){return I(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=c(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),s=this.outlets.getSelectorForOutletName(e);if(t){const s=Y(this,t,e);if(s)return s;throw new Error(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const s=Y(this,t,e);if(s)return s;console.warn(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`,t)}).filter(e=>e):[]}},[`${t}OutletElement`]:{get(){const t=this.outlets.find(e),s=this.outlets.getSelectorForOutletName(e);if(t)return t;throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${l(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ne.targets=[],ne.outlets=[],ne.values={}},396(e,t,s){s.d(t,{default:()=>Ui});var i=s(891);class n extends Error{constructor(e){super(`${e} is not valid. Please provide a valid event name`),this.name="InvalidEvent"}}class r{static events=["session-set","utm-set","forms:collected","form:completed","popup:mounted","popup:opened","popup:closed","alert:shown","alert:dismissed","alert:accepted","push:unsubscribed","activity:occurred","webchat:mounted","webchat:opened","webchat:closed","webchat:message:sent","webchat:message:received","cart.added"];static valid(e){return r.exists(e)}static invalid(e){return!this.valid(e)}static exists(e){return void 0!==this.events.find(t=>t===e)}constructor(){this.subscribers={}}addSubscriber(e,t){if(r.invalid(e))throw new n(e);this.subscribers={...this.subscribers,[e]:this.subscribers[e]?[...this.subscribers[e],t]:[t]}}removeSubscriber(e,t){if(r.invalid(e))throw new n(e);this.subscribers[e]&&(this.subscribers[e]=this.subscribers[e].filter(e=>e!==t))}dispatch(e,t){this.subscribers[e]?.forEach(e=>{e(t)})}get listeners(){return 0!==Object.keys(this.subscribers).length}}class a{static autoMount=!0;static successMessage=!0;static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}static get shouldShowSuccessMessage(){return this.successMessage}}class o{static _identifier;static set identifier(e){this._identifier=e}static get identifier(){return this._identifier?this._identifier:this.#e||this.#t||this.#s||"en"}static toString(){return this.identifier}static get#e(){return"undefined"!=typeof document?document.documentElement?.lang:void 0}static get#t(){return"undefined"!=typeof document?document.querySelector('meta[name="locale"]')?.content:void 0}static get#s(){return"undefined"!=typeof navigator?navigator.language?.split("-")[0]:void 0}}class c{static _id;static _container="body";static _device="auto";static set id(e){this._id=e}static get id(){return this._id}static set container(e){this._container=e}static get container(){return this._container}static set device(e){if(!["auto","mobile","desktop"].includes(e))throw new Error(`Invalid popup device value: ${e}`);this._device=e}static get device(){return this._device}static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}}const l={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"},h={ABSOLUTE:"absolute",FIXED:"fixed"},u={MODAL:"modal",POPOVER:"popover"};class d{static _id;static _container="body";static _placement="bottom-right";static _style={};static _appearance={};static _whatsapp={};static _mode=u.POPOVER;static _behaviour=null;static _hasBehaviourOverride=!1;static _strategy=null;static set container(e){this._container=e}static get container(){return this._container}static set placement(e){if(!Object.values(l).includes(e))throw new Error(`Invalid placement value: ${e}`);this._placement=e}static get placement(){return this._placement}static set id(e){this._id=e}static get id(){return this._id}static get isSet(){return!!this._id}static get style(){return this._style}static set style(e){if("object"!=typeof e)throw new Error("Style must be an object");Object.entries(e).forEach(([e,t])=>{if(!["primaryColor","secondaryColor","typography"].includes(e))throw new Error(`Invalid style property: ${e}`);if("typography"!==e&&!this.isHexOrRgba(t))throw new Error(`Invalid color value: ${t} for ${e}. Colors must be hex or rgb/a.`)}),this._style=e}static get appearance(){return this._appearance}static set appearance(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(([e,t])=>{if(!["header","launcher"].includes(e))throw new Error(`Invalid appearance property: ${e}`);if(!this.isPlainObject(t))throw new Error(`Appearance ${e} must be an object`);Object.entries(t).forEach(([t,s])=>{if("header"===e&&"name"!==t)throw new Error(`Invalid appearance header property: ${t}`);if("launcher"===e&&"iconUrl"!==t)throw new Error(`Invalid appearance launcher property: ${t}`);if(null!=s&&"string"!=typeof s)throw new Error(`Invalid appearance ${e}.${t} value: ${s}`)})}),this._appearance=e}static get whatsapp(){return this._whatsapp}static set whatsapp(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(([e,t])=>{if(!["number","restrictToChannel"].includes(e))throw new Error(`Invalid WhatsApp property: ${e}`);if(null!=t){if("number"===e&&"string"!=typeof t)throw new Error(`Invalid WhatsApp number value: ${t}`);if("restrictToChannel"===e&&"boolean"!=typeof t)throw new Error(`Invalid WhatsApp restrictToChannel value: ${t}`)}}),this._whatsapp=e}static get mode(){return this._mode}static set mode(e){if(!Object.values(u).includes(e))throw new Error(`Invalid mode value: ${e}`);this._mode=e}static get behaviour(){return this._behaviour}static set behaviour(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error(`Invalid behaviour value: ${e}`);this._behaviour=e}else this._behaviour=e}static get hasBehaviourOverride(){return this._hasBehaviourOverride}static set behaviourOverride(e){this._hasBehaviourOverride=!!e}static get strategy(){return this._strategy?this._strategy:"body"==this.container?h.FIXED:h.ABSOLUTE}static set strategy(e){if(e&&!Object.values(h).includes(e))throw new Error(`Invalid strategy value: ${e}`);this._strategy=e}static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}static isHexOrRgba(e){return/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(e)||/^rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3},?\s*(0|1|0?\.\d+)?\s*\)$/.test(e)}static isPlainObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}const p={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"};class m{static _id;static _container="body";static _placement="bottom-right";static _appearance={};static _number=null;static _body=null;static set id(e){this._id=e}static get id(){return this._id}static set container(e){this._container=e}static get container(){return this._container}static set placement(e){if(!Object.values(p).includes(e))throw new Error(`Invalid placement value: ${e}`);this._placement=e}static get placement(){return this._placement}static get appearance(){return this._appearance}static set appearance(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(([e,t])=>{if("launcher"!==e)throw new Error(`Invalid appearance property: ${e}`);if(!this.isPlainObject(t))throw new Error(`Appearance ${e} must be an object`);Object.entries(t).forEach(([t,s])=>{if("iconUrl"!==t)throw new Error(`Invalid appearance launcher property: ${t}`);if(null!=s&&"string"!=typeof s)throw new Error(`Invalid appearance ${e}.${t} value: ${s}`)})}),this._appearance=e}static get number(){return this._number}static set number(e){if(null!=e&&"string"!=typeof e)throw new Error(`Invalid number value: ${e}`);this._number=e}static get body(){return this._body}static set body(e){if(null!=e&&"string"!=typeof e)throw new Error(`Invalid body value: ${e}`);this._body=e}static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}static isPlainObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}class g{static serviceWorkerUrl=null;static channelId=null;static assign(e){return this.serviceWorkerUrl=e?.serviceWorkerUrl||null,this.channelId=e?.channelId||null,this}}class f{static apiRoot="https://api.hellotext.com/v1";static actionCableUrl="wss://www.hellotext.com/cable";static autoGenerateSession=!0;static session=null;static forms=a;static popup=c;static webchat=d;static whatsapp=m;static push=g;static assign(e){if(e){const t=Object.prototype.hasOwnProperty.call(e,"apiRoot")&&!Object.prototype.hasOwnProperty.call(e,"actionCableUrl");Object.entries(e).forEach(([e,t])=>{"forms"===e?this.forms=a.assign(t):"popup"===e?this.popup=c.assign(t):"webchat"===e?this.webchat=d.assign(t):"whatsappWidget"===e?this.whatsapp=m.assign(t):"push"===e?this.push=g.assign(t):this[e]=t}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}static set locale(e){o.identifier=e}static get locale(){return o.toString()}static endpoint(e){return`${this.apiRoot}/${e}`}static actionCableUrlForApiRoot(e){try{const t=new URL(e),s="https:"===t.protocol?"wss:":"ws:";return t.protocol=s,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}const y=class{static get endpoint(){return f.endpoint("public/businesses")}static async get(e){return fetch(`${this.endpoint}/${e}`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json","Content-Type":"application/json"}})}};class b{static get inPreviewMode(){return(new this).inPreviewMode}constructor(){this.urlSearchParams=new URLSearchParams(window.location.search)}get(e){return this.urlSearchParams.get(this.toHellotextParam(e))}has(e){return this.urlSearchParams.has(this.toHellotextParam(e))}get inPreviewMode(){return this.has("preview")}get session(){return this.get("session")}get popup(){return this.get("popup")}toHellotextParam(e){return`hello_${e}`}}class v{#i;constructor(e,t){this.response=t,this.#i=e}get data(){return this.response}async json(){return await this.response.json()}get failed(){return!1===this.#i}get succeeded(){return!0===this.#i}}class w{static get endpoint(){return f.endpoint("track/events")}static async create({headers:e,body:t,keepalive:s=!1}){if(b.inPreviewMode)return new v(!0,{received:!0});const i={method:"POST",headers:e,body:JSON.stringify(t)};s&&(i.keepalive=!0);const n=await fetch(this.endpoint,i);return new v(200===n.status,await n.json())}}class T{static get endpoint(){return f.endpoint("public/forms")}static async get(e){const t=new URL(`${this.endpoint}/${e}`);return t.searchParams.append("session",Lt.session),t.searchParams.append("locale",o.toString()),fetch(t,{method:"GET",headers:Lt.headers})}static async submit(e,t){const s=await fetch(`${this.endpoint}/${e}/submissions`,{method:"POST",headers:Lt.headers,body:JSON.stringify({session:Lt.session,...t})});return new v(s.ok,s)}}const S=class{static get endpoint(){return f.endpoint("public/identifications")}static async create(e={}){const t=await fetch(this.endpoint,{method:"POST",headers:Lt.headers,body:JSON.stringify({session:Lt.session,...e})});return new v(t.ok,t)}},C=class{static get endpoint(){return f.endpoint("public/popups")}static async get(e,{linked:t=!1}={}){const s=new URL(`${this.endpoint}/${e}`);s.searchParams.append("session",Lt.session),s.searchParams.append("locale",o.toString()),s.searchParams.append("device",this.runtimeDevice),t&&s.searchParams.append("linked","true");const i=await this.fetchPopup(s);if(!i.ok)return null;const n=await this.parsePopupResponse(i);return n&&!1!==n.eligible&&n.html?(Lt.business.data||(Lt.business.setData(n.business),Lt.business.setLocale(n.locale)),(new DOMParser).parseFromString(n.html,"text/html").querySelector("article")):null}static async submit(e,t,s=this.idempotencyKey()){const i=await fetch(`${this.endpoint}/${e}/submissions`,{method:"POST",headers:{...Lt.headers,"Idempotency-Key":s},body:JSON.stringify({session:Lt.session,popup_submission:t})});return new v(i.ok,i)}static async resend(e,t,s){const i=await fetch(`${this.endpoint}/${e}/submissions/${t}/resend`,{method:"POST",headers:Lt.headers,body:JSON.stringify({token:s})});return new v(i.ok,i)}static async cancel(e,t,s){const i=await fetch(`${this.endpoint}/${e}/submissions/${t}/cancel`,{method:"POST",headers:Lt.headers,body:JSON.stringify({token:s})});return new v(i.ok,i)}static idempotencyKey(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}static async fetchPopup(e){try{return await fetch(e,{method:"GET",headers:Lt.headers})}catch(e){return{ok:!1}}}static get runtimeDevice(){return"auto"!==f.popup.device?f.popup.device:window.innerWidth<=767?"mobile":"desktop"}static async parsePopupResponse(e){try{return await e.json()}catch(e){return null}}},A=class{static get endpoint(){return f.endpoint("public/webchats")}static async get(e){const t=new URL(`${this.endpoint}/${e}`);t.searchParams.append("session",Lt.session),t.searchParams.append("locale",o.toString()),Object.entries(f.webchat.style).forEach(([e,s])=>{t.searchParams.append(`style[${e}]`,s)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",f.webchat.placement);const s=await fetch(t,{method:"GET",headers:Lt.headers}),i=await s.json();return Lt.business.data||(Lt.business.setData(i.business),Lt.business.setLocale(i.locale)),(new DOMParser).parseFromString(i.html,"text/html").querySelector("article")}static appendWebchatOverrides(e){const{appearance:t,whatsapp:s}=f.webchat;this.appendIfSupplied(e,"webchat[appearance][header][name]",t.header?.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",t.launcher?.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",s.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",s.restrictToChannel)}static appendIfSupplied(e,t,s){null!=s&&e.searchParams.append(t,String(s))}},E=class{static get endpoint(){return f.endpoint("public/widgets/whatsapp")}static async get(e){const t=new URL(`${this.endpoint}/${e}`);Lt.session&&t.searchParams.append("session",Lt.session),t.searchParams.append("locale",o.toString()),t.searchParams.append("placement",f.whatsapp.placement),this.appendWhatsAppOverrides(t);const s=await this.fetchWidget(t);if(!s.ok)return null;const i=await this.parseWidgetResponse(s);return i?(Lt.business.data||(Lt.business.setData(i.business),Lt.business.setLocale(i.locale)),(new DOMParser).parseFromString(i.html,"text/html").querySelector("article")):null}static appendWhatsAppOverrides(e){const{appearance:t,body:s,number:i}=f.whatsapp;this.appendIfSupplied(e,"whatsapp[appearance][launcher][icon_url]",t.launcher?.iconUrl),this.appendIfSupplied(e,"whatsapp[number]",i),this.appendIfSupplied(e,"whatsapp[body]",s)}static appendIfSupplied(e,t,s){null!=s&&e.searchParams.append(t,String(s))}static async fetchWidget(e){try{return await fetch(e,{method:"GET",headers:Lt.headers})}catch(e){return{ok:!1}}}static async parseWidgetResponse(e){try{return await e.json()}catch(e){return null}}},O=class{static get endpoint(){return f.endpoint("public/acks")}static async send(e={}){const t={...e,session:Lt.session,at:(new Date).toISOString()};fetch(this.endpoint,{method:"POST",headers:Lt.headers,body:JSON.stringify(t),keepalive:!0})}},x=class{static get endpoint(){return f.endpoint("public/push/identities")}static async create(e={}){const t=await fetch(this.endpoint,{method:"POST",keepalive:!0,headers:Lt.headers,body:JSON.stringify({...e,session:Lt.session,origin:window.location.origin})});return new v(t.ok,t)}static async destroy(e={}){const t=await fetch(this.endpoint,{method:"DELETE",keepalive:!0,headers:Lt.headers,body:JSON.stringify({...e,session:Lt.session,origin:window.location.origin})});return new v(t.ok,t)}},k=class{static get endpoint(){return f.endpoint("public/push/alerts")}static async create({section:e,kind:t,page:s,pushIdentity:i}){const n=await fetch(this.endpoint,{method:"POST",keepalive:!0,headers:Lt.headers,body:JSON.stringify({session:Lt.session,section:e,kind:t,page:s,push_identity:i})});return new v(n.ok,n)}};function M(e){const t=JSON.stringify(e);return"undefined"==typeof Blob?t.length<6e4:new Blob([t]).size<6e4}class I{static get businesses(){return y}static get events(){return w}static get forms(){return T}static get popups(){return C}static get popups(){return C}static get webchats(){return A}static get whatsappWidgets(){return E}static get identifications(){return S}static get acks(){return O}static get pushAlerts(){return k}static get pushIdentities(){return x}}const P="data-hellotext-stylesheet";class L{constructor(e){this.id=e,this.data=null,this.stylesheet=null,this.stylesheetLoaded=Promise.resolve(!1)}async hydrate(){try{const e=await y.get(this.id);if(!1===e.ok)return null;const t=await e.json();return t?(this.setData(t),this.setLocale(o.toString()),t):null}catch(e){return null}}setData(e){this.data=e,"undefined"!=typeof document&&e.style_url?(this.stylesheet=this.constructor.ensureStylesheet(e.style_url),this.stylesheetLoaded=this.constructor.waitForStylesheet(this.stylesheet)):(this.stylesheet=null,this.stylesheetLoaded=Promise.resolve(!1))}static get stylesheetSelector(){return`link[rel="stylesheet"][${P}]`}static ensureStylesheet(e){const t=this.normalizedStylesheetUrl(e),s=this.stylesheetLinks.find(e=>e.href===t);if(s)return s.setAttribute(P,"true"),s;const i=document.createElement("link");return i.rel="stylesheet",i.href=e,i.setAttribute(P,"true"),this.waitForStylesheet(i),document.head.append(i),i}static get stylesheetLinks(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}static get latestStylesheet(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}static normalizedStylesheetUrl(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}static waitForStylesheet(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{let s;const i=i=>{clearTimeout(s),e.removeEventListener("load",n),e.removeEventListener("error",r),e.dataset.hellotextStylesheetLoaded=i?"true":"false",t(i)},n=()=>i(this.stylesheetIsLoaded(e)),r=()=>i(!1);e.addEventListener("load",n),e.addEventListener("error",r),s=setTimeout(()=>i(this.stylesheetIsLoaded(e)),1e4),s.unref&&s.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}static stylesheetIsLoaded(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}get subscription(){return this.data.subscription}get country(){return this.data.country}get enabledWhitelist(){return"disabled"!==this.data.whitelist}setLocale(e){this.data||(this.data={});const t=e?.toLowerCase().split("-")[0];this.data.locale=Object.prototype.hasOwnProperty.call(this.data.locales||{},t)?t:"en"}get locale(){const e=this.data?.locales;return e?.[this.data.locale]||e?.en}get features(){return this.data.features}}class _{static set(e,t){if("undefined"!=typeof document){const s="https:"===window.location.protocol?"; Secure":"",i=V.getRootDomain(),n=31536e4;document.cookie=i?`${e}=${t}; path=/${s}; domain=${i}; max-age=${n}; SameSite=Lax`:`${e}=${t}; path=/${s}; max-age=${n}; SameSite=Lax`}return"hello_session"===e&&Lt.eventEmitter.dispatch("session-set",t),"hello_utm"===e&&Lt.eventEmitter.dispatch("utm-set",t),t}static get(e){return"undefined"!=typeof document?document.cookie.match("(^|;)\\s*"+e+"\\s*=\\s*([^;]+)")?.pop():void 0}static delete(e){if("undefined"!=typeof document){const t=V.getRootDomain(),s="https:"===window.location.protocol?"; Secure":"";document.cookie=t?`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT${s}; domain=${t}; SameSite=Lax`:`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT${s}; SameSite=Lax`}}}class N{static get documentSearch(){try{const e=window.performance?.getEntriesByType?.("navigation")?.[0];if(e?.name)return new URL(e.name).search}catch(e){}return window.location.search}static get sameSiteReferrer(){try{if("undefined"==typeof document||!document.referrer||!window.location.hostname)return null;const e=new URL(document.referrer);return V.getRootDomain(e.hostname)===V.getRootDomain(window.location.hostname)?e:null}catch(e){return null}}static get restored(){try{const e=window.performance?.getEntriesByType?.("navigation")?.[0]?.type;return"reload"===e||"back_forward"===e}catch(e){return!1}}}const D=["source","medium","campaign","term","content"],R="hello_utm",F="hello_utm_internal";class ${constructor(){const e=$.fromSearch(window.location.search);e&&($.isArrival(e)?this.saveArrival(e):$.isHellotext(e)?this.saveHellotext(e):this.saveIfChanged(F,e))}save(e){this.recordClick(e)}get current(){return $.read(R)}get internal(){return $.read(F)}saveArrival(e){const t=this.current,s=$.restored(e)||$.observedDuringThisDocument(t)||Boolean(N.sameSiteReferrer);$.same(e,t)&&s||this.recordClick(e)}saveHellotext(e){const t=this.current;$.restored(e)&&$.complete(t)||$.same(e,t)&&$.observedDuringThisDocument(t)||this.recordClick(e)}recordClick(e){$.complete(e)&&(Object.keys(this.internal).length&&_.delete(F),this.write(R,e))}saveIfChanged(e,t){$.same(t,$.read(e))||this.write(e,t)}write(e,t){if(!$.complete(t))return;const s=Object.fromEntries(Object.entries(t).filter(([e,t])=>t&&"observed_at"!==e));s.observed_at=(new Date).toISOString(),_.set(e,JSON.stringify(s))}static complete(e){return Boolean(e?.source&&e?.medium)}static fromSearch(e){const t=$.paramsFrom(e);return t.source&&t.medium?t:null}static paramsFrom(e){const t=new URLSearchParams(e||"");return Object.fromEntries(D.map(e=>[e,t.get(`utm_${e}`)]).filter(([e,t])=>t))}static isArrival(e){if(!$.same(e,$.fromSearch(N.documentSearch)))return!1;if($.restored(e)){const t=$.read(R);return!$.complete(t)||$.same(e,t)}const t=N.sameSiteReferrer;return!t||!$.same(e,$.read(F))&&$.same(e,$.fromSearch(t.search))}static isHellotext(e){return"hellotext"===String(e.source).toLowerCase()}static same(e,t){return!(!e||!t)&&D.every(s=>(e[s]||"")===(t[s]||""))}static read(e){try{return JSON.parse(_.get(e))||{}}catch(e){return{}}}static restored(e){return N.restored&&$.same(e,$.fromSearch(N.documentSearch))}static observedDuringThisDocument(e){const t=window.performance?.timeOrigin,s=Date.parse(e?.observed_at);return Boolean(t)&&!Number.isNaN(s)&&s>=t}}const B=["homepage","product_collection","product_details"];class V{static route(e=window.location.href){const t=new URL(e||window.location.href,window.location.href),s=t.hash.match(/^#!?\/[^?]*/)?.[0];return`${t.pathname}${s?.replace(/^#!/,"#")||""}`}constructor(e=null){this.utm=new $,this._url=e,this._section=null}get section(){return this._section&&this._section.route===V.route(this.url)?this._section.value:null}set section(e){this._section=B.includes(e)?{value:e,route:V.route(this.url)}:null}get url(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}get title(){return document.title}get path(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}get utmParams(){return this.utm.current}get trackingData(){const e=this.utm.internal||{},t=this.section;return{page:{url:this.url,title:this.title,path:this.path,...t&&{section:t}},utm_params:this.utmParams,...Object.keys(e).length&&{internal_utm_params:e}}}get domain(){try{const e=this.url;if(!e)return null;const t=new URL(e).hostname;return V.getRootDomain(t)}catch(e){return null}}static getRootDomain(e=null){try{if(!e){if("undefined"==typeof window||!window.location?.hostname)return null;e=window.location.hostname}const t=e.split(".");if(t.length<=1)return e;const s=["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"];for(const e of s){const s=e.split(".");if(t.slice(-s.length).join(".")===e&&t.length>s.length)return`.${t.slice(-(s.length+1)).join(".")}`}const i=t[t.length-1],n=t[t.length-2];return t.length>2&&2===i.length&&n.length<=3?`.${t.slice(-3).join(".")}`:`.${t.slice(-2).join(".")}`}catch(e){return null}}}class j{static#n;static#r;static#a;static get session(){return this.#n}static get ackPayload(){return{utm_params:this.#a?.utmParams||{}}}static set session(e){const t=_.get("hello_session");return this.#n=e,_.set("hello_session",e),t!==e&&_.delete("hello_session_ack_at"),_.get("hello_session_ack_at")||(I.acks.send(this.ackPayload),_.set("hello_session_ack_at",(new Date).toISOString())),this.#n}static initialize(e=new V){this.#a=e,this.#r=new b,this.session=this.#r.session||f.session||_.get("hello_session"),!this.session&&f.autoGenerateSession&&(this.session=crypto.randomUUID())}}class q{static build(e){const t=document.createElement("article"),s=document.createElement("label"),i=document.createElement("input");s.innerText=e.label,i.type=e.type,i.required=e.required,i.placeholder=e.placeholder,["first_name","last_name"].includes(e.kind)?(i.type="text",i.id=i.name=e.kind,s.setAttribute("for",e.kind)):(i.type=e.type,"email"===e.type?(i.id=i.name="email",s.setAttribute("for","email")):"tel"===i.type?(i.id=i.name="phone",s.setAttribute("for","phone"),i.value=`+${Lt.business.country.prefix}`,i.setAttribute("data-default-value",`+${Lt.business.country.prefix}`)):(i.name=i.id=`property_by_id[${e.property}]`,s.setAttribute("for",`property_by_id[${e.property}]`)));const n=document.createElement("main");n.appendChild(s),n.appendChild(i),t.appendChild(n),t.setAttribute("data-hellotext--form-target","inputContainer"),i.setAttribute("data-hellotext--form-target","input");const r=document.createElement("div");return r.setAttribute("data-error-container",""),t.appendChild(r),t}}class U{static build(){const e=document.createElement("div");return e.innerHTML=this.#o(),e.firstElementChild}static#o(){const e=`https://www.hellotext.com?hello_session=${Lt.session}`;return`\n
\n ${Lt.business.locale.white_label.powered_by}\n\n \n \n Hellotext\n \n \n \n
\n `}}function z(e,t){this.v=e,this.k=t}function W(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s2?s-2:0),n=2;n1?t-1:0),i=1;i1?s-1:0),n=1;n2&&void 0!==arguments[2]?arguments[2]:ge;if(J&&J(e,null),!ue(t))return e;let i=t.length;for(;i--;){let n=t[i];if("string"==typeof n){const e=s(n);e!==n&&(Y(t)||(t[i]=e),n=e)}e[n]=!0}return e}function Le(e){for(let t=0;t/g),Ge=ee(/\${[\w\W]*/g),Je=ee(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ye=ee(/^aria-[\-\w]+$/),Ze=ee(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Xe=ee(/^(?:\w+script|data):/i),Qe=ee(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),et=ee(/^html$/i),tt=ee(/^[a-z][.\w]*(-[.\w]+)+$/i),st=ee(/<[/\w!]/g),it=ee(/<[/\w]/g),nt=ee(/<\/no(script|embed|frames)/i),rt=ee(/\/>/i),at=Q(Pe({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),ot=function(){return"undefined"==typeof window?null:window},ct=function(e,t,s,i){return Ee(e,t)&&ue(e[t])?Pe(i.base?_e(i.base):{},e[t],i.transform):s},lt=function(e,t,s){const i=Ee(e,t)?e[t]:void 0;return i&&"object"==typeof i?_e(i):s()};var ht=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ot();const s=t=>e(t);if(s.version="3.4.17",s.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return s.isSupported=!1,s;let i=t.document;const n=i,r=n.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,o=t.Node,c=t.Element,l=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const h=t.DOMParser,u=t.trustedTypes,d=c.prototype,p=Ne(d,"cloneNode"),m=Ne(d,"remove"),g=Ne(d,"removeAttributeNode"),f=Ne(d,"nextSibling"),y=Ne(d,"childNodes"),b=Ne(d,"parentNode"),v=Ne(d,"shadowRoot"),w=Ne(d,"attributes"),T=o&&o.prototype?Ne(o.prototype,"nodeType"):null,S=o&&o.prototype?Ne(o.prototype,"nodeName"):null,C=o&&o.prototype?Ne(o.prototype,"ownerDocument"):null,A=function(e){return T?T(e):e.nodeType},E=function(e){return S?S(e):e.nodeName},O=function(e){for(;null!==e;){const t=X(e,"namespaceURI");if(t)return t.get?Me(t.get):null;e=Z(e)}return null}(d),x=function(e){return O?O(e):e.namespaceURI};if("function"==typeof a){const e=i.createElement("template");e.content&&e.content.ownerDocument&&(i=e.content.ownerDocument)}let k,M,I="",P=!1,L=0;const _=function(){if(L>0)throw ke('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},N=function(e){_(),L++;try{return k.createHTML(e)}finally{L--}},D=i,R=D.implementation,F=D.createNodeIterator,$=D.createDocumentFragment,B=D.getElementsByTagName,V=n.importNode;let j={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};s.isSupported="function"==typeof G&&"function"==typeof b&&R&&void 0!==R.createHTMLDocument;const q=Ke,U=He,z=Ge,W=Je,K=Ye,H=Xe,J=Qe,Y=tt;let se=Ze,ie=null;const ne=Pe({},[...De,...Re,...Fe,...Be,...je]);let Ie=null;const Le=Pe({},[...qe,...Ue,...ze,...We]);let ht=Object.seal(te(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ut=null,dt=null;const pt=Object.seal(te(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let mt=!0,gt=!0,ft=!1,yt=!0,bt=!1,vt=!0,wt=!1,Tt=!1,St=null,Ct=null,At=!1,Et=!1,Ot=!1,xt=!1,kt=!0,Mt=!1;const It="user-content-";let Pt=!0,Lt=!1,_t=null,Nt={},Dt=null;const Rt=Pe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Ft=null;const $t=Pe({},["audio","video","img","source","image","track"]);let Bt=null;const Vt=Pe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),jt="http://www.w3.org/1998/Math/MathML",qt="http://www.w3.org/2000/svg",Ut="http://www.w3.org/1999/xhtml";let zt=Ut,Wt=!1,Kt=null;const Ht=Pe({},[jt,qt,Ut],fe),Gt=Q(["mi","mo","mn","ms","mtext"]);let Jt=Pe({},Gt);const Yt=Q(["annotation-xml"]);let Zt=Pe({},Yt);const Xt=Pe({},["title","style","font","a","script"]);let Qt=null;const es=["application/xhtml+xml","text/html"];let ts=null,ss=null;const is=i.createElement("form"),ns=function(e){return e instanceof RegExp||e instanceof Function},rs=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ss&&ss===e)return;e&&"object"==typeof e||(e={}),e=_e(e),Qt=-1===es.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ts="application/xhtml+xml"===Qt?fe:ge,ie=ct(e,"ALLOWED_TAGS",ne,{transform:ts}),Ie=ct(e,"ALLOWED_ATTR",Le,{transform:ts}),Kt=ct(e,"ALLOWED_NAMESPACES",Ht,{transform:fe}),Bt=ct(e,"ADD_URI_SAFE_ATTR",Vt,{transform:ts,base:Vt}),Ft=ct(e,"ADD_DATA_URI_TAGS",$t,{transform:ts,base:$t}),Dt=ct(e,"FORBID_CONTENTS",Rt,{transform:ts}),ut=ct(e,"FORBID_TAGS",_e({}),{transform:ts}),dt=ct(e,"FORBID_ATTR",_e({}),{transform:ts}),Nt=!!Ee(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?_e(e.USE_PROFILES):e.USE_PROFILES),mt=!1!==e.ALLOW_ARIA_ATTR,gt=!1!==e.ALLOW_DATA_ATTR,ft=e.ALLOW_UNKNOWN_PROTOCOLS||!1,yt=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,bt=e.SAFE_FOR_TEMPLATES||!1,vt=!1!==e.SAFE_FOR_XML,wt=e.WHOLE_DOCUMENT||!1,Et=e.RETURN_DOM||!1,Ot=e.RETURN_DOM_FRAGMENT||!1,xt=e.RETURN_TRUSTED_TYPE||!1,At=e.FORCE_BODY||!1,kt=!1!==e.SANITIZE_DOM,Mt=e.SANITIZE_NAMED_PROPS||!1,Pt=!1!==e.KEEP_CONTENT,Lt=e.IN_PLACE||!1,se=function(e){try{return xe(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Ze,zt="string"==typeof e.NAMESPACE?e.NAMESPACE:Ut,Jt=lt(e,"MATHML_TEXT_INTEGRATION_POINTS",()=>Pe({},Gt)),Zt=lt(e,"HTML_INTEGRATION_POINTS",()=>Pe({},Yt));const t=lt(e,"CUSTOM_ELEMENT_HANDLING",()=>te(null));if(ht=te(null),Ee(t,"tagNameCheck")&&ns(t.tagNameCheck)&&(ht.tagNameCheck=t.tagNameCheck),Ee(t,"attributeNameCheck")&&ns(t.attributeNameCheck)&&(ht.attributeNameCheck=t.attributeNameCheck),Ee(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(ht.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),ee(ht),bt&&(gt=!1),Ot&&(Et=!0),Nt&&(ie=Pe({},je),Ie=te(null),!0===Nt.html&&(Pe(ie,De),Pe(Ie,qe)),!0===Nt.svg&&(Pe(ie,Re),Pe(Ie,Ue),Pe(Ie,We)),!0===Nt.svgFilters&&(Pe(ie,Fe),Pe(Ie,Ue),Pe(Ie,We)),!0===Nt.mathMl&&(Pe(ie,Be),Pe(Ie,ze),Pe(Ie,We))),pt.tagCheck=null,pt.attributeCheck=null,Ee(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?pt.tagCheck=e.ADD_TAGS:ue(e.ADD_TAGS)&&(ie===ne&&(ie=_e(ie)),Pe(ie,e.ADD_TAGS,ts))),Ee(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?pt.attributeCheck=e.ADD_ATTR:ue(e.ADD_ATTR)&&(Ie===Le&&(Ie=_e(Ie)),Pe(Ie,e.ADD_ATTR,ts))),Ee(e,"ADD_FORBID_CONTENTS")&&ue(e.ADD_FORBID_CONTENTS)&&(Dt===Rt&&(Dt=_e(Dt)),Pe(Dt,e.ADD_FORBID_CONTENTS,ts)),Pt&&(ie["#text"]=!0),wt&&Pe(ie,["html","head","body"]),ie.table&&(Pe(ie,["tbody"]),delete ut.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw ke('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw ke('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=k;k=e.TRUSTED_TYPES_POLICY;try{I=N("")}catch(e){throw k=t,e}}else null===e.TRUSTED_TYPES_POLICY?(k=void 0,I=""):(void 0===k&&(P||(M=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let s=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(s=t.getAttribute(i));const n="dompurify"+(s?"#"+s:"");try{return e.createPolicy(n,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+n+" could not be created."),null}}(u,r),P=!0),k=M),k&&"string"==typeof I&&(I=N("")));Q&&Q(e),ss=e},as=Pe({},[...Re,...Fe,...$e]),os=Pe({},[...Be,...Ve]),cs=function(e){ce(s.removed,{element:e});try{b(e).removeChild(e)}catch(t){if(m(e),!b(e))throw ke("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},ls=function(e,t,s){try{g(e,t)}catch(t){try{e.removeAttribute(s)}catch(e){}}},hs=function(e){ms(e);const t=y(e);t&&re(le(t),e=>{try{m(e)}catch(e){}});const s=1===A(e)?w(e):null;if(s)for(let t=s.length-1;t>=0;--t){const i=s[t],n=i&&i.name;"string"==typeof n&&ls(e,i,n)}},us=function(e,t,i){if(!i)try{i=t.getAttributeNode(e)}catch(e){i=null}ce(s.removed,{attribute:i||null,from:t});try{i?g(t,i):t.removeAttribute(e)}catch(s){try{t.removeAttribute(e)}catch(e){}}if("is"===e)if(Et||Ot)try{cs(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},ds=function(e){const t=w(e);if(t)for(let s=t.length-1;s>=0;--s){const i=t[s],n=i&&i.name;"string"!=typeof n||Ie[ts(n)]||ls(e,i,n)}},ps=function(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const i=[e];for(;i.length>0;){const e=i.pop();if(!1===t(e))continue;if(s&&1===A(e)){const t=v(e);Es(t)&&i.push(t)}const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)i.push(n[e])}},ms=function(e){ps(e,e=>{1===A(e)&&ds(e)})},gs=function(e){const t=[];return ps(e,e=>{t.push(e)},!0),t},fs=function(e,t){let i=!1;return re(s.removed,t=>{t.element&&(i=i||t.element===e,ms(t.element))}),function(e,t){const s=de();re(gs(e),e=>{1===A(e)&&pe(s,e)}),re(t,e=>{1!==A(e)||me(s,e)||ds(e)})}(e,t),i},ys=function(e,t,s,i){const n=ws(e);let r;for(;r=n.nextNode();)me(i,r)&&!me(_t,r)&&(t&&xs(j.uponSanitizeShadowNode,r,null),Ps(r,s),$s(r,s),Es(r.content)&&Bs(r.content))},bs=function(e,t){return!!vt&&("patchsrc"===e||"for"===e&&"label"!==t&&"output"!==t)},vs=function(e){let t=null,s=null;if(At)e=""+e;else{const t=ye(e,/^[\r\n\t ]+/);s=t&&t[0]}"application/xhtml+xml"===Qt&&zt===Ut&&(e=''+e+"");const n=k?N(e):e;if(zt===Ut)try{t=(new h).parseFromString(n,Qt)}catch(e){}if(!t||!t.documentElement){t=R.createDocument(zt,"template",null);try{t.documentElement.innerHTML=Wt?I:n}catch(e){}}const r=t.body||t.documentElement;return e&&s&&r.insertBefore(i.createTextNode(s),r.childNodes[0]||null),zt===Ut?B.call(t,wt?"html":"body")[0]:wt?t.documentElement:r},ws=function(e){const t=C?C(e):e.ownerDocument;return F.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ts=function(e){return e=be(e,q," "),e=be(e,U," "),be(e,z," ")},Ss=function(e){var t;Cs(e);const s=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");s&&re(s,e=>{Es(e.content)&&Ss(e.content)})},Cs=function(e){e.normalize();const t=C?C(e):e.ownerDocument,s=F.call(t||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let i=s.nextNode();for(;i;)i.data=Ts(i.data),i=s.nextNode()},As=function(e){const t=S?S(e):null;return"string"==typeof t&&"form"===ts(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==w(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.removeAttributeNode||"function"!=typeof e.getAttributeNode||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==T(e)||e.childNodes!==y(e))},Es=function(e){if(!T||"object"!=typeof e||null===e)return!1;try{return 11===T(e)}catch(e){return!1}},Os=function(e){if(!T||"object"!=typeof e||null===e)return!1;try{return"number"==typeof T(e)}catch(e){return!1}};function xs(e,t,i){0!==e.length&&re(e,e=>{e.call(s,t,i,ss)})}const ks=function(e,t){if(e instanceof RegExp)return xe(e,t);if(e instanceof Function){for(var s=arguments.length,i=new Array(s>2?s-2:0),n=2;n=0;--n){const r=e===s?p(i[n],!0):i[n];t.insertBefore(r,f(e))}}return cs(e),!0}(e,i,t);return!(!1!==s||(xs(j.afterSanitizeElements,e,null),!Is(e,t)))||s}if(1===A(e)&&!function(e){const t=x(e),s=ge(E(e)),i=b(e);let n,r;return i&&1===A(i)?(n={namespaceURI:x(i)},r=ge(E(i))):(n={namespaceURI:zt},r="template"),!!Kt[t]&&(t===qt?function(e,t,s){return t.namespaceURI===Ut?"svg"===e:t.namespaceURI===jt?"svg"===e&&("annotation-xml"===s||Jt[s]):Boolean(as[e])}(s,n,r):t===jt?function(e,t,s){return t.namespaceURI===Ut?"math"===e:t.namespaceURI===qt?"math"===e&&Zt[s]:Boolean(os[e])}(s,n,r):t===Ut?function(e,t,s){return!(t.namespaceURI===qt&&!Zt[s])&&!(t.namespaceURI===jt&&!Jt[s])&&!os[e]&&(Xt[e]||!as[e])}(s,n,r):!("application/xhtml+xml"!==Qt||!Kt[t]))}(e))return cs(e),!0;if(("noscript"===i||"noembed"===i||"noframes"===i)&&xe(nt,e.innerHTML))return cs(e),!0;if(bt&&3===e.nodeType){const t=Ts(e.textContent);e.textContent!==t&&(ce(s.removed,{element:e.cloneNode()}),e.textContent=t)}return xs(j.afterSanitizeElements,e,null),Is(e,t)},Ls=function(e,t,s){if(dt[t])return!1;if(bs(t,e))return!1;if(kt&&("id"===t||"name"===t)&&(s in i||s in is))return!1;const n=Ie[t]||pt.attributeCheck instanceof Function&&pt.attributeCheck(t,e);return!(!gt||!xe(W,t))||!(!mt||!xe(K,t))||(n?!(!Bt[t]&&!xe(se,be(s,J,""))&&("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==ve(s,"data:")||!Ft[e])&&(!ft||xe(H,be(s,J,"")))&&s):Ns(e)&&ks(ht.tagNameCheck,e)&&ks(ht.attributeNameCheck,t,e)||"is"===t&&ht.allowCustomizedBuiltInElements&&ks(ht.tagNameCheck,s))},_s=Pe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Ns=function(e){return!_s[ge(e)]&&xe(Y,e)},Ds=function(e,t,s,i){if(k&&"object"==typeof u&&"function"==typeof u.getAttributeType&&!s)switch(u.getAttributeType(e,t)){case"TrustedHTML":return N(i);case"TrustedScriptURL":return function(e){_(),L++;try{return k.createScriptURL(e)}finally{L--}}(i)}return i},Rs=function(e,t,s,i){try{return s?e.setAttributeNS(s,t,i):e.setAttribute(t,i),!As(e)||(cs(e),!1)}catch(s){return us(t,e),!1}},Fs=function(e,t){return!(!vt||!xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,t))||"attributename"===ge(e)&&null!==ye(t,"href")},$s=function(e,t){if(xs(j.beforeSanitizeAttributes,e,null),Is(e,t))return;const i=e.attributes;if(!i||As(e))return;Ie=Ms(j.uponSanitizeAttribute,Ie,Le,Ct);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ie,forceKeepAttr:void 0};let r=i.length;const a=ts(e.nodeName);for(;r--;){const t=i[r],o=t.name,c=t.namespaceURI,l=t.value,h=ts(o),u=l;let d="value"===o?u:we(u),p=!1;n.attrName=h,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,xs(j.uponSanitizeAttribute,e,n),d=n.attrValue,!Mt||"id"!==h&&"name"!==h||0===ve(d,It)||(us(o,e,t),d=It+d,p=!0),Fs(o,d)?us(o,e,t):n.forceKeepAttr||(!n.keepAttr||!yt&&xe(rt,d)?us(o,e,t):(bt&&(d=Ts(d)),Ls(a,h,d)?(d=Ds(a,h,c,d),d!==u&&Rs(e,o,c,d)&&p&&oe(s.removed)):us(o,e,t)))}xs(j.afterSanitizeAttributes,e,null),Is(e,t)},Bs=function(e){let t=null;const s=ws(e);for(xs(j.beforeSanitizeShadowDOM,e,null);t=s.nextNode();)if(xs(j.uponSanitizeShadowNode,t,null),Ps(t,e),$s(t,e),Es(t.content)&&Bs(t.content),1===A(t)){const e=v(t);Es(e)&&(Vs(e),Bs(e))}bt&&Cs(e),xs(j.afterSanitizeShadowDOM,e,null)},Vs=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){Bs(e.shadow);continue}const s=e.node,i=1===A(s),n=y(s);if(n)for(let e=n.length-1;e>=0;--e)t.push({node:n[e],shadow:null});if(i){const e=S?S(s):null;if("string"==typeof e&&"template"===ts(e)){const e=s.content;Es(e)&&t.push({node:e,shadow:null})}}if(i){const e=v(s);Es(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return s.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=null,r=null,a=null,o=null;if(Wt=!e,Wt&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Os(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return Te(e);case"boolean":return Se(e);case"bigint":return Ce?Ce(e):"0";case"symbol":return Ae?Ae(e):"Symbol()";case"undefined":default:return Oe(e);case"function":case"object":{if(null===e)return Oe(e);const t=e,s=Ne(t,"toString");if("function"==typeof s){const e=s(t);return"string"==typeof e?e:Oe(e)}return Oe(e)}}}(e)))throw ke("dirty is not a string, aborting");if(!s.isSupported)return e;Tt?(ie=St,Ie=Ct):rs(t),(j.uponSanitizeElement.length>0||j.uponSanitizeAttribute.length>0)&&(ie=_e(ie)),j.uponSanitizeAttribute.length>0&&(Ie=_e(Ie)),s.removed=[];const c=Lt&&"string"!=typeof e&&Os(e);let l=[];const h=_t;if(c){vt&&ps(e,e=>{const t=A(e);if(7===t||8===t&&xe(it,e.data)){try{m(e)}catch(e){}return!1}if(1===t){const t=e,s=ts(E(e));try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&bs("for",s)&&t.removeAttribute("for")}catch(e){}}return!0});const t=E(e);if("string"==typeof t){const s=ts(t);if(!ie[s]||ut[s])throw hs(e),ke("root node is forbidden and cannot be sanitized in-place")}if(As(e))throw hs(e),ke("root node is clobbered and cannot be sanitized in-place");l=gs(e),_t=de()}else if(Os(e))i=vs("\x3c!----\x3e"),r=i.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?i=r:i.appendChild(r),Vs(i);else{if(!Et&&!bt&&!wt&&-1===e.indexOf("<"))return k&&xt?N(e):e;if(i=vs(e),!i)return Et?null:xt?I:""}i&&At&&cs(i.firstChild);const u=c?e:i;try{c&&Vs(e);const t=ws(u);for(;a=t.nextNode();)Ps(a,u),$s(a,u),Es(a.content)&&Bs(a.content);c&&function(e,t){const s=_t;let i=null;const n=()=>(i||(i=de(),re(t,e=>{pe(i,e)})),i);for(let t=0;;t++){const i=gs(e),r=[e];let a=!1;if(re(i,e=>{11===A(e)?ce(r,e):a||me(s,e)||(a=me(n(),e))}),!a)return;if(t>=8)throw ke("the tree kept changing during in-place sanitization; refusing to return it");re(r,(t,s)=>{ys(t,s>0,e,n())})}}(e,l)}catch(t){throw c&&(hs(e),fs(e,l)),t}finally{_t=h}if(c){if(fs(e,l))throw ke("a node selected for removal could not be safely returned; refusing to sanitize in place");return bt&&Ss(e),e}if(Et){if(bt&&Ss(i),Ot)for(o=$.call(i.ownerDocument);i.firstChild;)o.appendChild(i.firstChild);else o=i;return(Ie.shadowroot||Ie.shadowrootmode)&&(o=V.call(n,o,!0)),o}let d=wt?i.outerHTML:i.innerHTML;return wt&&ie["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&xe(et,i.ownerDocument.doctype.name)&&(d="\n"+d),bt&&(d=Ts(d)),k&&xt?N(d):d},s.setConfig=function(){rs(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Tt=!0,St=ie,Ct=Ie},s.clearConfig=function(){ss=null,Tt=!1,St=null,Ct=null,k=M,I=""},s.isValidAttribute=function(e,t,s){ss||rs({});const i=ts(e),n=ts(t);return("string"!=typeof s||!(Fs(t,s)||!yt&&xe(rt,s)))&&Ls(i,n,s)},s.addHook=function(e,t){"function"==typeof t&&Ee(j,e)&&ce(j[e],t)},s.removeHook=function(e,t){if(Ee(j,e)){if(void 0!==t){const s=ae(j[e],t);return-1===s?void 0:he(j[e],s,1)[0]}return oe(j[e])}},s.removeHooks=function(e){Ee(j,e)&&(j[e]=[])},s.removeAllHooks=function(){j={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},s}();const ut={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},dt={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}},pt={RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function mt(e,t){const s=ht.sanitize(e,t);return s.querySelectorAll('a[target="_blank"]').forEach(e=>{const t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),s}function gt(e,t){e.replaceChildren(function(e){return mt(e,ut)}(t))}class ft{constructor(e,t=null){this.data=e,this.element=t||document.querySelector(`[data-hello-form="${this.id}"]`)||document.createElement("form")}async mount({ifCompleted:e=!0}={}){if(e&&this.hasBeenCompleted)return this.element?.remove(),Lt.eventEmitter.dispatch("form:completed",{id:this.id,...JSON.parse(localStorage.getItem(`hello-form-${this.id}`))});const t=this.data.steps[0];this.buildHeader(t.header),this.buildInputs(t.inputs),this.buildButton(t.button),this.buildFooter(t.footer),this.elementAttributes.forEach(e=>{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Lt.business.features.white_label||this.element.prepend(U.build())}buildHeader(e){const t=this.#c("[data-form-header]","header");gt(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}buildInputs(e){const t=this.#c("[data-form-inputs]","main");e.map(e=>q.build(e)).forEach(e=>t.appendChild(e)),this.element.querySelector("[data-form-inputs]")?this.element.querySelector("[data-form-inputs]").replaceWith(t):this.element.querySelector("[data-form-header]").insertAdjacentHTML("afterend",t.outerHTML)}buildButton(e){const t=this.#c("[data-form-button]","button");t.innerText=e.text,t.setAttribute("data-action","click->hellotext--form#submit"),t.setAttribute("data-hellotext--form-target","button"),this.element.querySelector("[data-form-button]")?this.element.querySelector("[data-form-button]").replaceWith(t):this.element.querySelector("[data-form-inputs]").insertAdjacentHTML("afterend",t.outerHTML)}buildFooter(e){const t=this.#c("[data-form-footer]","footer");gt(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}markAsCompleted(e){const t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem(`hello-form-${this.id}`,JSON.stringify(t)),Lt.recordActivity("form.completed"),Lt.eventEmitter.dispatch("form:completed",t)}get hasBeenCompleted(){return null!==localStorage.getItem(`hello-form-${this.id}`)}get id(){return this.data.id}get localeAuthKey(){const e=this.data.steps[0];return e.inputs.some(e=>"email"===e.kind)&&e.inputs.some(e=>"phone"===e.kind)?"phone_and_email":e.inputs.some(e=>"email"===e.kind)?"email":e.inputs.some(e=>"phone"===e.kind)?"phone":"none"}get elementAttributes(){return[{name:"data-controller",value:"hellotext--form"},{name:"data-hello-form",value:this.id},{name:"data-hellotext--form-data-value",value:JSON.stringify(this.data)}]}#c(e,t){const s=this.element.querySelector(e);if(s)return s.cloneNode(!0);const i=document.createElement(t);return i.setAttribute(e.replace("[","").replace("]",""),""),i}}class yt extends Error{constructor(){super("You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"),this.name="NotInitializedError"}}class bt{constructor(){this.forms=[],this.initializationVersion=Lt.initializationVersion,this.includes=this.includes.bind(this),this.excludes=this.excludes.bind(this),this.add=this.add.bind(this),"undefined"!=typeof MutationObserver&&(this.mutationObserver=new MutationObserver(this.formMutationObserver.bind(this)),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}collectExistingFormsOnPage(){Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}formMutationObserver(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}async collect(){if(Lt.notInitialized)throw new yt;if(this.fetching)return;if(!this.current)return;if("undefined"==typeof document||!("querySelectorAll"in document))return console.warn("Document is not defined, collection is not possible. Please make sure to initialize the library after the document is loaded.");const e=this.#l;if(0===e.length)return;const t=e.map(e=>T.get(e).then(e=>e.json()));this.fetching=!0;try{const e=await Promise.all(t);if(!this.current)return;e.forEach(this.add),Lt.eventEmitter.dispatch("forms:collected",this),f.forms.autoMount&&this.forms.forEach(e=>e.mount())}finally{this.fetching=!1}}forEach(e){this.forms.forEach(e)}map(e){return this.forms.map(e)}add(e){this.includes(e.id)||(Lt.business.data||(Lt.business.setData(e.business),Lt.business.setLocale(o.toString())),Lt.business.enabledWhitelist||console.warn("No whitelist has been configured. It is advised to whitelist the domain to avoid bots from submitting forms."),this.forms.push(new ft(e)))}getById(e){return this.forms.find(t=>t.id===e)}getByIndex(e){return this.forms[e]}includes(e){return this.forms.some(t=>t.id===e)}excludes(e){return!this.includes(e)}get length(){return this.forms.length}get current(){return Lt.initializationVersion===this.initializationVersion}get#l(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}}const vt=/^[A-Za-z0-9_-]{1,64}$/;class wt{static get linkedId(){const e=(new b).popup;if(!e||!vt.test(e))return null;if(N.restored&&wt.idIn(N.documentSearch)===e)return null;const t=N.sameSiteReferrer;return t&&wt.idIn(t.search)===e?null:e}static browser(e=("undefined"==typeof navigator?"":navigator.userAgent)){return/Android/i.test(e)?"android":/Edg\//.test(e)?"edge":/Firefox\//.test(e)?"firefox":/Chrome\//.test(e)?"chrome":/Safari\//.test(e)?"safari":"other"}static idIn(e){return new URLSearchParams(e||"").get("hello_popup")}static finished(e){if(!vt.test(e||""))return!1;const t=wt.finishedKey(e),s=_.get(t);if("0"===s){try{localStorage.removeItem(t)}catch(e){}return!1}let i=null;try{i=localStorage.getItem(t)}catch(e){}const n=Boolean(s||i);return n&&wt.markFinished(e),n}static markFinished(e){if(!vt.test(e||""))return;const t=wt.finishedKey(e);_.set(t,"1");try{localStorage.setItem(t,"1")}catch(e){}}static forgetFinished(e){if(!vt.test(e||""))return;const t=wt.finishedKey(e);_.set(t,"0");try{localStorage.removeItem(t)}catch(e){}}static finishedKey(e){return`hello_popup_submitted_${e}`}static async load(e,t={}){const s=new wt({id:e,html:await I.popups.get(e,{linked:t.linked})},t);return s.rendered=s.render(),s}constructor(e,{container:t=f.popup.container,linked:s=!1,shouldMount:i=()=>!0,onActivity:n=()=>{}}={}){this.data=e,this.container=t,this.linked=s,this.mounted=!1,this.rendered=Promise.resolve(!1),this.shouldMount=i,this.onActivity=n}async render(){if(!this.data.html||!this.shouldMount())return!1;const e=this.containerToAppendTo;return e?!!this.shouldMount()&&(this.linked&&this.data.html.setAttribute("data-hellotext--popup-linked-value","true"),this.data.html.addEventListener("hellotext--popup:activity",e=>{this.onActivity(e.detail.active)}),e.appendChild(this.data.html),this.mounted=!0,this.shouldMount()||this.unmount(),this.mounted):(console.warn(`Hellotext popup was not mounted because the container ${this.container} was not found.`),!1)}unmount(){this.data.html?.remove(),this.mounted=!1}get containerToAppendTo(){try{return document.querySelector(this.container)}catch(e){return null}}}class Tt{constructor(e){this.publicKey=e.public_key,this.serviceWorkerUrl=f.push.serviceWorkerUrl,this.channelId=f.push.channelId,this.ready=null,this.registrationPromise=null,this.subscribePromise=null,this.unsubscribePromise=null,this.syncPromise=null,this.subscription=null,this.retryTimeout=null,this.retryAttempts=0,this.disposed=!1}initialize(){return this.ready=this.restoreSubscription(),this.ready}async restoreSubscription(){const e=await this.getRegistration(),t=await e.pushManager.getSubscription();!this.disposed&&!this.unsubscribePromise&&t&&this.owns(t)&&(this.subscription=t,await this.sync())}subscribe({onPermission:e}={}){if(this.disposed)return Promise.resolve();if(this.unsubscribePromise)return Promise.reject(new Error("Push unsubscribe is in progress"));if(this.subscribePromise)return this.subscribePromise;const t="default"===Notification.permission?Notification.requestPermission():Promise.resolve(Notification.permission);return this.subscribePromise=this.createSubscription(t,e).finally(()=>{this.subscribePromise=null}),this.subscribePromise}async createSubscription(e,t){const s=await e;if(t?.(s),"granted"!==s)throw new Error("Push permission was not granted");const i=await this.getRegistration();if(this.disposed)return;let n=await i.pushManager.getSubscription();if(!this.disposed){if(n&&!this.owns(n))throw new Error("The existing Push subscription belongs to a different application");if(n||=await i.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this.applicationServerKey}),!this.disposed)return this.subscription=n,this.sync()}}unsubscribe(){return this.disposed?Promise.resolve():(this.unsubscribePromise||(this.clearRetryTimeout(),this.unsubscribePromise=this.removeSubscription().finally(()=>{this.unsubscribePromise=null})),this.unsubscribePromise)}subscriptionForSubmission(){return this.disposed||"undefined"==typeof Notification||"granted"!==Notification.permission||!this.subscription?null:{subscription:this.subscription.toJSON(),channel_id:this.channelId}}async removeSubscription(){await(this.ready?.catch(()=>{})),await(this.subscribePromise?.catch(()=>{})),await(this.syncPromise?.catch(()=>{}));const e=await this.getRegistration(),t=await e.pushManager.getSubscription()||this.subscription;if(this.disposed)return;if(!t)return Lt.eventEmitter.dispatch("push:unsubscribed"),null;if(!this.owns(t))throw new Error("The existing Push subscription belongs to a different application");this.subscription=t;const s=await I.pushIdentities.destroy({subscription:t.toJSON()});return s.failed?s:this.disposed?void 0:(await t.unsubscribe(),this.subscription=null,this.clearRetryTimeout(),Lt.eventEmitter.dispatch("push:unsubscribed"),s)}sync(){return this.disposed?Promise.resolve():(this.syncPromise||(this.clearRetryTimeout(),this.syncPromise=this.registerIdentity().finally(()=>{this.syncPromise=null})),this.syncPromise)}async registerIdentity(){try{const e=await I.pushIdentities.create({subscription:this.subscription.toJSON(),...this.channelId?{channel_id:this.channelId}:{}});return e.succeeded?this.retryAttempts=0:this.scheduleRetry(),e}catch(e){throw this.scheduleRetry(),e}}scheduleRetry(){this.disposed||this.unsubscribePromise||this.retryTimeout||this.retryAttempts>=3||(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.sync().catch(()=>{})},1e3*2**this.retryAttempts),this.retryAttempts+=1)}clearRetryTimeout(){clearTimeout(this.retryTimeout),this.retryTimeout=null}dispose(){this.disposed=!0,this.clearRetryTimeout()}get subscribed(){return!!this.subscription}get applicationServerKey(){const e=this.publicKey.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(4*Math.ceil(e.length/4),"=")),e=>e.charCodeAt(0))}owns(e){const t=e.options?.applicationServerKey;if(!t)return!1;const s=new Uint8Array(t),i=this.applicationServerKey;return s.length===i.length&&s.every((e,t)=>e===i[t])}getRegistration(){return this.registrationPromise||(this.registrationPromise=this.loadRegistration().catch(e=>{throw this.registrationPromise=null,e})),this.registrationPromise}async loadRegistration(){if(this.serviceWorkerUrl){const e=await navigator.serviceWorker.register(this.serviceWorkerUrl);!e.active||e.installing||e.waiting||await e.update();const t=e.installing||e.waiting||e.active;return"activated"===t?.state?e:new Promise((s,i)=>{const n=setTimeout(()=>r(new Error("Push service worker did not become active")),1e4),r=r=>{clearTimeout(n),t?.removeEventListener("statechange",a),r?i(r):s(e)},a=()=>{"activated"===t?.state&&r(),"redundant"===t?.state&&r(new Error("Push service worker installation failed"))};t?.addEventListener("statechange",a),a()})}return new Promise((e,t)=>{const s=setTimeout(()=>t(new Error("Push service worker is not available")),1e4);navigator.serviceWorker.ready.then(t=>{clearTimeout(s),e(t)},e=>{clearTimeout(s),t(e)})})}static get supported(){return"undefined"!=typeof window&&!0===window.isSecureContext&&"undefined"!=typeof navigator&&"serviceWorker"in navigator&&"undefined"!=typeof PushManager&&"undefined"!=typeof Notification}}class St{constructor(e,t,s){this.business=t,this.push=s,this.disposed=!1,this.showRequest=0,this.controller=null,this.suspended=!1,this.resumed=Promise.resolve(),this.element=(new DOMParser).parseFromString(e.html,"text/html").querySelector('[data-controller~="hellotext--alert"]'),this.connected=new Promise(e=>{this.resolveConnected=e}),this.onConnect=this.onConnect.bind(this),this.ready=this.render()}onConnect(e){this.controller=e.detail.controller,this.controller.alert=this,this.resolveConnected(!0)}async render(){return!!this.element&&(this.element.addEventListener("hellotext--alert:connected",this.onConnect),!(!await this.business.stylesheetLoaded||this.disposed)&&(document.body.appendChild(this.element),this.connected))}async show(e,t={}){const s=++this.showRequest;return!(!await this.ready||this.disposed||s!==this.showRequest)&&(await this.resumed,!this.disposed&&s===this.showRequest&&this.controller.show(e,t))}hide(){this.showRequest+=1,this.controller?.close()}suspend(){this.disposed||this.suspended||(this.suspended=!0,this.resumed=new Promise(e=>{this.resolveResumed=e}),this.controller?.close())}resume(){!this.disposed&&this.suspended&&(this.suspended=!1,this.resolveResumed())}dispose(){this.disposed=!0,this.hide(),this.resolveConnected(!1),this.resolveResumed?.(),this.element?.removeEventListener("hellotext--alert:connected",this.onConnect),this.element?.remove()}}class Ct{static async load(e){const t=new Ct({id:e,html:await I.webchats.get(e)});return t.rendered=t.render(),t}constructor(e){this.data=e,this.mounted=!1,this.rendered=Promise.resolve(!1)}async render(){return this.applyBehaviourOverride(),await this.stylesheetLoaded?(this.containerToAppendTo.appendChild(this.data.html),this.markCoexistingWidgets(),this.mounted=!0,!0):(console.warn("Hellotext webchat was not mounted because its stylesheet failed to load."),!1)}applyBehaviourOverride(){f.webchat.hasBehaviourOverride&&f.webchat.behaviour&&this.data.html.setAttribute("data-hellotext--webchat-behaviour-value",JSON.stringify(this.serializedBehaviour))}get serializedBehaviour(){const e=f.webchat.behaviour;return{trigger:this.serializeTrigger(e.trigger),delay_seconds:e.delaySeconds,first_visit_only:e.firstVisitOnly,once_per_session:e.oncePerSession}}serializeTrigger(e){return"onLoad"===e?"on_load":"onClick"===e?"on_click":e}get containerToAppendTo(){return document.querySelector(f.webchat.container)}get stylesheetLoaded(){return L.waitForStylesheet(L.latestStylesheet)}markCoexistingWidgets(){const e=this.data.html,t=document.querySelector(".hellotext--whatsapp-widget");e&&t&&(e.classList.add("hellotext--with-whatsapp-widget"),t.classList.add("hellotext--with-webchat"))}}class At{static async load(e){const t=new At({id:e,html:await I.whatsappWidgets.get(e)});return t.rendered=t.render(),t}constructor(e){this.data=e,this.mounted=!1,this.rendered=Promise.resolve(!1)}async render(){if(!this.data.html)return!1;const e=this.containerToAppendTo;return e?await this.stylesheetLoaded?(this.linkThroughClickEndpoint(),e.appendChild(this.data.html),this.markCoexistingWidgets(),this.mounted=!0,!0):(console.warn("Hellotext WhatsApp widget was not mounted because its stylesheet failed to load."),!1):(console.warn(`Hellotext WhatsApp widget was not mounted because the container ${f.whatsapp.container} was not found.`),!1)}linkThroughClickEndpoint(){const e=this.data.html.getAttribute("data-hellotext--whatsapp-widget-click-url-value"),t=j.session;e&&t&&this.data.html.querySelectorAll("a[href]").forEach(s=>{const i=this.clickHref(e,s.getAttribute("href"),t);i&&s.setAttribute("href",i)})}clickHref(e,t,s){try{const i=new URL(e),n=new URL(t,i);return n.origin!==i.origin||n.pathname!==i.pathname?null:(["number","text"].forEach(e=>{const t=n.searchParams.get(e);t&&i.searchParams.set(e,t)}),i.searchParams.set("session",s),i.toString())}catch(e){return null}}get containerToAppendTo(){try{return document.querySelector(f.whatsapp.container)}catch(e){return null}}get stylesheetLoaded(){return L.waitForStylesheet(L.latestStylesheet)}markCoexistingWidgets(){const e=document.querySelector(".hellotext--webchat:not(.hellotext--whatsapp-widget)"),t=this.data.html;e&&t&&(e.classList.add("hellotext--with-whatsapp-widget"),t.classList.add("hellotext--with-webchat"))}}class Et{static get id(){return _.get("hello_user_id")}static get source(){return _.get("hello_user_source")}static get fingerprint(){return _.get("hello_user_identification_hash")}static remember(e,t,s){t&&_.set("hello_user_source",t),s&&_.set("hello_user_identification_hash",s),_.set("hello_user_id",e)}static forget(){_.delete("hello_user_id"),_.delete("hello_user_source"),_.delete("hello_user_identification_hash")}static get identificationData(){return this.id?{id:this.id,source:this.source}:{}}}function Ot(e){if(null!=e){if("string"==typeof e){const t=e.trim();return""===t?void 0:t}if(Array.isArray(e))return e.map(e=>Ot(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){const t=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,s)=>{const i=Ot(e[s]);return void 0!==i&&(t[s]=i),t},{});return Object.keys(t).length>0?t:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function xt(e,t,s={}){const i=Ot({session:e,user_id:t,...s})||{};return JSON.stringify(i)}class kt{static matches(e,t){return!!e&&e===t}static async generate(e,t,s={}){return await async function(e){if(!globalThis.crypto?.subtle||"undefined"==typeof TextEncoder)return function(e){let t=5381;for(let s=0;s>>0).toString(16)}`}(e);const t=await globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e));return`v1:${Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}`}(xt(e,t,s))}}const Mt=["source","medium","campaign"],It={"product.viewed":"activity.product_viewed","cart.added":"activity.cart_added","order.placed":"activity.purchase_completed","product.purchased":"activity.purchase_completed","form.completed":"activity.form_completed"};class Pt{static eventEmitter=new r;static activities=new Set;static pageViews=1;static visitCampaign={};static visitorType="new";static visitSignalsLoaded=!1;static lastPageUrl;static lastPageRoute;static pageStartedAt;static visitStartedAt;static forms;static business;static popup;static webchat;static whatsapp;static push;static alert;static initializationVersion=0;static async initialize(e,t={}){const s=++this.initializationVersion;this.popup?.unmount?.(),this.popup=void 0,this.alert?.dispose(),this.alert=null,this.push?.dispose(),this.push=null;const i=new L(e);this.business=i,this.page=new V,f.assign({push:{},...t}),j.initialize(this.page),this.initializeVisitSignals(),this.forms?.mutationObserver?.disconnect(),this.forms=new bt,this.query=new b;const n=wt.linkedId,r=await i.hydrate();if(this.business!==i)return;!1!==t.push&&r?.push?.public_key&&Tt.supported&&(this.push=new Tt(r.push),this.push.initialize().catch(e=>{console.warn("Hellotext Push initialization failed:",e)}),r.alert?.html&&(this.alert=new St(r.alert,i,this.push)));const a=!1!==t.popup&&this.deepMergePlainObjects(r&&r.popup||{},n?{...t.popup,id:n}:t.popup||{}),o=!1!==t.webchat&&this.mergeWebchatConfig(r&&r.webchat||{},t.webchat||{}),c=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(r&&r.whatsapp||{},t.whatsappWidget||{}),l=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");f.webchat.behaviourOverride=l;const h=[];if(o&&o.id&&(f.webchat.assign(o),h.push(Ct.load(o.id).then(e=>{this.business===i&&(this.webchat=e)}))),c&&c.id&&(f.whatsapp.assign(c),h.push(At.load(c.id).then(e=>{this.business===i&&(this.whatsapp=e)}))),a&&a.id&&(n||!wt.finished(a.id))){const e={container:"body",device:"auto",...a};f.popup.assign(e);const t=this.alert;let r=!1;t?.suspend(),h.push(wt.load(e.id,{container:e.container,linked:Boolean(n),shouldMount:()=>this.business===i&&this.initializationVersion===s,onActivity:e=>{e?(r=!0,t?.suspend()):r?t?.dispose():t?.resume()}}).then(e=>{e.mounted||t?.resume(),this.business===i&&this.initializationVersion===s&&(this.popup=e)}).catch(e=>{throw t?.resume(),e}))}await Promise.all(h),this.business===i&&this.initializationVersion===s&&"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}static mergeWebchatConfig(e,t){return this.deepMergePlainObjects(e,t)}static mergeWhatsAppConfig(e,t){return this.deepMergePlainObjects(e,t)}static deepMergePlainObjects(e,t){const s={...e};return Object.entries(t).forEach(([e,t])=>{this.isPlainObject(t)&&this.isPlainObject(s[e])?s[e]=this.deepMergePlainObjects(s[e],t):s[e]=t}),s}static isPlainObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static async track(e,t={}){if(this.notInitialized)throw new yt;const s=this.business,i=this.session,n={...t&&t.headers||{},...this.headers},r={...Et.identificationData,...t.user_parameters||{}},a=t&&t.url?new V(t.url):this.page,o={session:i,user_parameters:r,action:e,...t,...a.trackingData};delete o.headers;const c=await I.events.create({headers:n,body:o,keepalive:M(o)}),l=this.trackedAtMilliseconds(t.tracked_at);return c.succeeded&&this.business===s&&this.session===i&&(null===l||l>=this.visitStartedAt)&&this.recordActivity(e),c}static recordActivity(e){const t=It[e];t&&(this.activities.add(t),this.writeStorage("sessionStorage",this.visitStorageKey("activities"),JSON.stringify([...this.activities])),this.eventEmitter.dispatch("activity:occurred",{action:e,field:t}))}static trackedAtMilliseconds(e){return null==e||""===e?null:"number"==typeof e?Number.isFinite(e)?e<1e12?1e3*e:e:Number.NaN:new Date(e).getTime()}static initializeVisitSignals(){const e=!this.visitSignalsLoaded;if(this.visitSignalsLoaded=!0,e){this.pageViews=0,this.lastPageUrl=void 0,this.lastPageRoute=void 0,this.activities=new Set(this.readStoredActivities()),this.visitCampaign=this.readStoredVisitCampaign();const e=this.readStorage("sessionStorage",this.visitStorageKey("visitor-type"));this.visitorType=["new","returning"].includes(e)?e:void 0,this.visitorType||(this.visitorType=this.readStorage("localStorage",this.visitStorageKey("seen"))?"returning":"new",this.writeStorage("sessionStorage",this.visitStorageKey("visitor-type"),this.visitorType),this.writeStorage("localStorage",this.visitStorageKey("seen"),"1"));const t=Number(this.readStorage("sessionStorage",this.visitStorageKey("started-at")));this.visitStartedAt=Number.isFinite(t)&&t>0?t:this.initialPageStartedAt(),this.writeStorage("sessionStorage",this.visitStorageKey("started-at"),String(this.visitStartedAt))}this.rememberVisitCampaign($.paramsFrom(window.location.search)),(e||this.lastPageRoute!==this.pageRoute())&&this.recordPageView()}static rememberVisitCampaign(e){const t=Object.fromEntries(Mt.flatMap(t=>{const s="string"==typeof e?.[t]?e[t].trim():"";return""===s?[]:[[t,s]]}));0!==Object.keys(t).length&&(this.visitCampaign=t,this.writeStorage("sessionStorage",this.visitStorageKey("campaign"),JSON.stringify(t)))}static readStoredVisitCampaign(){try{const e=JSON.parse(this.readStorage("sessionStorage",this.visitStorageKey("campaign"))||"{}");return null===e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([e,t])=>Mt.includes(e)&&"string"==typeof t))}catch(e){return{}}}static recordPageView(){const e=this.visitStorageKey("page-views"),t=Number(this.readStorage("sessionStorage",e)),s=!this.lastPageUrl;this.pageViews=Number.isInteger(t)&&t>0?t+1:this.pageViews+1,this.lastPageUrl=window.location.href,this.lastPageRoute=this.pageRoute(),this.pageStartedAt=s?this.initialPageStartedAt():Date.now(),this.writeStorage("sessionStorage",e,String(this.pageViews))}static initialPageStartedAt(){const e=window.performance?.getEntriesByType?.("navigation")?.[0]?.name;return e&&this.pageRoute(e)!==this.pageRoute()?Date.now():window.performance?.timeOrigin||Date.now()}static pageRoute(e=window.location.href){return V.route(e)}static readStoredActivities(){try{const e=JSON.parse(this.readStorage("sessionStorage",this.visitStorageKey("activities"))||"[]");return Array.isArray(e)?e.filter(e=>Object.values(It).includes(e)):[]}catch(e){return[]}}static visitStorageKey(e){return`hellotext:visit:${e}`}static storage(e){try{return window[e]}catch(e){return null}}static readStorage(e,t){try{return this.storage(e)?.getItem(t)}catch(e){return null}}static writeStorage(e,t,s){try{this.storage(e)?.setItem(t,s)}catch(e){}}static async identify(e,t={}){const s=await kt.generate(this.session,e,t);if(kt.matches(Et.fingerprint,s))return new v(!0,{json:async()=>({already_identified:!0})});const i=await I.identifications.create({user_id:e,...t});return i.succeeded&&Et.remember(e,t.source,s),i}static forget(){Et.forget()}static on(e,t){this.eventEmitter.addSubscriber(e,t)}static removeEventListener(e,t){this.eventEmitter.removeSubscriber(e,t)}static get session(){return j.session}static get isInitialized(){return void 0!==j.session}static get notInitialized(){return!this.business||void 0===this.business.id}static get headers(){if(this.notInitialized)throw new yt;return{Authorization:`Bearer ${this.business.id}`,Accept:"application/json","Content-Type":"application/json"}}}const Lt=Pt,_t=new Map,Nt=class extends i.xI{static values={sections:Array};static targets=["title","description","primaryAction","secondaryAction"];initialize(){this.showRequest=0,this.submitting=!1,this.registrationResumed=Promise.resolve(),this.onStorage=this.onStorage.bind(this),this.onUnsubscribed=this.onUnsubscribed.bind(this)}connect(){this.dispatch("connected",{detail:{controller:this}}),window.addEventListener("storage",this.onStorage),Lt.eventEmitter.addSubscriber("push:unsubscribed",this.onUnsubscribed),this.registrationResumed=this.resumeRegistration()}disconnect(){this.close(),window.removeEventListener("storage",this.onStorage),Lt.eventEmitter.removeSubscriber("push:unsubscribed",this.onUnsubscribed)}onUnsubscribed(){this.alert&&(this.pendingRegistration=null)}onStorage(e){e.key===this.storageKey&&this.dismissal.dismissedUntil>Date.now()&&this.close()}async show(e,{force:t=!1,title:s,description:i,primaryAction:n,secondaryAction:r}={}){const a=++this.showRequest,o=this.sectionsValue.find(t=>t.kind===e);return o?(await(this.alert.push.ready?.catch(()=>{})),await this.registrationResumed,!(a!==this.showRequest||this.alert.disposed||!this.element.isConnected||(this.unavailable||!t&&this.dismissal.dismissedUntil>Date.now()?(this.close(),1):(this.titleTarget.textContent=s??o.title,this.descriptionTarget.textContent=i??o.description,this.primaryActionTarget.textContent=n??o.primary_action,this.secondaryActionTarget.textContent=r??o.secondary_action,this.kind=e,this.page=Lt.page.trackingData.page,this.element.hidden=!1,this.record("shown"),Lt.eventEmitter.dispatch("alert:shown",{kind:e}),0)))):(this.close(),!1)}hide(){if(this.element.hidden||this.submitting)return;const e=this.dismissal.dismissals+1,t={dismissals:e,dismissedUntil:Date.now()+864e5*(1===e?7:30)};_t.set(this.storageKey,t);try{localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(e){}this.close(),this.record("dismissed"),Lt.eventEmitter.dispatch("alert:dismissed",{kind:this.kind})}close(){this.showRequest+=1,this.element.hidden=!0}async subscribe(){if(this.submitting||this.element.hidden)return;if(this.unavailable)return this.close();this.submitting=!0,this.primaryActionTarget.disabled=!0,this.secondaryActionTarget.disabled=!0,this.element.setAttribute("aria-busy","true");const e={section:this.kind,page:this.page};try{this.record("accepted"),Lt.eventEmitter.dispatch("alert:accepted",{kind:this.kind});const t=await this.alert.push.subscribe({onPermission:t=>this.recordPermission(t,e)});return t?.succeeded&&this.recordRegistration(t,e),this.unavailable&&this.close(),t?.failed&&this.dispatch("error",{detail:{response:t}}),t}catch(e){this.unavailable&&this.close(),this.dispatch("error",{detail:{error:e}})}finally{this.submitting=!1,this.primaryActionTarget.disabled=!1,this.secondaryActionTarget.disabled=!1,this.element.removeAttribute("aria-busy")}}async record(e,{section:t=this.kind,page:s=this.page,pushIdentity:i}={}){try{const n=await I.pushAlerts.create({section:t,kind:e,page:s,pushIdentity:i});n.failed&&console.warn("Hellotext Smart Alert submission failed:",n)}catch(e){console.warn("Hellotext Smart Alert submission failed:",e)}}recordPermission(e,t){"granted"===e&&(this.pendingRegistration=t),"granted"!==e&&"denied"!==e||this.record(e,t)}async recordRegistration(e,t){this.pendingRegistration=null;try{const{id:s}=await e.data.clone().json();s&&this.record("registered",{...t,pushIdentity:s})}catch(e){console.warn("Hellotext Smart Alert submission failed:",e)}}async resumeRegistration(){if(!this.alert)return;const e=this.pendingRegistration;if(e&&(await(this.alert.push.ready?.catch(()=>{})),!this.alert.disposed&&this.pendingRegistration))if("undefined"!=typeof Notification&&"granted"===Notification.permission)try{const t=await this.alert.push.subscribe();t?.succeeded&&this.recordRegistration(t,e)}catch(e){}else this.pendingRegistration=null}get pendingRegistration(){try{const e=JSON.parse(localStorage.getItem(this.registrationKey));return"string"==typeof e?.section?e:null}catch(e){return null}}set pendingRegistration(e){try{e?localStorage.setItem(this.registrationKey,JSON.stringify(e)):localStorage.removeItem(this.registrationKey)}catch(e){}}get registrationKey(){return`${this.storageKey}:registration`}get unavailable(){return this.alert.push.disposed||this.alert.push.subscribed||"undefined"==typeof Notification||"denied"===Notification.permission}get storageKey(){return`hellotext:alert:${this.alert.business.id}`}get dismissal(){try{const e=JSON.parse(localStorage.getItem(this.storageKey));Number.isSafeInteger(e?.dismissals)&&e.dismissals>0&&Number.isFinite(e.dismissedUntil)&&e.dismissedUntil>=0&&_t.set(this.storageKey,e)}catch(e){}return _t.get(this.storageKey)||{dismissals:0,dismissedUntil:0}}},Dt=class extends i.xI{static values={data:Object,step:{type:Number,default:1}};static targets=["inputContainer","input","button","otpContainer"];initialize(){this.form=new ft(this.dataValue,this.element),this.onInput=this.trackStart.bind(this)}connect(){super.connect(),this.element.addEventListener("submit",this.submit.bind(this)),this.element.addEventListener("input",this.onInput),"INPUT"!==document.activeElement.tagName&&this.inputTargets[0].focus()}disconnect(){this.element.removeEventListener("input",this.onInput)}async trackStart(){if(this.trackingStart)return;const e=`hellotext--form--${this.form.id}--tracked-start`,t=`${Lt.session}:${this.localDate}`;if(Lt.readStorage("localStorage",e)!==t){this.trackingStart=!0;try{const s=await Lt.track("form.started",{form_id:this.form.id,tracked_at:(new Date).toISOString()});s?.succeeded&&Lt.writeStorage("localStorage",e,t)}catch(e){}finally{this.trackingStart=!1}}}get localDate(){const e=new Date;return[e.getFullYear(),e.getMonth()+1,e.getDate()].map(e=>String(e).padStart(2,"0")).join("-")}async submit(e){if(e.preventDefault(),this.invalid)return this.showErrorMessages();this.clearErrorMessages(),this.formData=Object.fromEntries(new FormData(this.element)),this.buttonTarget.disabled=!0;const t=await T.submit(this.form.id,this.formData);this.buttonTarget.disabled=!1;const s=await t.json();if(t.failed)return s.errors.forEach(e=>{const{type:t,parameter:s}=e,i=this.inputTargets.find(e=>e.name===s);i.setCustomValidity(Lt.business.locale.errors[t]),i.reportValidity(),i.addEventListener("input",()=>{i.setCustomValidity(""),i.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()}completed(){if(this.form.markAsCompleted(this.formData),!f.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof f.forms.successMessage?this.element.innerHTML=f.forms.successMessage:this.element.innerHTML=Lt.business.locale.forms[this.form.localeAuthKey]}showErrorMessages(){this.inputTargets.forEach(e=>{const t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}clearErrorMessages(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}inputTargetConnected(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}get requiredInputs(){return this.inputTargets.filter(e=>e.required)}get invalid(){return!this.element.checkValidity()}},Rt=class extends i.xI{static values={fadeDistance:{type:Number,default:64},id:String,kind:String,pageStartOffset:{type:Number,default:0},utm:Object};static targets=["carouselContainer","leftFade","rightFade","carouselCard"];connect(){this.updateFades(),this.observeContainerSize()}disconnect(){this.resizeObserver?.disconnect()}setId({detail:e}){this.idValue=e,this.element.id=e}onScroll(){this.updateFades()}quickReply({currentTarget:e}){const t=e.closest('[data-hellotext--message-target="carouselCard"]'),s=e.closest('[data-controller~="hellotext--message"]'),i=e.dataset.text||e.textContent.trim();this.dispatch("quickReply",{detail:{id:this.idValue,product:t?.dataset.id,buttonId:e.dataset.id,body:i,cardElement:t||s||e}})}addToCart({currentTarget:e}){const t=e.closest('[data-hellotext--message-target="carouselCard"]'),{id:s,reference:i,source:n}=t.dataset,r={product:s,quantity:1};this.hasUtmValue&&Lt.page.utm.save(this.utmValue),Lt.eventEmitter.dispatch("cart.added",{object_parameters:{items:[{...r,...i&&{reference:i},...n&&{source:n}}]},source:{kind:this.kindValue,message_id:this.idValue,button_id:e.dataset.id}})}moveToLeft(){if(!this.hasCarouselContainerTarget)return;const e=this.getPreviousPageScrollLeft(),t=this.carouselContainerTarget.scrollLeft-e;t<1||this.carouselContainerTarget.scrollBy({left:-t,behavior:"smooth"})}moveToRight(){if(!this.hasCarouselContainerTarget)return;const e=this.getNextPageScrollLeft()-this.carouselContainerTarget.scrollLeft;e<1||this.carouselContainerTarget.scrollBy({left:e,behavior:"smooth"})}getScrollAmount(){return this.getCardScrollAmount()}getCardScrollAmount(){const e=this.carouselContainerTarget.querySelector(".message__carousel_card");return e?e.offsetWidth+this.getGap():280}getPageScrollAmount(){const e=this.carouselContainerTarget.clientWidth-this.getGap();return e>0?e:this.getCardScrollAmount()}getNextPageScrollLeft(){const e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,s=this.getCardMetrics().find(e=>e.end>t+1),i=s?this.getPageAlignedScrollLeft(s.start):e+this.getPageScrollAmount(),n=e+this.getPageScrollAmount();return this.clampScrollLeft(i>e+1?i:n)}getPreviousPageScrollLeft(){const e=this.getCurrentScrollLeft();if(e<=1)return 0;const t=Math.max(e-this.getPageScrollAmount(),0);if(t<=1)return 0;const s=this.getCardMetrics(),i=s.find(s=>s.start>=t-1&&s.startt.start{const t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}getCardScrollLeft(e){const t=e.getBoundingClientRect(),s=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||s.left||s.width?t.left-s.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}getCurrentScrollLeft(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}clampScrollLeft(e){const t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}getGap(){const e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}getFadeDistance(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}getPageStartOffset(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}observeContainerSize(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}updateFades(){if(!this.hasCarouselContainerTarget)return;const e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);const t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),s=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/s),this.setFadeOpacity(this.rightFadeTarget,(e-t)/s)}setFadeOpacity(e,t){const s=Math.min(Math.max(t,0),1);s<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=s.toFixed(3),e.style.pointerEvents="auto")}hideFade(e){e.style.opacity="0",e.style.pointerEvents="none",e.setAttribute("aria-hidden","true"),e.setAttribute("tabindex","-1"),"disabled"in e&&(e.disabled=!0),e.classList.add("hidden")}},Ft="exact",$t="contains",Bt=["contains","does_not_contain"],Vt=/^https?:\/\/[^/?#]+/i,jt=/^\/\/[^/?#]+/,qt=/^[a-z][a-z0-9+.-]*:/i,Ut=/^(?:(?:[a-z0-9-]+\.)+[a-z]{2,}|localhost)(?::\d+)?\//i,zt=/(?:%[0-9a-f]{2})+/gi,Wt=/%(?:21|23|24|25|26|27|28|29|2a|2b|2c|2f|3a|3b|3d|3f|40|5b|5d)/i,Kt=/(^|\/)index\.(?:html?|php)$/;class Ht{static EXACT=Ft;static CONTAINS=$t;static modeFor(e){return Bt.includes(e)?$t:Ft}static canonical(e,{mode:t=Ft}={}){let s=String(e??"").trim();if(""===s)return"";if(s=this.withoutOrigin(s),null===s)return"";s=this.routePath(s),s=this.decoded(s),s=s.toLowerCase().replace(/ς/g,"σ").normalize("NFC").replace(/\/{2,}/g,"/");const i=Kt.test(s);return s=s.replace(Kt,"$1"),t===$t?(i&&(s=s.replace(/\/$/,"")),"/"===s?"":s):this.resolved(s)}static withoutOrigin(e){return Vt.test(e)?e.replace(Vt,""):jt.test(e)?e.replace(jt,""):qt.test(e)||Ut.test(e)?null:e}static routePath(e){const t=e.indexOf("#"),s=(-1===t?e:e.slice(0,t)).split("?")[0],i=-1===t?"":e.slice(t+1),n=i.startsWith("/")?i:i.startsWith("!/")?i.slice(1):"";return n?`${s}/${n.split("?")[0]}`:s}static decoded(e){return e.replace(zt,e=>{const t=e.match(/%[0-9a-f]{2}/gi)??[],s=[];let i=[];const n=()=>{i.length>0&&s.push(i.join("")),i=[]};return t.forEach(e=>{Wt.test(e)?(n(),s.push(e)):i.push(e)}),n(),s.map(e=>{if(Wt.test(e))return e;try{return decodeURIComponent(e)}catch(t){return e}}).join("")})}static resolved(e){const t=[];return e.split("/").forEach(e=>{""!==e&&"."!==e&&(".."===e?t.pop():t.push(e))}),`/${t.join("/")}`}}const Gt=["does_not_contain","is_not"],Jt=["session.scroll_depth","session.time_on_page","session.page_views"],Yt=["at_least","at_most","greater_than","less_than"],Zt=["page.path","page.title","session.referrer","session.language","session.visitor_type","session.browser","session.utm_source","session.utm_medium","session.utm_campaign"],Xt=["session.utm_source","session.utm_medium","session.utm_campaign"],Qt=["activity.product_viewed","activity.cart_added","activity.purchase_completed","activity.form_completed"],es={"session.language":["en","es","pt","fr","nl"],"session.visitor_type":["new","returning"],"session.browser":["chrome","safari","firefox","edge"]},ts={"session.scroll_depth":[1,100],"session.time_on_page":[1,3600],"session.page_views":[1,1e3]},ss=["contains","does_not_contain","is","is_not"],is=["is","is_not"];class ns{constructor(e){this.valid=null!==e&&"object"==typeof e&&!Array.isArray(e)&&Array.isArray(e.lanes),this.lanes=(this.valid?e.lanes:[]).map(e=>Array.isArray(e)?e:[null])}get empty(){return this.valid&&0===this.lanes.length}get needsMeasurements(){return this.lanes.some(e=>e.some(e=>Jt.includes(e?.field)))}get needsNavigation(){return this.lanes.some(e=>e.some(e=>this.validCondition(e)))}get needsTitle(){return this.lanes.some(e=>e.some(e=>"page.title"===e?.field))}get needsActivities(){return this.lanes.some(e=>e.some(e=>Qt.includes(e?.field)))}matches(e){return!!this.valid&&(!!this.empty||this.lanes.some(t=>this.laneMatches(t,e)))}laneMatches(e,t){if(!e.every(e=>this.validCondition(e)))return!1;const s=new Map;return e.forEach(e=>{const t=s.get(e?.field)||[];t.push(e),s.set(e?.field,t)}),[...s.entries()].every(([e,s])=>this.fieldGroupMatches(e,s,t))}fieldGroupMatches(e,t,s){if(!Zt.includes(e))return t.every(e=>this.conditionMatches(e,s));const i=t.filter(e=>!Gt.includes(e?.operator)),n=t.filter(e=>Gt.includes(e?.operator));return(0===i.length||i.some(e=>this.conditionMatches(e,s)))&&n.every(e=>this.conditionMatches(e,s))}conditionMatches(e,t){if(!this.validCondition(e))return!1;if(Qt.includes(e.field))return t.activities?.has?.(e.field)||t.activities?.includes?.(e.field);const s=this.actualValue(e.field,t);return Jt.includes(e.field)?this.thresholdMatches(e,s):"page.path"===e.field?this.pathMatches(e,s,t):this.stringMatches(e,s)}actualValue(e,t){switch(e){case"page.path":return void 0===t.path||null===t.path?t.path:`${t.path}${t.hash??""}`;case"page.title":return t.title;case"session.referrer":return t.referrer;case"session.scroll_depth":return t.scrollDepth;case"session.time_on_page":return t.timeOnPage;case"session.page_views":return t.pageViews;case"session.language":return t.language;case"session.visitor_type":return t.visitorType;case"session.browser":return t.browser;case"session.utm_source":return t.utm?.source;case"session.utm_medium":return t.utm?.medium;case"session.utm_campaign":return t.utm?.campaign;default:return}}validCondition(e){if(!e||"object"!=typeof e||!Array.isArray(e.values))return!1;if(Jt.includes(e.field)){const t=e.values[0],s=Number(t),[i,n]=ts[e.field];return Yt.includes(e.operator)&&1===e.values.length&&("number"==typeof t||"string"==typeof t&&/^\d+$/.test(t))&&Number.isInteger(s)&&s>=i&&s<=n}if(Qt.includes(e.field))return"occurred"===e.operator&&0===e.values.length;const t=es[e.field]?is:ss;if(!(Zt.includes(e.field)&&t.includes(e.operator)&&e.values.length>0&&e.values.every(e=>"string"==typeof e&&e.trim().length>0&&e.length<=512)))return!1;const s=es[e.field];return!s||e.values.every(e=>s.includes(e))}thresholdMatches(e,t){if(null==t||""===t)return!1;const s=Number(t),i=Number(e.values[0]);switch(e.operator){case"at_least":return s>=i;case"at_most":return s<=i;case"greater_than":return s>i;case"less_than":return sString(e).trim().toLowerCase():e=>String(e).toLowerCase(),n=i(t),r=e.values.some(t=>this.compare(e.operator,n,i(t)));return s?!r:r}pathMatches(e,t,s){const i=Gt.includes(e.operator);if(null==t)return i;const n=Ht.modeFor(e.operator),r=e.values.map(e=>Ht.canonical(e,{mode:n}));if(r.includes(""))return!1;const a=Ht.canonical(t),o=r.some(e=>n===Ht.CONTAINS?a.includes(e):a===e);return i?!o:o}compare(e,t,s){switch(e){case"contains":case"does_not_contain":return t.includes(s);case"is":case"is_not":return t===s;case"starts_with":return t.startsWith(s);case"ends_with":return t.endsWith(s);default:return!1}}}const rs=class extends i.xI{static targets=["bubble","dialog","step","completed","input","submitButton","globalError","resendButton","changeDestinationButton","deliveryCopy","pushDeliveryCopy","noDeliveryCopy","pushRequired","pushRequiredBrowser","pushRequiredError"];static values={capture:Object,device:String,hasBubble:Boolean,id:String,linked:Boolean,rules:Object};initialize(){this.stepIndex=0,this.trackingSteps=new Set,this.resendLabel=this.hasResendButtonTarget?this.resendButtonTarget.textContent.trim():"",this.rules=new ns(this.rulesValue),this.connectedAt=this.pageStartedAt()}connect(){Lt.eventEmitter.dispatch("popup:mounted"),this.hideUnsupportedPushFields(),this.requiredPushUnavailable&&(this.dismissed=!0),this.syncRequiredPush=this.syncRequiredPush.bind(this),this.element.addEventListener("change",this.syncRequiredPush),this.trackStepStart=this.trackStepStart.bind(this),this.element.addEventListener("input",this.trackStepStart),this.syncRequiredPush(),this.requireBirthdays(),this.linkedValue||this.submissionId||!wt.finished(this.idValue)||(this.dismissed=!0),this.deviceMatches=this.matchesDevice(),this.watchNavigation(),this.watchActivities(),this.evaluateDisplay(),this.watchMeasurements(),this.reportActivity(),this.closeIfFinishedElsewhere=this.closeIfFinishedElsewhere.bind(this),window.addEventListener("storage",this.closeIfFinishedElsewhere),window.addEventListener("pageshow",this.closeIfFinishedElsewhere)}disconnect(){this.stopResendCooldown(),this.stopWatchingMeasurements(),this.stopWatchingNavigation(),this.stopWatchingActivities(),window.removeEventListener("storage",this.closeIfFinishedElsewhere),window.removeEventListener("pageshow",this.closeIfFinishedElsewhere),this.element.removeEventListener("change",this.syncRequiredPush),this.element.removeEventListener("input",this.trackStepStart),this.reportActivity(!1)}pageStartedAt(){if(Number.isFinite(Lt.pageStartedAt))return Lt.pageStartedAt;const e=window.performance?.timeOrigin;return Number.isFinite(e)&&e<=Date.now()?e:Date.now()}watchNavigation(){if(this.onNavigation)return;this.lastRoute=this.pageRoute(),this.onNavigation=()=>this.scheduleNavigationEvaluation(),window.addEventListener("popstate",this.onNavigation),window.addEventListener("hashchange",this.onNavigation),window.addEventListener("turbo:load",this.onNavigation),window.addEventListener("turbo:render",this.onNavigation),this.rules.needsTitle&&document.head&&(this.titleObserver=new MutationObserver(()=>this.scheduleNavigationEvaluation()),this.titleObserver.observe(document.head,{childList:!0,characterData:!0,subtree:!0}));const e=window.history.pushState,t=window.history.replaceState;let s=!0;this.originalPushState=e,this.originalReplaceState=t,this.stopNavigationWrapper=()=>{s=!1},this.patchedPushState=(...t)=>{const i=e.apply(window.history,t);return s&&this.scheduleNavigationEvaluation(),i},this.patchedReplaceState=(...e)=>{const i=t.apply(window.history,e);return s&&this.scheduleNavigationEvaluation(),i},window.history.pushState=this.patchedPushState,window.history.replaceState=this.patchedReplaceState}scheduleNavigationEvaluation(){this.navigationTimer||(this.navigationTimer=setTimeout(()=>{this.navigationTimer=void 0;const e=this.pageRoute();e!==this.lastRoute&&(Lt.recordPageView(),this.connectedAt=Date.now()),this.lastRoute=e,this.currentUtmParams(),this.displayed||this.reevaluateDisplay()}))}pageRoute(){return Lt.pageRoute()}stopWatchingNavigation(){this.stopNavigationWrapper?.(),this.stopNavigationWrapper=void 0,this.titleObserver?.disconnect(),this.titleObserver=void 0,this.onNavigation&&(window.removeEventListener("popstate",this.onNavigation),window.removeEventListener("hashchange",this.onNavigation),window.removeEventListener("turbo:load",this.onNavigation),window.removeEventListener("turbo:render",this.onNavigation),this.onNavigation=void 0),this.navigationTimer&&(clearTimeout(this.navigationTimer),this.navigationTimer=void 0),window.history.pushState===this.patchedPushState&&(window.history.pushState=this.originalPushState),window.history.replaceState===this.patchedReplaceState&&(window.history.replaceState=this.originalReplaceState),this.patchedPushState=void 0,this.patchedReplaceState=void 0,this.originalPushState=void 0,this.originalReplaceState=void 0}watchMeasurements(){!this.displayed&&this.rules.needsMeasurements&&(this.onScroll=()=>this.reevaluateDisplay(),window.addEventListener("scroll",this.onScroll,{passive:!0}),this.measurementTimer=setInterval(()=>this.reevaluateDisplay(),1e3))}stopWatchingMeasurements(){this.onScroll&&(window.removeEventListener("scroll",this.onScroll),this.onScroll=void 0),this.measurementTimer&&(clearInterval(this.measurementTimer),this.measurementTimer=void 0)}watchActivities(){this.displayed||!this.rules.needsActivities||this.onActivity||(this.onActivity=()=>this.reevaluateDisplay(),Lt.on("activity:occurred",this.onActivity))}stopWatchingActivities(){this.onActivity&&(Lt.removeEventListener("activity:occurred",this.onActivity),this.onActivity=void 0)}closeIfFinishedElsewhere(e){"storage"===e.type&&e.key!==wt.finishedKey(this.idValue)||("pageshow"!==e.type||e.persisted)&&(this.submissionId||this.linkedValue||this.dismissed||wt.finished(this.idValue)&&this.close())}open(e){e&&e.preventDefault(),this.hasBubbleTarget&&(this.bubbleTarget.hidden=!0),this.dialogTarget.hidden=!1,Lt.eventEmitter.dispatch("popup:opened"),this.reportActivity(),this.trackStepView()}close(e){e&&e.preventDefault(),this.dismissed=!0,wt.markFinished(this.idValue),this.dialogTarget.hidden=!0,this.hasBubbleTarget&&(this.bubbleTarget.hidden=!0),this.element.hidden=!0,Lt.eventEmitter.dispatch("popup:closed"),this.reportActivity()}closeOnEscape(e){"Escape"!==e.key||this.element.hidden||this.dialogTarget.hidden||e.defaultPrevented||e.isComposing||this.close(e)}async next(e){if(e&&e.preventDefault(),!this.advancingStep){this.advancingStep=!0;try{if(this.clearCustomValidity(),!this.currentStepValid())return void this.showErrorMessages(this.currentStepInputs);if(this.clearErrorMessages(this.currentStepInputs),await this.subscribeForPushOnCurrentStep(),this.stepIndex{e.disabled=!0});let t=!1;try{await this.subscribeForPushOnCurrentStep(),t=this.requiredPushPending;const e=this.submissionPayload(),s=await C.submit(this.idValue,e,this.idempotencyKeyFor(e));if(s.failed)return void await this.handleSubmissionError(s);const i=await s.json();t||wt.markFinished(this.idValue),this.submissionId=i.id,this.submissionVerificationState=i.verification_state,this.submissionActionToken=i.action_token,this.submissionDeliveryStatus=i.delivery_status,this.submissionDeliveryChannel=i.delivery_channel,this.submissionDestination=i.destination,this.submissionCouponPush=!0===i.coupon_push,this.resetSubmissionRequest()}catch(e){return void this.showGlobalError()}finally{this.submitting=!1,this.submitButtonTargets.forEach(e=>{e.disabled=!1}),this.syncRequiredPush()}t?this.showPushRequired():this.showCompleted()}showPushRequired(){if(!this.hasPushRequiredTarget)return this.showCompleted();this.stepTargets.forEach(e=>{e.hidden=!0}),this.completedTarget.hidden=!0,this.hasPushRequiredErrorTarget&&(this.pushRequiredErrorTarget.hidden=!0);const e=wt.browser(),t=this.pushRequiredBrowserTargets.some(t=>t.dataset.pushBrowser===e);this.pushRequiredBrowserTargets.forEach(s=>{s.hidden=s.dataset.pushBrowser!==(t?e:"other")}),this.pushRequiredTarget.hidden=!1}async retryPush(e){e&&e.preventDefault(),this.submitting||this.pushSubscriptionPromise||(this.hasPushRequiredErrorTarget&&(this.pushRequiredErrorTarget.hidden=!0),"denied"!==("undefined"==typeof Notification?"denied":Notification.permission)&&(this.pushPermissionState=null,await this.subscribeForPush(e?.currentTarget?[e.currentTarget]:[])),"granted"===this.pushPermissionState?(this.pushRequiredTarget.hidden=!0,await this.submit(),this.completedTarget.hidden&&(this.pushRequiredTarget.hidden=!1)):this.hasPushRequiredErrorTarget&&(this.pushRequiredErrorTarget.hidden=!1))}showPushLoading(e){const t=this.element.dataset.pushLoadingLabel||"Enable notifications",s=e.map(e=>({button:e,content:e.innerHTML,busy:e.getAttribute("aria-busy")})),i=document.createElement("span"),n=document.createElement("span");n.setAttribute("aria-hidden","true"),n.style.visibility="hidden";let r=0;const a=()=>{r=(r+1)%4,i.textContent=".".repeat(r),n.textContent=".".repeat(3-r)};e.forEach(e=>{e.replaceChildren(document.createTextNode(t),i,n),e.setAttribute("aria-busy","true")}),a();const o=setInterval(a,450);return()=>{clearInterval(o),s.forEach(({button:e,content:t,busy:s})=>{!function(e,t){e.replaceChildren(mt(t,pt))}(e,t),null===s?e.removeAttribute("aria-busy"):e.setAttribute("aria-busy",s)})}}async subscribeForPushOnCurrentStep(){if(!this.currentStepInputs.some(e=>"push"===e.dataset.popupFieldKind&&e.checked)||this.pushPermissionState)return;const e=this.stepTargets[this.stepIndex]?.querySelectorAll('[data-hellotext--popup-target~="submitButton"], [data-action~="click->hellotext--popup#next"]')||[];return this.subscribeForPush(Array.from(e))}async subscribeForPush(e){if(!Lt.push)return;if(this.pushSubscriptionPromise)return this.pushSubscriptionPromise;const t=e.map(e=>({button:e,disabled:e.disabled}));t.forEach(({button:e})=>{e.disabled=!0});const s=this.showPushLoading(t.map(({button:e})=>e)),i="undefined"==typeof Notification?"default":Notification.permission;let n,r;try{n=Lt.push.subscribe()}catch(e){return this.pushPermissionState="denied"===i?"denied":"registration_failed",s(),void t.forEach(({button:e,disabled:t})=>{e.disabled=t})}const a=new Promise(e=>{r=setTimeout(()=>{this.pushPermissionState||="registration_failed",e()},15e3)}),o=n.then(e=>{this.pushPermissionState=e?.failed?"registration_failed":"undefined"!=typeof Notification&&"granted"===Notification.permission?"granted":"denied"===i?"denied":"dismissed"}).catch(()=>{this.pushPermissionState="undefined"!=typeof Notification&&"denied"===Notification.permission?"denied":"undefined"!=typeof Notification&&"default"===Notification.permission?"dismissed":"registration_failed"});return this.pushSubscriptionPromise=Promise.race([o,a]).finally(()=>{clearTimeout(r),s(),t.forEach(({button:e,disabled:t})=>{e.disabled=t}),this.pushSubscriptionPromise=null}),this.pushSubscriptionPromise}get requiredPushUnavailable(){return this.inputTargets.some(e=>"push"===e.dataset.popupFieldKind&&e.required&&e.disabled)}get requiredPushPending(){return this.inputTargets.some(e=>"push"===e.dataset.popupFieldKind&&e.required&&!e.disabled&&e.checked)&&"granted"!==this.pushPermissionState}syncRequiredPush(){this.submitting||this.pushSubscriptionPromise||this.stepTargets.forEach(e=>{const t=this.inputsForStep(e).some(e=>"push"===e.dataset.popupFieldKind&&e.required&&!e.disabled&&!e.checked);e.querySelectorAll('[data-hellotext--popup-target~="submitButton"], [data-action~="click->hellotext--popup#next"]').forEach(e=>{e.disabled=t})})}hideUnsupportedPushFields(){this.inputTargets.filter(e=>"push"===e.dataset.popupFieldKind).forEach(e=>{if("true"===e.dataset.popupPushAvailable&&Lt.push)return;e.checked=!1,e.disabled=!0;const t=e.closest(".hellotext--popup-field")||e.parentElement;t&&(t.hidden=!0)})}reevaluateDisplay(){const e=this.displayed;this.evaluateDisplay(),this.displayed&&!e&&this.reportActivity()}evaluateDisplay(){this.dismissed||!this.linkedValue&&!this.deviceMatches?this.element.hidden=!0:this.displayed||(this.linkedValue||this.rules.matches(this.pageContext())?(this.displayed=!0,this.stopWatchingMeasurements(),this.stopWatchingActivities(),this.showInitialState()):this.element.hidden=!0)}pageContext(){return{url:window.location.href,path:window.location.pathname,hash:window.location.hash,title:document.title,referrer:document.referrer||void 0,scrollDepth:this.scrollDepth(),timeOnPage:Math.floor((Date.now()-this.connectedAt)/1e3),pageViews:Lt.pageViews,language:this.browserLanguage(),visitorType:Lt.visitorType,browser:this.browserName(),utm:this.currentUtmParams(),activities:Lt.activities}}currentUtmParams(){const e=window.location.hash.match(/^#!?\/[^?]*\?(.*)$/)?.[1],t=this.popupUtmParams($.paramsFrom(e)),s=this.popupUtmParams($.paramsFrom(window.location.search)),i=Object.keys(s).length>0?s:t;return Object.keys(i).length>0?(Lt.rememberVisitCampaign(i),i):this.popupUtmParams(Lt.visitCampaign)}popupUtmParams(e){return Object.fromEntries(Object.entries(e||{}).flatMap(([e,t])=>["source","medium","campaign"].includes(e)&&"string"==typeof t?""===t.trim()?[]:[[e,t.trim()]]:[]))}browserName(){const e=window.navigator.userAgentData?.brands;if(Array.isArray(e)){const t=e.map(({brand:e})=>e?.toLowerCase()||"");if(t.some(e=>e.includes("edge")))return"edge";if(t.some(e=>e.includes("opera")||e.includes("samsung")))return;if(t.some(e=>e.includes("chrome")))return"chrome"}const t=window.navigator.userAgent?.toLowerCase()||"";return/edg([ea]|ios)?\//.test(t)?"edge":t.includes("opr/")||t.includes("opera/")||t.includes("samsungbrowser/")?void 0:t.includes("firefox/")||t.includes("fxios/")?"firefox":t.includes("chrome/")||t.includes("crios/")?"chrome":t.includes("safari/")?"safari":void 0}browserLanguage(){const e=window.navigator.languages?.[0]||window.navigator.language;return e?.split("-")[0]?.toLowerCase()}scrollDepth(){const e=Math.max(document.documentElement.scrollHeight,window.innerHeight),t=window.scrollY+window.innerHeight;return Math.max(0,Math.min(100,Math.round(t/e*100)))}showInitialState(){if(this.element.hidden=!1,this.hasBubbleValue&&this.hasBubbleTarget&&!this.linkedValue)return this.bubbleTarget.hidden=!1,void(this.dialogTarget.hidden=!0);this.hasBubbleTarget&&(this.bubbleTarget.hidden=!0),this.dialogTarget.hidden=!1,Lt.eventEmitter.dispatch("popup:opened"),this.trackStepView()}showStep(e){this.stepIndex=e,this.stepTargets.forEach((t,s)=>{t.hidden=s!==e}),this.completedTarget.hidden=!0,this.hasPushRequiredTarget&&(this.pushRequiredTarget.hidden=!0),this.reportActivity(),this.trackStepView()}showCompleted(){this.stepTargets.forEach(e=>{e.hidden=!0}),this.interpolateCompletionCopy(),this.configureCompletionActions(),this.hasPushRequiredTarget&&(this.pushRequiredTarget.hidden=!0),this.completedTarget.hidden=!1,this.reportActivity()}trackStepView(){this.element.hidden||this.dialogTarget.hidden||!this.completedTarget.hidden||this.trackStep("popup.step_viewed",this.stepTargets[this.stepIndex])}trackStepStart(e){const t=e.target?.dataset?.popupStepId;t&&this.trackStep("popup.step_started",this.stepTargets.find(e=>e.dataset.stepId===t))}async trackStep(e,t){const s=t?.dataset.stepId;if(!s)return;const i=`hellotext--popup--${this.idValue}--${s}--${e}`,n=`${Lt.session}:${this.localDate}`;if(!this.trackingSteps.has(i)&&Lt.readStorage("localStorage",i)!==n){this.trackingSteps.add(i);try{const t=await Lt.track(e,{popup_id:this.idValue,step_id:s,tracked_at:(new Date).toISOString()});t?.succeeded&&Lt.writeStorage("localStorage",i,n)}catch(e){}finally{this.trackingSteps.delete(i)}}}get localDate(){const e=new Date;return[e.getFullYear(),e.getMonth()+1,e.getDate()].map(e=>String(e).padStart(2,"0")).join("-")}reportActivity(e=!this.element.hidden&&!this.dialogTarget.hidden&&this.completedTarget.hidden){this.element.dispatchEvent(new CustomEvent("hellotext--popup:activity",{bubbles:!0,detail:{active:e}}))}interpolateCompletionCopy(){const e=this.completedIdentity;if(!e)return;const t={destination:e.value,channel:this.completionChannelLabel(this.submissionDeliveryChannel||e.kind)};this.completionTextTemplates.forEach(({node:e,template:s})=>{e.nodeValue=s.replace(/\{(destination|channel)\}/g,(e,s)=>t[s]||e)})}completionChannelLabel(e){return this.element.dataset[`channelLabel${e[0]?.toUpperCase()}${e.slice(1)}`]||e}identityValue(e){const t=this.inputValue(e).trim();if(!t)return"";if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;const s=this.phoneCountryPrefix(e);if(s)return`${s}${this.phoneDigits(t)}`;const i=e.dataset.popupPhonePrefix;return i?`${i}${t.replace(/^0+/,"")}`:t}asciiDigits(e){const t=e=>/\p{Nd}/u.test(e);return e.replace(/\p{Nd}/gu,e=>{let s=e.codePointAt(0);const i=s;for(;t(String.fromCodePoint(s-1));)s-=1;return(i-s)%10})}phoneDigits(e){return this.asciiDigits(e).replace(/\D/g,"")}phoneCountryPrefix(e){const t=e.closest("[data-popup-phone]")?.querySelector("[data-popup-phone-country]");return t?.selectedOptions?.[0]?.dataset.prefix}selectPhoneCountry(e){const t=e.target,s=t.closest("[data-popup-phone]")?.querySelector("[data-popup-phone-country-label]");s&&(s.textContent=t.selectedOptions[0]?.dataset.label||"")}filterPhone(e){const t=e.target,s=t.value.replace(/[^\p{Nd}+() .\-]/gu,"");s!==t.value&&(t.value=s)}requireBirthdays(){this.element.querySelectorAll("[data-popup-birthday]").forEach(e=>{const t=e.querySelector('[data-popup-field-kind="birthday"]');t&&(t.required=Boolean(e.querySelector("select[required]")))})}selectBirthday(e){const t=e.target.closest("[data-popup-birthday]"),s=t?.querySelector('[data-popup-field-kind="birthday"]');if(!s)return;const[i,n,r]=["day","month","year"].map(e=>t.querySelector(`[data-popup-birthday-part="${e}"]`)),a=n.value?new Date(Date.UTC(Number(r.value)||2e3,Number(n.value),0)).getUTCDate():31;Array.from(i.options).forEach(e=>{e.value&&(e.disabled=Number(e.value)>a)}),Number(i.value)>a&&(i.value=""),s.value=i.value&&n.value&&r.value?`${r.value}-${n.value}-${i.value}`:""}submissionValue(e){const t=this.inputValue(e),s="phone"===e.dataset.popupFieldKind&&this.phoneCountryPrefix(e),i="string"==typeof t?t.trim():"";return s&&i?i.startsWith("+")?this.asciiDigits(t):`${s}${this.phoneDigits(i)}`:t}configureCompletionActions(){const e="not_required"!==this.submissionDeliveryStatus;if(this.revealCompletionCopy(e),!e)return void this.completedTarget.querySelector("[data-delivery-actions]")?.setAttribute("hidden","");const t=this.completedIdentity;t&&(this.hasChangeDestinationButtonTarget&&(this.changeDestinationButtonTarget.textContent=this.changeDestinationButtonTarget.dataset[`${t.kind}Label`],this.changeDestinationButtonTarget.hidden=!1),this.submissionId&&this.submissionActionToken&&"queued"===this.submissionDeliveryStatus&&"unverified"===this.submissionVerificationState&&this.hasResendButtonTarget&&(this.resendButtonTarget.hidden=!1,this.startResendCooldown(60)))}async resend(e){if(e&&e.preventDefault(),this.submissionId&&this.submissionActionToken&&!this.resendPending&&!this.resendCooldownActive&&this.completedIdentity){this.resendPending=!0,this.resendButtonTarget.disabled=!0;try{const e=await C.resend(this.idValue,this.submissionId,this.submissionActionToken),t=Number(e.data.headers?.get("Retry-After"))||60;e.succeeded||429===e.data.status?this.startResendCooldown(t):this.resendButtonTarget.disabled=!1}catch(e){this.resendButtonTarget.disabled=!1}finally{this.resendPending=!1}}}async changeDestination(e){if(e&&e.preventDefault(),!this.submissionId||!this.submissionActionToken||this.changeDestinationPending)return;const t=this.completedIdentity?.input;if(!t)return;const s=this.stepTargets.findIndex(e=>e.dataset.stepId===t.dataset.popupStepId);if(!(s<0)){this.changeDestinationPending=!0,this.changeDestinationButtonTarget.disabled=!0;try{if((await C.cancel(this.idValue,this.submissionId,this.submissionActionToken)).failed)return;wt.forgetFinished(this.idValue),this.stopResendCooldown(),this.submissionId=null,this.submissionActionToken=null,this.submissionVerificationState=null,this.submissionDeliveryStatus=null,this.submissionDeliveryChannel=null,this.submissionDestination=null,this.submissionCouponPush=!1,this.resetSubmissionRequest(),this.showStep(s),t.focus()}catch(e){}finally{this.changeDestinationPending=!1,this.changeDestinationButtonTarget.disabled=!1}}}startResendCooldown(e){this.stopResendCooldown(),this.resendCooldownEndsAt=Date.now()+1e3*Math.max(e,1),this.updateResendCountdown(),this.resendTimer=window.setInterval(()=>this.updateResendCountdown(),1e3)}stopResendCooldown(){this.resendTimer&&window.clearInterval(this.resendTimer),this.resendTimer=null,this.resendCooldownEndsAt=null}updateResendCountdown(){const e=Math.max(0,Math.ceil((this.resendCooldownEndsAt-Date.now())/1e3));if(0===e)return this.stopResendCooldown(),this.resendButtonTarget.textContent=this.resendLabel,void(this.resendButtonTarget.disabled=!1);const t=`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`,s=this.resendButtonTarget.dataset.countdownLabel||`${this.resendLabel} %{time}`;this.resendButtonTarget.textContent=s.replace("%{time}",t),this.resendButtonTarget.disabled=!0}get resendCooldownActive(){return this.resendCooldownEndsAt>Date.now()}get completionIdentity(){return this.identityInputs.map(e=>({input:e,kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(({value:e})=>e)}get completedIdentity(){if(this.submissionDestination&&this.submissionDeliveryChannel){const e="email"===this.submissionDeliveryChannel?"email":"phone";return{input:this.identityInputs.find(t=>t.dataset.popupFieldKind===e),kind:e,value:this.submissionDestination}}return this.completionIdentity}revealCompletionCopy(e){const t=e&&!0===this.submissionCouponPush;this.hasDeliveryCopyTarget&&this.deliveryCopyTargets.forEach(s=>{s.hidden=!e||t}),this.hasPushDeliveryCopyTarget&&this.pushDeliveryCopyTargets.forEach(e=>{e.hidden=!t}),this.hasNoDeliveryCopyTarget&&this.noDeliveryCopyTargets.forEach(t=>{t.hidden=e})}currentStepValid(){return this.currentStepInputs.every(e=>e.checkValidity())}showErrorMessages(e){e.forEach(e=>{const t=e.closest(".hellotext--popup-field")?.querySelector("[data-error-container]");t&&(t.textContent=e.validity.valid?"":e.validationMessage)})}clearErrorMessages(e=this.inputTargets){e.forEach(e=>{const t=e.closest(".hellotext--popup-field")?.querySelector("[data-error-container]");t&&(t.textContent="")})}clearCustomValidity(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}clearGlobalError(){this.hasGlobalErrorTarget&&(this.globalErrorTarget.textContent="",this.globalErrorTarget.hidden=!0)}showGlobalError(e=null){this.hasGlobalErrorTarget&&(this.globalErrorTarget.textContent=e||this.globalErrorTarget.dataset.submitError||"Unable to submit. Please try again.",this.globalErrorTarget.hidden=!1)}async handleSubmissionError(e){let t;try{t=await e.json()}catch(e){return void this.showGlobalError()}const s=t.errors||[],i=[],n=[];s.forEach(e=>{const t=this.inputForError(e);t?(t.setCustomValidity(e.description||t.validationMessage),n.push(t)):e.description&&i.push(e.description)});const r=this.stepTargets.findIndex(e=>n.some(t=>this.inputsForStep(e).includes(t)));r>=0&&this.showStep(r),n.forEach(e=>e.reportValidity()),this.showErrorMessages(this.inputTargets),i.length?this.showGlobalError(i.join(" ")):s.length||this.showGlobalError()}inputForError(e){const t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}submissionPayload(){const e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{const s={};this.inputsForStep(t).forEach(t=>{const i=this.submissionValue(t),n=t.dataset.popupFieldKey||t.name;s[n]=i,e.metadata.fields[n]=i,"email"===t.dataset.popupFieldKind&&(e.email=i),"phone"===t.dataset.popupFieldKind&&(e.phone=i)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:s})}),this.inputTargets.some(e=>"push"===e.dataset.popupFieldKind&&e.checked)&&(e.metadata.push_subscription=Lt.push?.subscriptionForSubmission()||null,e.metadata.push_permission=this.pushPermissionState||"unavailable"),e}idempotencyKeyFor(e){const t=JSON.stringify(e);return this.submissionPayloadSnapshot!==t&&(this.submissionPayloadSnapshot=t,this.submissionIdempotencyKey=C.idempotencyKey()),this.submissionIdempotencyKey}resetSubmissionRequest(){this.submissionPayloadSnapshot=null,this.submissionIdempotencyKey=null}inputValue(e){return"checkbox"===e.type?e.checked:e.value}inputsForStep(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}get identityInputs(){const e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}get completionTextTemplates(){if(this._completionTextTemplates)return this._completionTextTemplates;const e=document.createTreeWalker(this.completedTarget,NodeFilter.SHOW_TEXT);for(this._completionTextTemplates=[];e.nextNode();)this._completionTextTemplates.push({node:e.currentNode,template:e.currentNode.nodeValue});return this._completionTextTemplates}matchesDevice(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}get currentStep(){return this.stepTargets[this.stepIndex]}get currentStepInputs(){return this.inputsForStep(this.currentStep)}},as=["start","end"],os=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+as[0],t+"-"+as[1]),[]),cs=Math.min,ls=Math.max,hs=Math.round,us=Math.floor,ds=e=>({x:e,y:e}),ps={left:"right",right:"left",bottom:"top",top:"bottom"},ms={start:"end",end:"start"};function gs(e,t,s){return ls(e,cs(t,s))}function fs(e,t){return"function"==typeof e?e(t):e}function ys(e){return e.split("-")[0]}function bs(e){return e.split("-")[1]}function vs(e){return"x"===e?"y":"x"}function ws(e){return"y"===e?"height":"width"}const Ts=new Set(["top","bottom"]);function Ss(e){return Ts.has(ys(e))?"y":"x"}function Cs(e){return vs(Ss(e))}function As(e,t,s){void 0===s&&(s=!1);const i=bs(e),n=Cs(e),r=ws(n);let a="x"===n?i===(s?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[r]>t.floating[r]&&(a=Is(a)),[a,Is(a)]}function Es(e){return e.replace(/start|end/g,e=>ms[e])}const Os=["left","right"],xs=["right","left"],ks=["top","bottom"],Ms=["bottom","top"];function Is(e){return e.replace(/left|right|bottom|top/g,e=>ps[e])}function Ps(e){const{x:t,y:s,width:i,height:n}=e;return{width:i,height:n,top:s,left:t,right:t+i,bottom:s+n,x:t,y:s}}function Ls(e,t,s){let{reference:i,floating:n}=e;const r=Ss(t),a=Cs(t),o=ws(a),c=ys(t),l="y"===r,h=i.x+i.width/2-n.width/2,u=i.y+i.height/2-n.height/2,d=i[o]/2-n[o]/2;let p;switch(c){case"top":p={x:h,y:i.y-n.height};break;case"bottom":p={x:h,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:u};break;case"left":p={x:i.x-n.width,y:u};break;default:p={x:i.x,y:i.y}}switch(bs(t)){case"start":p[a]-=d*(s&&l?-1:1);break;case"end":p[a]+=d*(s&&l?-1:1)}return p}async function _s(e,t){var s;void 0===t&&(t={});const{x:i,y:n,platform:r,rects:a,elements:o,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:h="viewport",elementContext:u="floating",altBoundary:d=!1,padding:p=0}=fs(t,e),m=function(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}(p),g=o[d?"floating"===u?"reference":"floating":u],f=Ps(await r.getClippingRect({element:null==(s=await(null==r.isElement?void 0:r.isElement(g)))||s?g:g.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(o.floating)),boundary:l,rootBoundary:h,strategy:c})),y="floating"===u?{x:i,y:n,width:a.floating.width,height:a.floating.height}:a.reference,b=await(null==r.getOffsetParent?void 0:r.getOffsetParent(o.floating)),v=await(null==r.isElement?void 0:r.isElement(b))&&await(null==r.getScale?void 0:r.getScale(b))||{x:1,y:1},w=Ps(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:y,offsetParent:b,strategy:c}):y);return{top:(f.top-w.top+m.top)/v.y,bottom:(w.bottom-f.bottom+m.bottom)/v.y,left:(f.left-w.left+m.left)/v.x,right:(w.right-f.right+m.right)/v.x}}const Ns=new Set(["left","top"]);function Ds(){return"undefined"!=typeof window}function Rs(e){return Bs(e)?(e.nodeName||"").toLowerCase():"#document"}function Fs(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function $s(e){var t;return null==(t=(Bs(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Bs(e){return!!Ds()&&(e instanceof Node||e instanceof Fs(e).Node)}function Vs(e){return!!Ds()&&(e instanceof Element||e instanceof Fs(e).Element)}function js(e){return!!Ds()&&(e instanceof HTMLElement||e instanceof Fs(e).HTMLElement)}function qs(e){return!(!Ds()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Fs(e).ShadowRoot)}const Us=new Set(["inline","contents"]);function zs(e){const{overflow:t,overflowX:s,overflowY:i,display:n}=si(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+s)&&!Us.has(n)}const Ws=new Set(["table","td","th"]);function Ks(e){return Ws.has(Rs(e))}const Hs=[":popover-open",":modal"];function Gs(e){return Hs.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const Js=["transform","translate","scale","rotate","perspective"],Ys=["transform","translate","scale","rotate","perspective","filter"],Zs=["paint","layout","strict","content"];function Xs(e){const t=Qs(),s=Vs(e)?si(e):e;return Js.some(e=>!!s[e]&&"none"!==s[e])||!!s.containerType&&"normal"!==s.containerType||!t&&!!s.backdropFilter&&"none"!==s.backdropFilter||!t&&!!s.filter&&"none"!==s.filter||Ys.some(e=>(s.willChange||"").includes(e))||Zs.some(e=>(s.contain||"").includes(e))}function Qs(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const ei=new Set(["html","body","#document"]);function ti(e){return ei.has(Rs(e))}function si(e){return Fs(e).getComputedStyle(e)}function ii(e){return Vs(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ni(e){if("html"===Rs(e))return e;const t=e.assignedSlot||e.parentNode||qs(e)&&e.host||$s(e);return qs(t)?t.host:t}function ri(e){const t=ni(e);return ti(t)?e.ownerDocument?e.ownerDocument.body:e.body:js(t)&&zs(t)?t:ri(t)}function ai(e,t,s){var i;void 0===t&&(t=[]),void 0===s&&(s=!0);const n=ri(e),r=n===(null==(i=e.ownerDocument)?void 0:i.body),a=Fs(n);if(r){const e=oi(a);return t.concat(a,a.visualViewport||[],zs(n)?n:[],e&&s?ai(e):[])}return t.concat(n,ai(n,[],s))}function oi(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ci(e){const t=si(e);let s=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const n=js(e),r=n?e.offsetWidth:s,a=n?e.offsetHeight:i,o=hs(s)!==r||hs(i)!==a;return o&&(s=r,i=a),{width:s,height:i,$:o}}function li(e){return Vs(e)?e:e.contextElement}function hi(e){const t=li(e);if(!js(t))return ds(1);const s=t.getBoundingClientRect(),{width:i,height:n,$:r}=ci(t);let a=(r?hs(s.width):s.width)/i,o=(r?hs(s.height):s.height)/n;return a&&Number.isFinite(a)||(a=1),o&&Number.isFinite(o)||(o=1),{x:a,y:o}}const ui=ds(0);function di(e){const t=Fs(e);return Qs()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ui}function pi(e,t,s,i){void 0===t&&(t=!1),void 0===s&&(s=!1);const n=e.getBoundingClientRect(),r=li(e);let a=ds(1);t&&(i?Vs(i)&&(a=hi(i)):a=hi(e));const o=function(e,t,s){return void 0===t&&(t=!1),!(!s||t&&s!==Fs(e))&&t}(r,s,i)?di(r):ds(0);let c=(n.left+o.x)/a.x,l=(n.top+o.y)/a.y,h=n.width/a.x,u=n.height/a.y;if(r){const e=Fs(r),t=i&&Vs(i)?Fs(i):i;let s=e,n=oi(s);for(;n&&i&&t!==s;){const e=hi(n),t=n.getBoundingClientRect(),i=si(n),r=t.left+(n.clientLeft+parseFloat(i.paddingLeft))*e.x,a=t.top+(n.clientTop+parseFloat(i.paddingTop))*e.y;c*=e.x,l*=e.y,h*=e.x,u*=e.y,c+=r,l+=a,s=Fs(n),n=oi(s)}}return Ps({width:h,height:u,x:c,y:l})}function mi(e,t){const s=ii(e).scrollLeft;return t?t.left+s:pi($s(e)).left+s}function gi(e,t,s){void 0===s&&(s=!1);const i=e.getBoundingClientRect();return{x:i.left+t.scrollLeft-(s?0:mi(e,i)),y:i.top+t.scrollTop}}const fi=new Set(["absolute","fixed"]);function yi(e,t,s){let i;if("viewport"===t)i=function(e,t){const s=Fs(e),i=$s(e),n=s.visualViewport;let r=i.clientWidth,a=i.clientHeight,o=0,c=0;if(n){r=n.width,a=n.height;const e=Qs();(!e||e&&"fixed"===t)&&(o=n.offsetLeft,c=n.offsetTop)}return{width:r,height:a,x:o,y:c}}(e,s);else if("document"===t)i=function(e){const t=$s(e),s=ii(e),i=e.ownerDocument.body,n=ls(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),r=ls(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let a=-s.scrollLeft+mi(e);const o=-s.scrollTop;return"rtl"===si(i).direction&&(a+=ls(t.clientWidth,i.clientWidth)-n),{width:n,height:r,x:a,y:o}}($s(e));else if(Vs(t))i=function(e,t){const s=pi(e,!0,"fixed"===t),i=s.top+e.clientTop,n=s.left+e.clientLeft,r=js(e)?hi(e):ds(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:n*r.x,y:i*r.y}}(t,s);else{const s=di(e);i={x:t.x-s.x,y:t.y-s.y,width:t.width,height:t.height}}return Ps(i)}function bi(e,t){const s=ni(e);return!(s===t||!Vs(s)||ti(s))&&("fixed"===si(s).position||bi(s,t))}function vi(e,t,s){const i=js(t),n=$s(t),r="fixed"===s,a=pi(e,!0,r,t);let o={scrollLeft:0,scrollTop:0};const c=ds(0);function l(){c.x=mi(n)}if(i||!i&&!r)if(("body"!==Rs(t)||zs(n))&&(o=ii(t)),i){const e=pi(t,!0,r,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else n&&l();r&&!i&&n&&l();const h=!n||i||r?ds(0):gi(n,o);return{x:a.left+o.scrollLeft-c.x-h.x,y:a.top+o.scrollTop-c.y-h.y,width:a.width,height:a.height}}function wi(e){return"static"===si(e).position}function Ti(e,t){if(!js(e)||"fixed"===si(e).position)return null;if(t)return t(e);let s=e.offsetParent;return $s(e)===s&&(s=s.ownerDocument.body),s}function Si(e,t){const s=Fs(e);if(Gs(e))return s;if(!js(e)){let t=ni(e);for(;t&&!ti(t);){if(Vs(t)&&!wi(t))return t;t=ni(t)}return s}let i=Ti(e,t);for(;i&&Ks(i)&&wi(i);)i=Ti(i,t);return i&&ti(i)&&wi(i)&&!Xs(i)?s:i||function(e){let t=ni(e);for(;js(t)&&!ti(t);){if(Xs(t))return t;if(Gs(t))return null;t=ni(t)}return null}(e)||s}const Ci={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:s,offsetParent:i,strategy:n}=e;const r="fixed"===n,a=$s(i),o=!!t&&Gs(t.floating);if(i===a||o&&r)return s;let c={scrollLeft:0,scrollTop:0},l=ds(1);const h=ds(0),u=js(i);if((u||!u&&!r)&&(("body"!==Rs(i)||zs(a))&&(c=ii(i)),js(i))){const e=pi(i);l=hi(i),h.x=e.x+i.clientLeft,h.y=e.y+i.clientTop}const d=!a||u||r?ds(0):gi(a,c,!0);return{width:s.width*l.x,height:s.height*l.y,x:s.x*l.x-c.scrollLeft*l.x+h.x+d.x,y:s.y*l.y-c.scrollTop*l.y+h.y+d.y}},getDocumentElement:$s,getClippingRect:function(e){let{element:t,boundary:s,rootBoundary:i,strategy:n}=e;const r=[..."clippingAncestors"===s?Gs(t)?[]:function(e,t){const s=t.get(e);if(s)return s;let i=ai(e,[],!1).filter(e=>Vs(e)&&"body"!==Rs(e)),n=null;const r="fixed"===si(e).position;let a=r?ni(e):e;for(;Vs(a)&&!ti(a);){const t=si(a),s=Xs(a);s||"fixed"!==t.position||(n=null),(r?!s&&!n:!s&&"static"===t.position&&n&&fi.has(n.position)||zs(a)&&!s&&bi(e,a))?i=i.filter(e=>e!==a):n=t,a=ni(a)}return t.set(e,i),i}(t,this._c):[].concat(s),i],a=r[0],o=r.reduce((e,s)=>{const i=yi(t,s,n);return e.top=ls(i.top,e.top),e.right=cs(i.right,e.right),e.bottom=cs(i.bottom,e.bottom),e.left=ls(i.left,e.left),e},yi(t,a,n));return{width:o.right-o.left,height:o.bottom-o.top,x:o.left,y:o.top}},getOffsetParent:Si,getElementRects:async function(e){const t=this.getOffsetParent||Si,s=this.getDimensions,i=await s(e.floating);return{reference:vi(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:s}=ci(e);return{width:t,height:s}},getScale:hi,isElement:Vs,isRTL:function(e){return"rtl"===si(e).direction}};function Ai(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const Ei=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var s,i;const{x:n,y:r,placement:a,middlewareData:o}=t,c=await async function(e,t){const{placement:s,platform:i,elements:n}=e,r=await(null==i.isRTL?void 0:i.isRTL(n.floating)),a=ys(s),o=bs(s),c="y"===Ss(s),l=Ns.has(a)?-1:1,h=r&&c?-1:1,u=fs(t,e);let{mainAxis:d,crossAxis:p,alignmentAxis:m}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return o&&"number"==typeof m&&(p="end"===o?-1*m:m),c?{x:p*h,y:d*l}:{x:d*l,y:p*h}}(t,e);return a===(null==(s=o.offset)?void 0:s.placement)&&null!=(i=o.arrow)&&i.alignmentOffset?{}:{x:n+c.x,y:r+c.y,data:{...c,placement:a}}}}},Oi=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:s,y:i,placement:n}=t,{mainAxis:r=!0,crossAxis:a=!1,limiter:o={fn:e=>{let{x:t,y:s}=e;return{x:t,y:s}}},...c}=fs(e,t),l={x:s,y:i},h=await _s(t,c),u=Ss(ys(n)),d=vs(u);let p=l[d],m=l[u];if(r){const e="y"===d?"bottom":"right";p=gs(p+h["y"===d?"top":"left"],p,p-h[e])}if(a){const e="y"===u?"bottom":"right";m=gs(m+h["y"===u?"top":"left"],m,m-h[e])}const g=o.fn({...t,[d]:p,[u]:m});return{...g,data:{x:g.x-s,y:g.y-i,enabled:{[d]:r,[u]:a}}}}}},xi=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var s,i;const{placement:n,middlewareData:r,rects:a,initialPlacement:o,platform:c,elements:l}=t,{mainAxis:h=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...f}=fs(e,t);if(null!=(s=r.arrow)&&s.alignmentOffset)return{};const y=ys(n),b=Ss(o),v=ys(o)===o,w=await(null==c.isRTL?void 0:c.isRTL(l.floating)),T=d||(v||!g?[Is(o)]:function(e){const t=Is(e);return[Es(e),t,Es(t)]}(o)),S="none"!==m;!d&&S&&T.push(...function(e,t,s,i){const n=bs(e);let r=function(e,t,s){switch(e){case"top":case"bottom":return s?t?xs:Os:t?Os:xs;case"left":case"right":return t?ks:Ms;default:return[]}}(ys(e),"start"===s,i);return n&&(r=r.map(e=>e+"-"+n),t&&(r=r.concat(r.map(Es)))),r}(o,g,m,w));const C=[o,...T],A=await _s(t,f),E=[];let O=(null==(i=r.flip)?void 0:i.overflows)||[];if(h&&E.push(A[y]),u){const e=As(n,a,w);E.push(A[e[0]],A[e[1]])}if(O=[...O,{placement:n,overflows:E}],!E.every(e=>e<=0)){var x,k;const e=((null==(x=r.flip)?void 0:x.index)||0)+1,t=C[e];if(t&&("alignment"!==u||b===Ss(t)||O.every(e=>Ss(e.placement)!==b||e.overflows[0]>0)))return{data:{index:e,overflows:O},reset:{placement:t}};let s=null==(k=O.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!s)switch(p){case"bestFit":{var M;const e=null==(M=O.filter(e=>{if(S){const t=Ss(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:M[0];e&&(s=e);break}case"initialPlacement":s=o}if(n!==s)return{reset:{placement:s}}}return{}}}},ki=e=>{Object.assign(e,{show(){this.cancelBehaviourOpen?.(),this.openValue=!0},hide(){this.openValue=!1},toggle(){this.cancelBehaviourOpen?.(),this.openValue=!this.openValue},setupFloatingUI({trigger:e,popover:t,strategy:s}){this.floatingUICleanup=function(e,t,s,i){void 0===i&&(i={});const{ancestorScroll:n=!0,ancestorResize:r=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:o="function"==typeof IntersectionObserver,animationFrame:c=!1}=i,l=li(e),h=n||r?[...l?ai(l):[],...ai(t)]:[];h.forEach(e=>{n&&e.addEventListener("scroll",s,{passive:!0}),r&&e.addEventListener("resize",s)});const u=l&&o?function(e,t){let s,i=null;const n=$s(e);function r(){var e;clearTimeout(s),null==(e=i)||e.disconnect(),i=null}return function a(o,c){void 0===o&&(o=!1),void 0===c&&(c=1),r();const l=e.getBoundingClientRect(),{left:h,top:u,width:d,height:p}=l;if(o||t(),!d||!p)return;const m={rootMargin:-us(u)+"px "+-us(n.clientWidth-(h+d))+"px "+-us(n.clientHeight-(u+p))+"px "+-us(h)+"px",threshold:ls(0,cs(1,c))||1};let g=!0;function f(t){const i=t[0].intersectionRatio;if(i!==c){if(!g)return a();i?a(!1,i):s=setTimeout(()=>{a(!1,1e-7)},1e3)}1!==i||Ai(l,e.getBoundingClientRect())||a(),g=!1}try{i=new IntersectionObserver(f,{...m,root:n.ownerDocument})}catch(e){i=new IntersectionObserver(f,m)}i.observe(e)}(!0),r}(l,s):null;let d,p=-1,m=null;a&&(m=new ResizeObserver(e=>{let[i]=e;i&&i.target===l&&m&&(m.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var e;null==(e=m)||e.observe(t)})),s()}),l&&!c&&m.observe(l),m.observe(t));let g=c?pi(e):null;return c&&function t(){const i=pi(e);g&&!Ai(g,i)&&s(),g=i,d=requestAnimationFrame(t)}(),s(),()=>{var e;h.forEach(e=>{n&&e.removeEventListener("scroll",s),r&&e.removeEventListener("resize",s)}),null==u||u(),null==(e=m)||e.disconnect(),m=null,c&&cancelAnimationFrame(d)}}(e,t,()=>{((e,t,s)=>{const i=new Map,n={platform:Ci,...s},r={...n.platform,_c:i};return(async(e,t,s)=>{const{placement:i="bottom",strategy:n="absolute",middleware:r=[],platform:a}=s,o=r.filter(Boolean),c=await(null==a.isRTL?void 0:a.isRTL(t));let l=await a.getElementRects({reference:e,floating:t,strategy:n}),{x:h,y:u}=Ls(l,i,c),d=i,p={},m=0;for(let s=0;s{const n={left:`${e}px`,top:`${s}px`,position:i};Object.assign(t.style,n)})})},openValueChanged(){this.disabledValue||(this.openValue?(this.preparePopoverOpenAnimation?.(),this.popoverTarget.showPopover(),this.popoverTarget.setAttribute("aria-expanded","true"),this.onPopoverOpened&&this.onPopoverOpened()):(this.popoverTarget.hidePopover(),this.popoverTarget.removeAttribute("aria-expanded"),this.onPopoverClosed&&this.onPopoverClosed()))}})},Mi=class extends i.xI{static targets=["button","popover"];static values={placement:{type:String,default:"bottom-end"},open:{type:Boolean,default:!1},autoPlacement:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1},size:{type:Number,default:24},perLine:{type:Number,default:9}};initialize(){this.onEmojiSelect=this.onEmojiSelect.bind(this),this.pickerLoaded=!1,this.pickerLoadPromise=null,this.connected=!1,super.initialize()}connect(){this.connected=!0,ki(this),this.setupFloatingUI({trigger:this.buttonTarget,popover:this.popoverTarget,strategy:"absolute"}),super.connect()}disconnect(){this.connected=!1,this.pickerLoadPromise=null,this.floatingUICleanup(),super.disconnect()}onEmojiSelect(e){this.dispatch("selected",{detail:e.native}),this.hide()}onClickOutside(e){this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}async onPopoverOpened(){await this.loadPicker()}async loadPicker(){if(this.pickerLoaded)return;this.pickerLoadPromise||=this.loadPickerDependencies();const{Picker:e,i18n:t}=await this.pickerLoadPromise;this.connected&&!this.pickerLoaded&&(this.popoverTarget.appendChild(this.buildPicker(e,t)),this.pickerLoaded=!0)}async loadPickerDependencies(){const[e,t]=await Promise.all([s.e(160).then(s.bind(s,405)),this.loadI18n()]);return{Picker:e.Picker,i18n:t.default||t}}loadI18n(){return"es"===Hellotext.business.locale?s.e(437).then(s.t.bind(s,9,19)):s.e(200).then(s.t.bind(s,714,19))}buildPicker(e,t){return new e({onEmojiSelect:this.onEmojiSelect,theme:"light",dynamicWidth:!0,previewPosition:"none",skinTonePosition:"none",emojiSize:this.sizeValue,perLine:this.perLineValue,i18n:t})}get middlewares(){return[Ei(5),Oi({padding:24}),(e={allowedPlacements:["top","bottom"]},void 0===e&&(e={}),{name:"autoPlacement",options:e,async fn(t){var s,i,n;const{rects:r,middlewareData:a,placement:o,platform:c,elements:l}=t,{crossAxis:h=!1,alignment:u,allowedPlacements:d=os,autoAlignment:p=!0,...m}=fs(e,t),g=void 0!==u||d===os?function(e,t,s){return(e?[...s.filter(t=>bs(t)===e),...s.filter(t=>bs(t)!==e)]:s.filter(e=>ys(e)===e)).filter(s=>!e||bs(s)===e||!!t&&Es(s)!==s)}(u||null,p,d):d,f=await _s(t,m),y=(null==(s=a.autoPlacement)?void 0:s.index)||0,b=g[y];if(null==b)return{};const v=As(b,r,await(null==c.isRTL?void 0:c.isRTL(l.floating)));if(o!==b)return{reset:{placement:g[0]}};const w=[f[ys(b)],f[v[0]],f[v[1]]],T=[...(null==(i=a.autoPlacement)?void 0:i.overflows)||[],{placement:b,overflows:w}],S=g[y+1];if(S)return{data:{index:y+1,overflows:T},reset:{placement:S}};const C=T.map(e=>{const t=bs(e.placement);return[e.placement,t&&h?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),A=(null==(n=C.filter(e=>e[2].slice(0,bs(e[0])?2:3).every(e=>e<=0))[0])?void 0:n[0])||C[0][0];return A!==o?{data:{index:y+1,overflows:T},reset:{placement:A}}:{}}})];var e}};class Ii{static get endpoint(){return f.endpoint("public/webchats/:id/messages")}constructor(e){this.webchatId=e}async index(e){const t=new URL(this.url);return Object.entries(e).forEach(([e,s])=>{t.searchParams.append(e,s)}),await fetch(t,{method:"GET",headers:Lt.headers})}catchUp(e){return this.index({after_id:e,session:Lt.session})}async create(e){this.appendPage(e);const t=await fetch(this.url,{method:"POST",headers:{Authorization:`Bearer ${Lt.business.id}`},body:e});return new v(t.ok,t)}markAsSeen(e=null){const t=e?this.url+`/${e}`:this.url+"/seen";fetch(t,{method:"PATCH",headers:Lt.headers,body:JSON.stringify({session:Lt.session})})}get url(){return Ii.endpoint.replace(":id",this.webchatId)}appendPage(e){const t=Lt.page?.trackingData?.page||{};Object.entries(t).forEach(([t,s])=>{s&&e.append(`message[page][${t}]`,s)})}}const Pi=Ii;class Li{static webSocket;static channels=new Set;static messageHandlers=new Set;static disconnectHandlers=new Set;static subscriptionConfirmHandlers=new Set;static reconnectTimeout=null;static reconnectAttempts=0;static reconnectBaseDelay=500;static reconnectMaxDelay=1e4;static reconnectJitter=.3;static needsResubscribe=!1;constructor(){Li.channels.add(this)}send({command:e,identifier:t,data:s}){const i={command:e,identifier:JSON.stringify(t),data:JSON.stringify(s||{})},n=Li.ensureWebSocket(),r=JSON.stringify(i);n.readyState===WebSocket.OPEN?n.send(r):n.addEventListener("open",()=>{n.send(r)})}onMessage(e){const t=t=>{const s=JSON.parse(t.data),{type:i,message:n}=s;this.ignoredEvents.includes(i)||e(n)};Li.messageHandlers.add(t),Li.ensureWebSocket().addEventListener("message",t)}onDisconnect(e){Li.disconnectHandlers.add(e)}onSubscriptionConfirmed(e){Li.subscriptionConfirmHandlers.add(e)}get webSocket(){return Li.ensureWebSocket()}static ensureWebSocket(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}static openWebSocket(){this.clearReconnectTimeout();const e=new WebSocket(f.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}static installWebSocketHandlers(e){e.addEventListener("open",()=>this.handleOpen(e)),e.addEventListener("close",()=>this.handleDisconnect(e)),e.addEventListener("error",()=>this.handleDisconnect(e)),e.addEventListener("message",e=>this.handleControlMessage(e)),this.messageHandlers.forEach(t=>{e.addEventListener("message",t)})}static handleOpen(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}static handleControlMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}static handleDisconnect(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}static scheduleReconnect(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}static clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}static resubscribeChannels(){this.channels.forEach(e=>{const t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}static closedWebSocket(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}static get reconnectDelay(){const e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}get ignoredEvents(){return["ping","confirm_subscription","welcome"]}}const _i=Li,Ni=class extends _i{constructor(e,t,s){super(),this.id=e,this.session=t,this.conversation=s,this.subscribed=!1,this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks=new Set,this.onSubscriptionConfirmed(e=>this.handleSubscriptionConfirmed(e)),this.subscribe()}subscribe(){this.subscribed=!0;const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}unsubscribe(){this.subscribed=!1;const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}resubscribe(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}onReconnect(e){this.reconnectCallbacks.add(e)}handleSubscriptionConfirmed(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}matchesIdentifier(e){let t;try{t="string"==typeof e?JSON.parse(e):e}catch{return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}startTypingIndicator(){const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}stopTypingIndicator(){const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}onMessage(e){super.onMessage(t=>{"message"===t.type&&e(t)})}onReaction(e){super.onMessage(t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)})}onTypingStart(e){super.onMessage(t=>{"started_typing"===t.type&&e(t)})}updateSubscriptionWith(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}},Di=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(!this.shouldAutoOpenFromBehaviour())return;const e=1e3*Number(this.behaviourValue.delay_seconds||0);this.behaviourOpenTimeout=window.setTimeout(()=>{this.behaviourOpenTimeout=null,this.openValue||(this.openValue=!0,this.markBehaviourAutoOpened())},e)},cancelBehaviourOpen(){window.clearTimeout(this.behaviourOpenTimeout),this.behaviourOpenTimeout=null},shouldAutoOpenFromBehaviour(){const e=this.behaviourValue;return!(!e||"on_load"!==e.trigger||e.first_visit_only&&localStorage.getItem(this.firstVisitKey())||e.once_per_session&&sessionStorage.getItem(this.sessionKey()))},markBehaviourAutoOpened(){this.behaviourValue.first_visit_only&&localStorage.setItem(this.firstVisitKey(),"1"),this.behaviourValue.once_per_session&&sessionStorage.setItem(this.sessionKey(),"1")},firstVisitKey(){return`hellotext--webchat--${this.idValue}--auto-opened`},sessionKey(){return`hellotext--webchat--${this.idValue}--auto-opened-session`}})},Ri=e=>{Object.assign(e,{setupOpeningSequence(){this.openingSequenceStarted=!1,this.openingSequenceCancelled=!1,this.openingSequenceTimeout=null,this.openingSequenceMessages=[],this.revealedOpeningSequenceMessageIds=[]},teardownOpeningSequence(){this.cancelOpeningSequence()},startOpeningSequence(){this.openingSequenceMessages=Array.from(this.openingSequenceMessageTargets||[]),this.openingSequenceCanStart()&&(this.openingSequenceStarted=!0,this.openingSequenceCancelled=!1,this.revealedOpeningSequenceMessageIds=[],this.playOpeningSequenceMessageAt(0))},openingSequenceCanStart(){return!this.conversationIdValue&&this.hasOpeningSequenceTarget&&this.openingSequenceMessages.length>0&&!this.openingSequenceStarted},playOpeningSequenceMessageAt(e){const t=this.openingSequenceMessages[e];if(!t)return;const s=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},s)},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){const t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){const t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},scrollOpeningSequenceToBottom(){this.messagesContainerTarget.scroll&&this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"smooth"})},cancelOpeningSequence(){this.openingSequenceCancelled=!0,null!==this.openingSequenceTimeout&&void 0!==this.openingSequenceTimeout&&(window.clearTimeout(this.openingSequenceTimeout),this.openingSequenceTimeout=null)},appendOpeningSequenceMessageIds(e){this.cancelOpeningSequence(),(this.revealedOpeningSequenceMessageIds||[]).forEach(t=>{e.append("message[opening_sequence_message_ids][]",t)})},clearRevealedOpeningSequenceMessageIds(){this.revealedOpeningSequenceMessageIds=[]}})},Fi=e=>{Object.assign(e,{setupTeaser(){this.teaserCycleTimeout=null,this.teaserMessages=[],this.boundOnTeaserClick=this.boundOnTeaserClick||this.onTeaserClick.bind(this),this.hasTeaserTarget&&(this.teaserTarget.addEventListener("click",this.boundOnTeaserClick),this.startTeaserPresentation())},teardownTeaser(){this.stopTeaserCycle(),this.hasTeaserTarget&&this.boundOnTeaserClick&&this.teaserTarget.removeEventListener("click",this.boundOnTeaserClick)},collectTeaserMessages(){return this.hasTeaserTarget?Array.from(this.teaserTarget.querySelectorAll("[data-teaser-message]")):[]},startTeaserPresentation(){this.stopTeaserCycle(),this.teaserMessages=this.collectTeaserMessages(),this.hasTeaserTarget&&(0!==this.teaserMessages.length?this.openValue||this.conversationIdValue||this.hasRenderedConversationMessages()?this.dismissTeaserForSession():this.teaserSeenForSession()?this.hideTeaser():this.teaserMessageDelay(this.teaserMessages[0])>0?this.scheduleTeaserMessage(0):(this.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.scheduleTeaserMessage(1)):this.hideTeaser())},scheduleTeaserMessage(e){const t=this.teaserMessages[e];if(!t)return;const s=this.teaserPresentationDelay(t);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(e),this.scheduleTeaserMessage(e+1)},s)},showTeaserMessage(e){this.teaserMessages.forEach((t,s)=>{t.classList.toggle("hidden",s!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){const t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){let e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){const e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?`:${e}`:"";return`hellotext:webchat:${this.idValue||this.element.id}:teaser-seen${t}`},teaserSeenForSession(){try{return"true"===window.sessionStorage.getItem(this.teaserSeenKey())}catch(e){return!1}},markTeaserSeenForSession(){try{window.sessionStorage.setItem(this.teaserSeenKey(),"true")}catch(e){}},dismissTeaserForSession(){this.markTeaserSeenForSession(),this.hideTeaser()},hideTeaser(){this.stopTeaserCycle(),this.hasTeaserTarget&&this.teaserTarget.classList.add("invisible")},onTeaserClick(e){e.target.closest("a")||(this.dismissTeaserForSession(),this.show())}})},$i={hour:"numeric",minute:"2-digit"},Bi=/Android|iPhone|iPad|iPod/i,Vi={capture:!0,passive:!0},ji=class extends i.xI{static messageTimestampFormatters={};static values={id:String,conversationId:String,media:Object,fileSizeErrorMessage:String,placement:{type:String,default:"bottom-end"},open:{type:Boolean,default:!1},autoPlacement:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1},nextPage:{type:Number,default:void 0},fullScreenThreshold:{type:Number,default:1024},typingIndicatorKeepAlive:{type:Number,default:3e4},offset:{type:Number,default:24},padding:{type:Number,default:24},optimisticTypingIndicatorWait:{type:Number,default:1e3},teaser:Object,messageTeaser:String,behaviour:Object};static classes=["fadeOut"];static targets=["trigger","popover","input","attachmentInput","attachmentButton","errorMessageContainer","attachmentTemplate","attachmentContainer","attachment","messageTemplate","messagesContainer","title","attachmentImage","footer","toolbar","message","unreadCounter","typingIndicator","typingIndicatorTemplate","teaser","teaserMessage","inboundMessageTeaser","inboundMessageTeaserBody","openingSequence","openingSequenceMessage"];initialize(){this.messagesAPI=new Pi(this.idValue),this.webChatChannel=new Ni(this.idValue,Lt.session,this.conversationIdValue),this.files=[],this.messageIds=new Set,this.catchUpAfterMessageId=null,this.fetchingCatchUpMessages=!1,this.onMessageReceived=this.onMessageReceived.bind(this),this.onMessageReaction=this.onMessageReaction.bind(this),this.onTypingStart=this.onTypingStart.bind(this),this.captureCatchUpCursor=this.captureCatchUpCursor.bind(this),this.catchUpMessages=this.catchUpMessages.bind(this),this.onScroll=this.onScroll.bind(this),this.onOutboundMessageSent=this.onOutboundMessageSent.bind(this),this.closePopoverOnEscape=this.closePopoverOnEscape.bind(this),this.broadcastChannel=new BroadcastChannel(`hellotext--webchat--${this.idValue}`),this.webChatChannel.onDisconnect(this.captureCatchUpCursor),this.webChatChannel.onReconnect(this.catchUpMessages),super.initialize()}connect(){Di(this),ki(this),Ri(this),Fi(this),this.setupFloatingUI({trigger:this.triggerTarget,popover:this.popoverTarget}),this.hasTeaserTarget&&this.setupFloatingUI({trigger:this.triggerTarget,popover:this.teaserTarget,strategy:"absolute"}),this.setupTeaser(),this.setupOpeningSequence(),this.localizeMessageTimestamps(),this.webChatChannel.onMessage(this.onMessageReceived),this.webChatChannel.onTypingStart(this.onTypingStart),this.webChatChannel.onReaction(this.onMessageReaction),this.setupMessagesContainerScrollIsolation(),this.messagesContainerTarget.addEventListener("scroll",this.onScroll),this.messagesContainerTarget.addEventListener("wheel",this.stopHostScrollPropagation,Vi),this.messagesContainerTarget.addEventListener("touchmove",this.stopHostScrollPropagation,Vi),this.shouldOpenOnMount&&(this.openValue=!0),Lt.eventEmitter.dispatch("webchat:mounted"),this.broadcastChannel.addEventListener("message",this.onOutboundMessageSent),window.addEventListener("keydown",this.closePopoverOnEscape,!0),this.scheduleBehaviourOpen(),super.connect()}disconnect(){this.cancelBehaviourOpen(),this.clearPopoverOpenAnimation(),this.teardownTeaser(),this.teardownOpeningSequence(),this.broadcastChannel.removeEventListener("message",this.onOutboundMessageSent),this.messagesContainerTarget.removeEventListener("scroll",this.onScroll),this.messagesContainerTarget.removeEventListener("wheel",this.stopHostScrollPropagation,Vi),this.messagesContainerTarget.removeEventListener("touchmove",this.stopHostScrollPropagation,Vi),window.removeEventListener("keydown",this.closePopoverOnEscape,!0),this.clearTypingIndicator(),this.broadcastChannel.close(),this.floatingUICleanup(),super.disconnect()}setupMessagesContainerScrollIsolation(){this.messagesContainerTarget.style.overscrollBehavior="contain",this.messagesContainerTarget.style.webkitOverflowScrolling="touch",this.messagesContainerTarget.style.touchAction="pan-y",this.messagesContainerTarget.setAttribute("data-lenis-prevent",""),this.messagesContainerTarget.setAttribute("data-lenis-prevent-wheel",""),this.messagesContainerTarget.setAttribute("data-lenis-prevent-touch","")}stopHostScrollPropagation(e){e.stopPropagation()}onTypingStart(){if(this.typingIndicatorVisible)return this.resetTypingIndicatorTimer();this.showTypingIndicator()}showOptimisticTypingIndicator(){this.typingIndicatorVisible||this.showTypingIndicator()}showTypingIndicator(){this.clearTypingIndicator(),this.typingIndicatorVisible=!0;const e=this.typingIndicatorTemplateTarget.cloneNode(!0);e.setAttribute("data-hellotext--webchat-target","typingIndicator"),e.style.display="flex",this.messagesContainerTarget.appendChild(e),requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});const t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}resetTypingIndicatorTimer(){if(!this.typingIndicatorVisible)return;clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);const e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}clearTypingIndicator(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}onMessageInputChange(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}onOutboundMessageSent(e){const{data:t}=e,s={"message:sent":e=>{const t=(new DOMParser).parseFromString(e.element,"text/html").body.firstElementChild;this.localizeMessageTimestamps(t),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(t,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(t),t.scrollIntoView({behavior:"instant"})},"message:failed":e=>{const t=this.messagesContainerTarget.querySelector(`#${e.id}`);this.markMessageFailed(t,e.reason)}};s[t.type]?s[t.type](t):console.log(`Unhandled message event: ${t.type}`)}async onScroll(){if(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)return;this.fetchingNextPage=!0;const e=await this.messagesAPI.index({page:this.nextPageValue,session:Lt.session}),{next:t,messages:s}=await e.json();this.nextPageValue=t,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,s.forEach(e=>{const{body:t,attachments:s}=e,i=e.created_at||e.createdAt,n=this.messageTemplateTarget.cloneNode(!0);n.classList.add("hellotext--webchat-message"),n.setAttribute("data-hellotext--webchat-target","message"),n.setAttribute("data-id",e.id),i&&n.setAttribute("data-created-at",i),n.style.removeProperty("display"),gt(n.querySelector("[data-body]"),t),"received"===e.state?n.classList.add("received"):n.classList.remove("received"),s&&s.forEach(e=>{const t=this.attachmentImageTarget.cloneNode(!0);t.removeAttribute("data-hellotext--webchat-target"),t.src=e,t.style.display="block",this.messageAttachmentsContainer(n)?.appendChild(t)}),n.setAttribute("data-body",t),this.localizeMessageTimestamp(n.querySelector("[data-message-timestamp]"),i),this.messagesContainerTarget.prepend(n)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}onClickOutside(e){d.mode===u.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}closePopover(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}preparePopoverOpenAnimation(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.popoverTarget.classList.add("hellotext--webchat-popover-opening"),this.popoverOpenAnimationTimeout=setTimeout(()=>{this.popoverTarget.classList.remove("hellotext--webchat-popover-opening"),this.popoverOpenAnimationTimeout=null},120)}clearPopoverOpenAnimation(){this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),this.popoverTarget?.classList.remove("hellotext--webchat-popover-opening")}onPopoverOpened(){this.popoverTarget.classList.remove(...this.fadeOutClasses),this.dismissTeaserForSession?.(),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Lt.eventEmitter.dispatch("webchat:opened"),localStorage.setItem(`hellotext--webchat--${this.idValue}`,"opened"),this.trackOpen(),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}onPopoverClosed(){this.clearPopoverOpenAnimation(),Lt.eventEmitter.dispatch("webchat:closed"),localStorage.setItem(`hellotext--webchat--${this.idValue}`,"closed")}async trackOpen(){const e=`hellotext--webchat--${this.idValue}--tracked-open`,t=`${Lt.session}:${this.localDate}`;if(Lt.readStorage("localStorage",e)!==t)try{const s=await Lt.track("webchat.opened",{webchat_id:this.idValue,tracked_at:(new Date).toISOString()});s?.succeeded&&Lt.writeStorage("localStorage",e,t)}catch(e){}}onMessageReaction(e){const{message:t,reaction:s,type:i}=e,n=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===i)return n.querySelector(`[data-id="${s.id}"]`).remove();if(n.querySelector(`[data-id="${s.id}"]`))n.querySelector(`[data-id="${s.id}"]`).innerText=s.emoji;else{const e=document.createElement("span");e.innerText=s.emoji,e.setAttribute("data-id",s.id),n.appendChild(e)}}onMessageReceived(e,t={}){const{id:s,body:i,attachments:n,teaser:r}=e,a=e.created_at||e.createdAt;if(!this.claimMessageId(s))return;if(this.hideTeaser?.(),e.carousel)return this.insertCarouselMessage(e,t);const o=this.messageTemplateTarget.cloneNode(!0);o.classList.add("hellotext--webchat-message"),o.style.display="flex",gt(o.querySelector("[data-body]"),i),o.setAttribute("data-id",s),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,a),this.localizeMessageTimestamp(o.querySelector("[data-message-timestamp]"),a),n&&n.forEach(e=>{const t=this.attachmentImageTarget.cloneNode(!0);t.src=e,t.style.display="block",this.messageAttachmentsContainer(o)?.appendChild(t)}),this.clearTypingIndicator(),this.insertMessageElement(o),Lt.eventEmitter.dispatch("webchat:message:received",{...e,body:o.querySelector("[data-body]").innerText}),!1!==t.scroll&&o.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(r),this.openValue?this.messagesAPI.markAsSeen(s):this.incrementUnreadCounter()}claimMessageId(e){const t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}captureCatchUpCursor(){this.catchUpAfterMessageId=this.lastRenderedMessageId}async catchUpMessages(){const e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{const t=await this.messagesAPI.catchUp(e),{messages:s=[]}=await t.json();s.forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}get lastRenderedMessageId(){const e=this.persistedMessageElements;return e[e.length-1]?.dataset.id||null}get persistedMessageElements(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}setMessageCreatedAt(e,t){t&&e.setAttribute("data-created-at",t)}insertMessageElement(e){const t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}nextMessageElementFor(e){const t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(s=>{if(s===e)return!1;const i=Date.parse(s.dataset.createdAt);return!Number.isNaN(i)&&i>t})}updateMessageTeaser(e){this.messageTeaserValue=e,this.messageTeaserValue&&this.hasTeaserTarget&&this.hasInboundMessageTeaserTarget&&this.hasInboundMessageTeaserBodyTarget&&(this.teaserMessageTargets.forEach(e=>e.classList.add("hidden")),this.inboundMessageTeaserBodyTarget.textContent=this.messageTeaserValue,this.inboundMessageTeaserTarget.classList.remove("hidden"),this.teaserTarget.classList.toggle("invisible",this.openValue))}insertCarouselMessage(e,t={}){const s=e.html,i=e.created_at||e.createdAt,n=function(e){return mt(e,dt)}(s).firstElementChild;n.classList.add("hellotext--webchat-message"),n.setAttribute("data-id",e.id),n.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(n,i),this.localizeMessageTimestamps(n),this.clearTypingIndicator(),this.insertMessageElement(n),!1!==t.scroll&&n.scrollIntoView({behavior:"smooth"}),Lt.eventEmitter.dispatch("webchat:message:received",{...e,body:n.querySelector("[data-body]")?.innerText||""}),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}resizeInput(){this.inputTarget.style.height="auto";const e=this.inputTarget.scrollHeight;this.inputTarget.style.height=`${Math.min(e,96)}px`}async sendQuickReplyMessage({detail:{id:e,product:t,buttonId:s,body:i,cardElement:n}}){this.dismissTeaserForSession?.();const r=new FormData;r.append("message[body]",i),e&&r.append("message[replied_to]",e),t&&r.append("message[product]",t),s&&r.append("message[button]",s),r.append("session",Lt.session),r.append("locale",o.toString()),this.appendOpeningSequenceMessageIds(r);const a=this.buildMessageElement(),c=n?.querySelector("img")?.cloneNode(!0);a.querySelector("[data-body]").innerText=i,c&&(c.removeAttribute("width"),c.removeAttribute("height"),this.messageAttachmentsContainer(a)?.appendChild(c)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(a,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(a),a.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:a.outerHTML});const l=await this.messagesAPI.create(r);if(l.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(l,a);const h=await l.json();this.dispatch("set:id",{target:a,detail:h.id}),this.localizeMessageTimestamp(a.querySelector("[data-message-timestamp]"),h.created_at||h.createdAt),this.clearRevealedOpeningSequenceMessageIds();const u={id:h.id,body:i,attachments:c?[c.src]:[],replied_to:e,product:t,button:s,type:"quick_reply"};Lt.eventEmitter.dispatch("webchat:message:sent",u)}async sendTeaserQuickReply(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,s=(t.dataset.value||"").trim(),i=[t.dataset.text,t.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),n=s||i;if(!n)return;this.dismissTeaserForSession?.(),this.show();const r=(t.dataset.type||"").trim()||"quick_reply",a=new FormData;a.append("message[body]",n),a.append("session",Lt.session),a.append("locale",o.toString()),this.appendOpeningSequenceMessageIds(a);const c=this.buildMessageElement();c.querySelector("[data-body]").innerText=n,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(c,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(c),c.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:c.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));const l=await this.messagesAPI.create(a);if(l.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(l,c);const h=await l.json();c.setAttribute("data-id",h.id),this.localizeMessageTimestamp(c.querySelector("[data-message-timestamp]"),h.created_at||h.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Lt.eventEmitter.dispatch("webchat:message:sent",{id:h.id,body:n,attachments:[],type:"quick_reply",teaser:{text:i||n,value:s||n,type:r}}),h.conversation&&h.conversation!==this.conversationIdValue&&(this.conversationIdValue=h.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}async sendMessage(e){const t={body:this.inputTarget.value,attachments:this.files};if(0===this.inputTarget.value.trim().length&&0===this.files.length)return void(e&&e.target&&e.preventDefault());this.dismissTeaserForSession?.();const s=new FormData;this.inputTarget.value.trim().length>0?s.append("message[body]",this.inputTarget.value):delete t.body,this.files.forEach(e=>{s.append("message[attachments][]",e)}),s.append("session",Lt.session),s.append("locale",o.toString()),this.appendOpeningSequenceMessageIds(s);const i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();const n=this.attachmentContainerTarget.querySelectorAll("img");n.length>0&&n.forEach(e=>{this.messageAttachmentsContainer(i)?.appendChild(e.cloneNode(!0))}),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(i,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(i),i.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:i.outerHTML}),this.inputTarget.value="",this.resizeInput(),this.files=[],this.attachmentInputTarget.value="",this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none",this.errorMessageContainerTarget.style.display="none",this.focusComposeInput(),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));const r=await this.messagesAPI.create(s);if(r.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(r,i);const a=await r.json();i.setAttribute("data-id",a.id),t.id=a.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),a.created_at||a.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Lt.eventEmitter.dispatch("webchat:message:sent",t),a.conversation!==this.conversationIdValue&&(this.conversationIdValue=a.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}buildMessageElement(){const e=this.messageTemplateTarget.cloneNode(!0);return e.id=`hellotext--webchat--${this.idValue}--message--${Date.now()}`,e.classList.add("received"),e.style.removeProperty("display"),e.setAttribute("data-controller","hellotext--message"),e.setAttribute("data-hellotext--webchat-target","message"),this.localizeMessageTimestamp(e.querySelector("[data-message-timestamp]"),new Date),e}focusCompose(e){const{target:t}=e,s=["button","a","input","textarea","select","label",'[role="button"]',"em-emoji-picker",'[data-hellotext--webchat--emoji-target~="popover"]','[data-controller~="hellotext--webchat--emoji"]'].join(", ");this.hasInputTarget&&!t.closest(s)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}closePopoverFromHeader(e){const{target:t}=e;t.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}closePopoverOnEscape(e){"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),this.triggerTarget?.focus?.())}async markMessageFailedFromResponse(e,t){const s=await this.messageFailureReason(e);this.markMessageFailed(t,s),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:s})}markMessageFailed(e,t){if(!e)return;if(e.classList.add("failed"),!t)return;const s=e.querySelector("[data-message-timestamp]");s&&(s.textContent=t)}localizeMessageTimestamps(e=this.element){e&&(e.matches?.("time[datetime][data-message-timestamp]")?[e]:Array.from(e.querySelectorAll?.("time[datetime][data-message-timestamp]")||[])).forEach(e=>this.localizeMessageTimestamp(e))}localizeMessageTimestamp(e,t=e?.getAttribute("datetime")){if(!e||!t)return;const s=t instanceof Date?t:new Date(t);Number.isNaN(s.getTime())||(e.setAttribute("datetime",s.toISOString()),e.textContent=this.formatMessageTimestamp(s))}formatMessageTimestamp(e){return this.constructor.messageTimestampFormatterFor(o.toString()).format(e)}static messageTimestampFormatterFor(e){const t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}static buildMessageTimestampFormatter(e){try{return new Intl.DateTimeFormat(e||void 0,$i)}catch(e){return new Intl.DateTimeFormat(void 0,$i)}}async messageFailureReason(e){const t=e?.data||e?.response,s=t?.statusText||"Message failed";try{const e=t?.clone?t.clone():t,s=await(e?.json?.()),i=this.messageFailureReasonFromPayload(s);if(i)return i}catch(e){}try{const e=t?.clone?t.clone():t,i=await(e?.text?.());return this.messageFailureReasonFromText(i)||s}catch(e){return s}}messageFailureReasonFromText(e){if("string"!=typeof e)return null;const t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}messageFailureReasonFromPayload(e){return e?[e.error?.message,e.message,e.errors?.message,e.errors?.[0]?.message,e.errors?.[0]?.description].find(e=>"string"==typeof e&&e.trim().length>0):null}messageAttachmentsContainer(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}incrementUnreadCounter(){this.unreadCounterTarget.style.display="flex";const e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}openAttachment(){this.attachmentInputTarget.click()}onFileInputChange(){this.errorMessageContainerTarget.style.display="none";const e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";const t=e.find(e=>{const t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}createAttachmentElement(e){const t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){const s=this.attachmentImageTarget.cloneNode(!0);s.src=URL.createObjectURL(e),s.style.display="block",t.appendChild(s),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{const s=t.querySelector("main");s.style.height="5rem",s.style.borderRadius="0.375rem",s.style.backgroundColor="#e5e7eb",s.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}removeAttachment({currentTarget:e}){const t=e.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}attachmentTargetDisconnected(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}attachmentElement(){const e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}onEmojiSelect({detail:e}){const t=this.inputTarget.value,s=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=t.slice(0,s)+e+t.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=s+e.length,this.focusComposeInput()}focusComposeInput({moveCursorToEnd:e=!1}={}){if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),e&&"number"==typeof this.inputTarget.selectionStart){const e=this.inputTarget.value.length;this.inputTarget.setSelectionRange(e,e)}return!0}byteToMegabyte(e){return Math.ceil(e/1024/1024)}get middlewares(){return[Ei(this.offsetValue),Oi({padding:this.paddingValue}),xi()]}get localDate(){const e=new Date;return[e.getFullYear(),e.getMonth()+1,e.getDate()].map(e=>String(e).padStart(2,"0")).join("-")}get shouldOpenOnMount(){return"opened"===localStorage.getItem(`hellotext--webchat--${this.idValue}`)&&!this.onMobile}get shouldAutofocusCompose(){return!this.usesVirtualKeyboard}get usesVirtualKeyboard(){if("undefined"==typeof navigator)return!1;const e=navigator.userAgent||"",t="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,s=Bi.test(e),i=!0===navigator.userAgentData?.mobile;return s||t||i||this.hasTouchOnlyPointer}get hasTouchOnlyPointer(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}get onMobile(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(`(max-width: ${this.fullScreenThresholdValue}px)`).matches}},qi=i.lg.start();qi.register("hellotext--alert",Nt),qi.register("hellotext--form",Dt),qi.register("hellotext--popup",rs),qi.register("hellotext--webchat",ji),qi.register("hellotext--webchat--emoji",Mi),qi.register("hellotext--message",Rt),window.Hellotext=Lt;const Ui=Lt}};const t={};function s(i){const n=t[i];if(void 0!==n)return n.exports;const r=t[i]={exports:{}};return e[i](r,r.exports,s),r.exports}s.m=e,(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;s.t=function(i,n){if(1&n&&(i=this(i)),8&n)return i;if("object"==typeof i&&i){if(4&n&&i.__esModule)return i;if(16&n&&"function"==typeof i.then)return i}const r=Object.create(null);s.r(r);const a={};t=t||[null,e({}),e([]),e(e)];for(var o=2&n&&i;("object"==typeof o||"function"==typeof o)&&!~t.indexOf(o);o=e(o))Object.getOwnPropertyNames(o).forEach(e=>a[e]=()=>i[e]);return a.default=()=>i,s.d(r,a),r}})(),s.d=(e,t)=>{if(Array.isArray(t))for(var i=0;iPromise.all(Object.keys(s.f).reduce((t,i)=>(s.f[i](e,t),t),[])),s.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";s.l=(i,n,r,a)=>{if(e[i])return void e[i].push(n);let o,c;if(void 0!==r){const e=document.getElementsByTagName("script");for(var l=0;l{o.onerror=o.onload=null,clearTimeout(u);const n=e[i];if(delete e[i],o.parentNode?.removeChild(o),n?.forEach(e=>e(s)),t)return t(s)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=h.bind(null,o.onerror),o.onload=h.bind(null,o.onload),c&&document.head.appendChild(o)}})(),s.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{let e;s.g.importScripts&&(e=s.g.location+"");const t=s.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const s=t.getElementsByTagName("script");if(s.length){let t=s.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=s[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),(()=>{const e={792:0};s.f.j=(t,i)=>{let n=s.o(e,t)?e[t]:void 0;if(0!==n)if(n)i.push(n[2]);else{const r=new Promise((s,i)=>n=e[t]=[s,i]);i.push(n[2]=r);const a=s.p+s.u(t),o=new Error,c=i=>{if(s.o(e,t)&&(n=e[t],0!==n&&(e[t]=void 0),n)){const e=i&&("load"===i.type?"missing":i.type),s=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+e+": "+s+")",o.name="ChunkLoadError",o.type=e,o.request=s,n[1](o)}};s.l(a,c,"chunk-"+t,t)}};const t=(t,i)=>{let[n,r,a]=i;var o,c,l=0;if(n.some(t=>0!==e[t])){for(o in r)s.o(r,o)&&(s.m[o]=r[o]);a&&a(s)}for(t&&t(i);l(()=>{"use strict";var e={948(e,t,s){s.d(t,{lg:()=>G,xI:()=>ne});class i{constructor(e,t,s){this.eventTarget=e,this.eventName=t,this.eventOptions=s,this.unorderedBindings=new Set}connect(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)}disconnect(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)}bindingConnected(e){this.unorderedBindings.add(e)}bindingDisconnected(e){this.unorderedBindings.delete(e)}handleEvent(e){const t=function(e){if("immediatePropagationStopped"in e)return e;{const{stopImmediatePropagation:t}=e;return Object.assign(e,{immediatePropagationStopped:!1,stopImmediatePropagation(){this.immediatePropagationStopped=!0,t.call(this)}})}}(e);for(const e of this.bindings){if(t.immediatePropagationStopped)break;e.handleEvent(t)}}hasBindings(){return this.unorderedBindings.size>0}get bindings(){return Array.from(this.unorderedBindings).sort((e,t)=>{const s=e.index,i=t.index;return si?1:0})}}class n{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach(e=>e.connect()))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach(e=>e.disconnect()))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce((e,t)=>e.concat(Array.from(t.values())),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,s={}){this.application.handleError(e,`Error ${t}`,s)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:s,eventOptions:i}=e,n=this.fetchEventListenerMapForEventTarget(t),r=this.cacheKey(s,i);n.delete(r),0==n.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:s,eventOptions:i}=e;return this.fetchEventListener(t,s,i)}fetchEventListener(e,t,s){const i=this.fetchEventListenerMapForEventTarget(e),n=this.cacheKey(t,s);let r=i.get(n);return r||(r=this.createEventListener(e,t,s),i.set(n,r)),r}createEventListener(e,t,s){const n=new i(e,t,s);return this.started&&n.connect(),n}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const s=[e];return Object.keys(t).sort().forEach(e=>{s.push(`${t[e]?"":"!"}${e}`)}),s.join(":")}}const r={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:s})=>!t||s===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function o(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function c(e){return o(e.replace(/--/g,"-").replace(/__/g,"_"))}function l(e){return e.charAt(0).toUpperCase()+e.slice(1)}function h(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function u(e){return null!=e}function d(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const p=["meta","ctrl","alt","shift"];class m{constructor(e,t,s,i){this.element=e,this.index=t,this.eventTarget=s.eventTarget||e,this.eventName=s.eventName||function(e){const t=e.tagName.toLowerCase();if(t in g)return g[t](e)}(e)||f("missing event name"),this.eventOptions=s.eventOptions||{},this.identifier=s.identifier||f("missing identifier"),this.methodName=s.methodName||f("missing method name"),this.keyFilter=s.keyFilter||"",this.schema=i}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let s=t[2],i=t[3];return i&&!["keydown","keyup","keypress"].includes(s)&&(s+=`.${i}`,i=""),{eventTarget:(n=t[4],"window"==n?window:"document"==n?document:void 0),eventName:s,eventOptions:t[7]?(r=t[7],r.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||i};var n,r}(e.content),t)}toString(){const e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;const t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;const s=t.filter(e=>!p.includes(e))[0];return!!s&&(d(this.keyMappings,s)||f(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[s].toLowerCase()!==e.key.toLowerCase())}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;const t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){const e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(const{name:s,value:i}of Array.from(this.element.attributes)){const n=s.match(t),r=n&&n[1];r&&(e[o(r)]=y(i))}return e}get eventTargetName(){return(e=this.eventTarget)==window?"window":e==document?"document":void 0;var e}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){const[s,i,n,r]=p.map(e=>t.includes(e));return e.metaKey!==s||e.ctrlKey!==i||e.altKey!==n||e.shiftKey!==r}}const g={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function f(e){throw new Error(e)}function y(e){try{return JSON.parse(e)}catch(t){return e}}class b{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){const t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){const e=this.controller[this.methodName];if("function"==typeof e)return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){const{element:t}=this.action,{actionDescriptorFilters:s}=this.context.application,{controller:i}=this.context;let n=!0;for(const[r,a]of Object.entries(this.eventOptions))if(r in s){const o=s[r];n=n&&o({name:r,value:a,event:e,element:t,controller:i})}return n}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:s}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:s,action:this.methodName})}catch(t){const{identifier:s,controller:i,element:n,index:r}=this,a={identifier:s,controller:i,element:n,index:r,event:e};this.context.handleError(t,`invoking action "${this.action}"`,a)}}willBeInvokedByEvent(e){const t=e.target;return!(e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e))&&!(e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e))&&(this.element===t||(t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element)))}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}}class v{constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver(e=>this.processMutations(e))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){const e=new Set(this.matchElementsInTree());for(const t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(const t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){"attributes"==e.type?this.processAttributeChange(e.target,e.attributeName):"childList"==e.type&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.processTree(e,this.removeElement)}}processAddedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.elementIsActive(e)&&this.processTree(e,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(const s of this.matchElementsInTree(e))t.call(this,s)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected==this.element.isConnected&&this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}}class w{constructor(e,t,s){this.attributeName=t,this.delegate=s,this.elementObserver=new v(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){const t=this.matchElement(e)?[e]:[],s=Array.from(e.querySelectorAll(this.selector));return t.concat(s)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}}function T(e,t){let s=e.get(t);return s||(s=new Set,e.set(t,s)),s}class S{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce((e,t)=>e.concat(Array.from(t)),[])}get size(){return Array.from(this.valuesByKey.values()).reduce((e,t)=>e+t.size,0)}add(e,t){!function(e,t,s){T(e,t).add(s)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,s){T(e,t).delete(s),function(e,t){const s=e.get(t);null!=s&&0==s.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const s=this.valuesByKey.get(e);return null!=s&&s.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some(t=>t.has(e))}getValuesForKey(e){const t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter(([t,s])=>s.has(e)).map(([e,t])=>e)}}class C{constructor(e,t,s,i){this._selector=t,this.details=i,this.elementObserver=new v(e,this),this.delegate=s,this.matchesByElement=new S}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){const{selector:t}=this;if(t){const s=e.matches(t);return this.delegate.selectorMatchElement?s&&this.delegate.selectorMatchElement(e,this.details):s}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const s=this.matchElement(e)?[e]:[],i=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return s.concat(i)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const s of t)this.selectorUnmatched(e,s)}elementAttributeChanged(e,t){const{selector:s}=this;if(s){const t=this.matchElement(e),i=this.matchesByElement.has(s,e);t&&!i?this.selectorMatched(e,s):!t&&i&&this.selectorUnmatched(e,s)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}}class A{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver(e=>this.processMutations(e))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(const e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){const t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){const s=this.delegate.getStringMapKeyForAttribute(e);if(null!=s){this.stringMap.has(e)||this.stringMapKeyAdded(s,e);const i=this.element.getAttribute(e);if(this.stringMap.get(e)!=i&&this.stringMapValueChanged(i,s,t),null==i){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(s,e,t)}else this.stringMap.set(e,i)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,s){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,s)}stringMapKeyRemoved(e,t,s){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,s)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map(e=>e.name)}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}}class E{constructor(e,t,s){this.attributeObserver=new w(e,t,this),this.delegate=s,this.tokensByElement=new S}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){const[t,s]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(s)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach(e=>this.tokenMatched(e))}tokensUnmatched(e){e.forEach(e=>this.tokenUnmatched(e))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){const t=this.tokensByElement.getValuesForKey(e),s=this.readTokensForElement(e),i=function(e,t){const s=Math.max(e.length,t.length);return Array.from({length:s},(s,i)=>[e[i],t[i]])}(t,s).findIndex(([e,t])=>{return i=t,!((s=e)&&i&&s.index==i.index&&s.content==i.content);var s,i});return-1==i?[[],[]]:[t.slice(i),s.slice(i)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,s){return e.trim().split(/\s+/).filter(e=>e.length).map((e,i)=>({element:t,attributeName:s,content:e,index:i}))}(e.getAttribute(t)||"",e,t)}}class O{constructor(e,t,s){this.tokenListObserver=new E(e,t,this),this.delegate=s,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){const{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).set(e,s),this.delegate.elementMatchedValue(t,s))}tokenUnmatched(e){const{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,s))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(e){return{error:e}}}}class x{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new O(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){const t=new b(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){const t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach(e=>this.delegate.bindingDisconnected(e,!0)),this.bindingsByAction.clear()}parseValueForToken(e){const t=m.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class k{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new A(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){const s=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,s.writer(this.receiver[e]),s.writer(s.defaultValue))}stringMapValueChanged(e,t,s){const i=this.valueDescriptorNameMap[t];null!==e&&(null===s&&(s=i.writer(i.defaultValue)),this.invokeChangedCallback(t,e,s))}stringMapKeyRemoved(e,t,s){const i=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,i.writer(this.receiver[e]),s):this.invokeChangedCallback(e,i.writer(i.defaultValue),s)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:s,writer:i}of this.valueDescriptors)null==s||this.controller.data.has(e)||this.invokeChangedCallback(t,i(s),void 0)}invokeChangedCallback(e,t,s){const i=`${e}Changed`,n=this.receiver[i];if("function"==typeof n){const i=this.valueDescriptorNameMap[e];try{const e=i.reader(t);let r=s;s&&(r=i.reader(s)),n.call(this.receiver,e,r)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${i.name}" - ${e.message}`),e}}}get valueDescriptors(){const{valueDescriptorMap:e}=this;return Object.keys(e).map(t=>e[t])}get valueDescriptorNameMap(){const e={};return Object.keys(this.valueDescriptorMap).forEach(t=>{const s=this.valueDescriptorMap[t];e[s.name]=s}),e}hasValue(e){const t=`has${l(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class M{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new S}start(){this.tokenListObserver||(this.tokenListObserver=new E(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var s;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(s=this.tokenListObserver)||void 0===s||s.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var s;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(s=this.tokenListObserver)||void 0===s||s.pause(()=>this.delegate.targetDisconnected(e,t)))}disconnectAllTargets(){for(const e of this.targetsByName.keys)for(const t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}}function I(e,t){const s=P(e);return Array.from(s.reduce((e,s)=>(function(e,t){const s=e[t];return Array.isArray(s)?s:[]}(s,t).forEach(t=>e.add(t)),e),new Set))}function P(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class L{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new S,this.outletElementsByName=new S,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach(e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)}),this.started=!0,this.dependentContexts.forEach(e=>e.refresh()))}refresh(){this.selectorObserverMap.forEach(e=>e.refresh()),this.attributeObserverMap.forEach(e=>e.refresh())}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach(e=>e.stop()),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach(e=>e.stop()),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:s}){const i=this.getOutlet(e,s);i&&this.connectOutlet(i,e,s)}selectorUnmatched(e,t,{outletName:s}){const i=this.getOutletFromMap(e,s);i&&this.disconnectOutlet(i,e,s)}selectorMatchElement(e,{outletName:t}){const s=this.selector(t),i=this.hasOutlet(e,t),n=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!s&&i&&n&&e.matches(s)}elementMatchedAttribute(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementAttributeValueChanged(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementUnmatchedAttribute(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}connectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)||(this.outletsByName.add(s,e),this.outletElementsByName.add(s,t),null===(i=this.selectorObserverMap.get(s))||void 0===i||i.pause(()=>this.delegate.outletConnected(e,t,s)))}disconnectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)&&(this.outletsByName.delete(s,e),this.outletElementsByName.delete(s,t),null===(i=this.selectorObserverMap.get(s))||void 0===i||i.pause(()=>this.delegate.outletDisconnected(e,t,s)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const s of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(s,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),s=new C(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,s),s.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),s=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,s),s.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find(t=>this.attributeNameForOutletName(t)===e)}get outletDependencies(){const e=new S;return this.router.modules.forEach(t=>{I(t.definition.controllerConstructor,"outlets").forEach(s=>e.add(s,t.identifier))}),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){const e=this.dependentControllerIdentifiers;return this.router.contexts.filter(t=>e.includes(t.identifier))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find(t=>t.element===e)}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}}class _{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:s,controller:i,element:n}=this;t=Object.assign({identifier:s,controller:i,element:n},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new x(this,this.dispatcher),this.valueObserver=new k(this,this.controller),this.targetObserver=new M(this,this),this.outletObserver=new L(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(e){this.handleError(e,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,s={}){const{identifier:i,controller:n,element:r}=this;s=Object.assign({identifier:i,controller:n,element:r},s),this.application.handleError(e,`Error ${t}`,s)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,s){this.invokeControllerMethod(`${c(s)}OutletConnected`,e,t)}outletDisconnected(e,t,s){this.invokeControllerMethod(`${c(s)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const s=this.controller;"function"==typeof s[e]&&s[e](...t)}}const N="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,D=(()=>{function e(e){function t(){return Reflect.construct(e,arguments,new.target)}return t.prototype=Object.create(e.prototype,{constructor:{value:t}}),Reflect.setPrototypeOf(t,e),t}try{return function(){const t=e(function(){this.a.call(this)});t.prototype.a=function(){},new t}(),e}catch(e){return e=>class extends e{}}})();class R{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const s=D(e),i=function(e,t){return N(t).reduce((s,i)=>{const n=function(e,t,s){const i=Object.getOwnPropertyDescriptor(e,s);if(!i||!("value"in i)){const e=Object.getOwnPropertyDescriptor(t,s).value;return i&&(e.get=i.get||e.get,e.set=i.set||e.set),e}}(e,t,i);return n&&Object.assign(s,{[i]:n}),s},{})}(e.prototype,t);return Object.defineProperties(s.prototype,i),s}(t,function(e){return I(e,"blessings").reduce((t,s)=>{const i=s(e);for(const e in i){const s=t[e]||{};t[e]=Object.assign(s,i[e])}return t},{})}(t)))};var t}(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){const t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){const t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new _(this,e),this.contextsByScope.set(e,t)),t}}class F{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){return(this.data.get(this.getDataKey(e))||"").match(/[^\s]+/g)||[]}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}}class ${constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){const t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){const s=this.getAttributeNameForKey(e);return this.element.setAttribute(s,t),this.get(e)}has(e){const t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){const t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${h(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,s){let i=this.warnedKeysByObject.get(e);i||(i=new Set,this.warnedKeysByObject.set(e,i)),i.has(t)||(i.add(t),this.logger.warn(s,e))}}function V(e,t){return`[${e}~="${t}"]`}class j{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce((e,t)=>e||this.findTarget(t)||this.findLegacyTarget(t),void 0)}findAll(...e){return e.reduce((e,t)=>[...e,...this.findAllTargets(t),...this.findAllLegacyTargets(t)],[])}findTarget(e){const t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){const t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){return V(this.schema.targetAttributeForScope(this.identifier),e)}findLegacyTarget(e){const t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){const t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map(t=>this.deprecate(t,e))}getLegacySelectorForTargetName(e){const t=`${this.identifier}.${e}`;return V(this.schema.targetAttribute,t)}deprecate(e,t){if(e){const{identifier:s}=this,i=this.schema.targetAttribute,n=this.schema.targetAttributeForScope(s);this.guide.warn(e,`target:${t}`,`Please replace ${i}="${s}.${t}" with ${n}="${t}". The ${i} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class q{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce((e,t)=>e||this.findOutlet(t),void 0)}findAll(...e){return e.reduce((e,t)=>[...e,...this.findAllOutlets(t)],[])}getSelectorForOutletName(e){const t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){const t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){const t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter(s=>this.matchesElement(s,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(s=>this.matchesElement(s,e,t))}matchesElement(e,t,s){const i=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&i.split(" ").includes(s)}}class U{constructor(e,t,s,i){this.targets=new j(this),this.classes=new F(this),this.data=new $(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=s,this.guide=new B(i),this.outlets=new q(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return V(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new U(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class z{constructor(e,t,s){this.element=e,this.schema=t,this.delegate=s,this.valueListObserver=new O(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){const{element:t,content:s}=e;return this.parseValueForElementAndIdentifier(t,s)}parseValueForElementAndIdentifier(e,t){const s=this.fetchScopesByIdentifierForElement(e);let i=s.get(t);return i||(i=this.delegate.createScopeForElementAndIdentifier(e,t),s.set(t,i)),i}elementMatchedValue(e,t){const s=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,s),1==s&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const s=this.scopeReferenceCounts.get(t);s&&(this.scopeReferenceCounts.set(t,s-1),1==s&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}}class W{constructor(e){this.application=e,this.scopeObserver=new z(this.element,this.schema,this),this.scopesByIdentifier=new S,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce((e,t)=>e.concat(t.contexts),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);const t=new R(this.application,e);this.connectModule(t);const s=e.controllerConstructor.afterLoad;s&&s.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const s=this.modulesByIdentifier.get(t);if(s)return s.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const s=this.scopeObserver.parseValueForElementAndIdentifier(e,t);s?this.scopeObserver.elementMatchedValue(s.element,s):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,s){this.application.handleError(e,t,s)}createScopeForElementAndIdentifier(e,t){return new U(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(t=>e.connectContextForScope(t))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(t=>e.disconnectContextForScope(t))}}const K={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:e=>`data-${e}-target`,outletAttributeForScope:(e,t)=>`data-${e}-${t}-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},H("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),H("0123456789".split("").map(e=>[e,e])))};function H(e){return e.reduce((e,[t,s])=>Object.assign(Object.assign({},e),{[t]:s}),{})}class G{constructor(e=document.documentElement,t=K){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,s={})=>{this.debug&&this.logFormattedMessage(e,t,s)},this.element=e,this.schema=t,this.dispatcher=new n(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},r)}static start(e,t){const s=new this(e,t);return s.start(),s}async start(){await new Promise(e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",()=>e()):e()}),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(e=>{e.controllerConstructor.shouldLoad&&this.router.loadDefinition(e)})}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(e=>this.router.unloadIdentifier(e))}get controllers(){return this.router.contexts.map(e=>e.controller)}getControllerForElementAndIdentifier(e,t){const s=this.router.getContextForElementAndIdentifier(e,t);return s?s.controller:null}handleError(e,t,s){var i;this.logger.error("%s\n\n%o\n\n%o",t,e,s),null===(i=window.onerror)||void 0===i||i.call(window,t,"",0,0,e)}logFormattedMessage(e,t,s={}){s=Object.assign({application:this},s),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},s)),this.logger.groupEnd()}}function J(e,t,s){return e.application.getControllerForElementAndIdentifier(t,s)}function Y(e,t,s){let i=J(e,t,s);return i||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,s),i=J(e,t,s),i||void 0)}function Z([e,t],s){return function(e){const{token:t,typeDefinition:s}=e,i=`${h(t)}-value`,n=function(e){const{controller:t,token:s,typeDefinition:i}=e,n=function(e){const{controller:t,token:s,typeObject:i}=e,n=u(i.type),r=u(i.default),a=n&&r,o=n&&!r,c=!n&&r,l=X(i.type),h=Q(e.typeObject.default);if(o)return l;if(c)return h;if(l!==h)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${s}`:s}" must match the defined type "${l}". The provided default value of "${i.default}" is of type "${h}".`);return a?l:void 0}({controller:t,token:s,typeObject:i}),r=Q(i),a=X(i),o=n||r||a;if(o)return o;throw new Error(`Unknown value type "${t?`${t}.${i}`:s}" for "${s}" value`)}(e);return{type:n,key:i,name:o(i),get defaultValue(){return function(e){const t=X(e);if(t)return ee[t];const s=d(e,"default"),i=d(e,"type"),n=e;if(s)return n.default;if(i){const{type:e}=n,t=X(e);if(t)return ee[t]}return e}(s)},get hasCustomDefaultValue(){return void 0!==Q(s)},reader:te[n],writer:se[n]||se.default}}({controller:s,token:e,typeDefinition:t})}function X(e){switch(e){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function Q(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}return Array.isArray(e)?"array":"[object Object]"===Object.prototype.toString.call(e)?"object":void 0}const ee={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},te={array(e){const t=JSON.parse(e);if(!Array.isArray(t))throw new TypeError(`expected value of type "array" but instead got value "${e}" of type "${Q(t)}"`);return t},boolean:e=>!("0"==e||"false"==String(e).toLowerCase()),number:e=>Number(e.replace(/_/g,"")),object(e){const t=JSON.parse(e);if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(`expected value of type "object" but instead got value "${e}" of type "${Q(t)}"`);return t},string:e=>e},se={default:function(e){return`${e}`},array:ie,object:ie};function ie(e){return JSON.stringify(e)}class ne{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:s={},prefix:i=this.identifier,bubbles:n=!0,cancelable:r=!0}={}){const a=new CustomEvent(i?`${i}:${e}`:e,{detail:s,bubbles:n,cancelable:r});return t.dispatchEvent(a),a}}ne.blessings=[function(e){return I(e,"classes").reduce((e,t)=>{return Object.assign(e,(s=t,{[`${s}Class`]:{get(){const{classes:e}=this;if(e.has(s))return e.get(s);{const t=e.getAttributeName(s);throw new Error(`Missing attribute "${t}"`)}}},[`${s}Classes`]:{get(){return this.classes.getAll(s)}},[`has${l(s)}Class`]:{get(){return this.classes.has(s)}}}));var s},{})},function(e){return I(e,"targets").reduce((e,t)=>{return Object.assign(e,(s=t,{[`${s}Target`]:{get(){const e=this.targets.find(s);if(e)return e;throw new Error(`Missing target element "${s}" for "${this.identifier}" controller`)}},[`${s}Targets`]:{get(){return this.targets.findAll(s)}},[`has${l(s)}Target`]:{get(){return this.targets.has(s)}}}));var s},{})},function(e){const t=function(e,t){return P(e).reduce((e,s)=>(e.push(...function(e,t){const s=e[t];return s?Object.keys(s).map(e=>[e,s[e]]):[]}(s,t)),e),[])}(e,"values"),s={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const s=Z(t,this.identifier),i=this.data.getAttributeNameForKey(s.key);return Object.assign(e,{[i]:s})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=Z(e,void 0),{key:s,name:i,reader:n,writer:r}=t;return{[i]:{get(){const e=this.data.get(s);return null!==e?n(e):t.defaultValue},set(e){void 0===e?this.data.delete(s):this.data.set(s,r(e))}},[`has${l(i)}`]:{get(){return this.data.has(s)||t.hasCustomDefaultValue}}}}(t)),s)},function(e){return I(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=c(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),s=this.outlets.getSelectorForOutletName(e);if(t){const s=Y(this,t,e);if(s)return s;throw new Error(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const s=Y(this,t,e);if(s)return s;console.warn(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`,t)}).filter(e=>e):[]}},[`${t}OutletElement`]:{get(){const t=this.outlets.find(e),s=this.outlets.getSelectorForOutletName(e);if(t)return t;throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${l(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ne.targets=[],ne.outlets=[],ne.values={}},543(e,t,s){s.d(t,{default:()=>Ui});var i=s(948);class n extends Error{constructor(e){super(`${e} is not valid. Please provide a valid event name`),this.name="InvalidEvent"}}class r{static events=["session-set","utm-set","forms:collected","form:completed","popup:mounted","popup:opened","popup:closed","alert:shown","alert:dismissed","alert:accepted","push:unsubscribed","activity:occurred","webchat:mounted","webchat:opened","webchat:closed","webchat:message:sent","webchat:message:received","cart.added"];static valid(e){return r.exists(e)}static invalid(e){return!this.valid(e)}static exists(e){return void 0!==this.events.find(t=>t===e)}constructor(){this.subscribers={}}addSubscriber(e,t){if(r.invalid(e))throw new n(e);this.subscribers={...this.subscribers,[e]:this.subscribers[e]?[...this.subscribers[e],t]:[t]}}removeSubscriber(e,t){if(r.invalid(e))throw new n(e);this.subscribers[e]&&(this.subscribers[e]=this.subscribers[e].filter(e=>e!==t))}dispatch(e,t){this.subscribers[e]?.forEach(e=>{e(t)})}get listeners(){return 0!==Object.keys(this.subscribers).length}}class a{static autoMount=!0;static successMessage=!0;static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}static get shouldShowSuccessMessage(){return this.successMessage}}class o{static _identifier;static set identifier(e){this._identifier=e}static get identifier(){return this._identifier?this._identifier:this.#e||this.#t||this.#s||"en"}static toString(){return this.identifier}static get#e(){return"undefined"!=typeof document?document.documentElement?.lang:void 0}static get#t(){return"undefined"!=typeof document?document.querySelector('meta[name="locale"]')?.content:void 0}static get#s(){return"undefined"!=typeof navigator?navigator.language?.split("-")[0]:void 0}}class c{static _id;static _container="body";static _device="auto";static set id(e){this._id=e}static get id(){return this._id}static set container(e){this._container=e}static get container(){return this._container}static set device(e){if(!["auto","mobile","desktop"].includes(e))throw new Error(`Invalid popup device value: ${e}`);this._device=e}static get device(){return this._device}static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}}const l={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"},h={ABSOLUTE:"absolute",FIXED:"fixed"},u={MODAL:"modal",POPOVER:"popover"};class d{static _id;static _container="body";static _placement="bottom-right";static _style={};static _appearance={};static _whatsapp={};static _mode=u.POPOVER;static _behaviour=null;static _hasBehaviourOverride=!1;static _strategy=null;static set container(e){this._container=e}static get container(){return this._container}static set placement(e){if(!Object.values(l).includes(e))throw new Error(`Invalid placement value: ${e}`);this._placement=e}static get placement(){return this._placement}static set id(e){this._id=e}static get id(){return this._id}static get isSet(){return!!this._id}static get style(){return this._style}static set style(e){if("object"!=typeof e)throw new Error("Style must be an object");Object.entries(e).forEach(([e,t])=>{if(!["primaryColor","secondaryColor","typography"].includes(e))throw new Error(`Invalid style property: ${e}`);if("typography"!==e&&!this.isHexOrRgba(t))throw new Error(`Invalid color value: ${t} for ${e}. Colors must be hex or rgb/a.`)}),this._style=e}static get appearance(){return this._appearance}static set appearance(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(([e,t])=>{if(!["header","launcher"].includes(e))throw new Error(`Invalid appearance property: ${e}`);if(!this.isPlainObject(t))throw new Error(`Appearance ${e} must be an object`);Object.entries(t).forEach(([t,s])=>{if("header"===e&&"name"!==t)throw new Error(`Invalid appearance header property: ${t}`);if("launcher"===e&&"iconUrl"!==t)throw new Error(`Invalid appearance launcher property: ${t}`);if(null!=s&&"string"!=typeof s)throw new Error(`Invalid appearance ${e}.${t} value: ${s}`)})}),this._appearance=e}static get whatsapp(){return this._whatsapp}static set whatsapp(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(([e,t])=>{if(!["number","restrictToChannel"].includes(e))throw new Error(`Invalid WhatsApp property: ${e}`);if(null!=t){if("number"===e&&"string"!=typeof t)throw new Error(`Invalid WhatsApp number value: ${t}`);if("restrictToChannel"===e&&"boolean"!=typeof t)throw new Error(`Invalid WhatsApp restrictToChannel value: ${t}`)}}),this._whatsapp=e}static get mode(){return this._mode}static set mode(e){if(!Object.values(u).includes(e))throw new Error(`Invalid mode value: ${e}`);this._mode=e}static get behaviour(){return this._behaviour}static set behaviour(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error(`Invalid behaviour value: ${e}`);this._behaviour=e}else this._behaviour=e}static get hasBehaviourOverride(){return this._hasBehaviourOverride}static set behaviourOverride(e){this._hasBehaviourOverride=!!e}static get strategy(){return this._strategy?this._strategy:"body"==this.container?h.FIXED:h.ABSOLUTE}static set strategy(e){if(e&&!Object.values(h).includes(e))throw new Error(`Invalid strategy value: ${e}`);this._strategy=e}static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}static isHexOrRgba(e){return/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(e)||/^rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3},?\s*(0|1|0?\.\d+)?\s*\)$/.test(e)}static isPlainObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}const p={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"};class m{static _id;static _container="body";static _placement="bottom-right";static _appearance={};static _number=null;static _body=null;static set id(e){this._id=e}static get id(){return this._id}static set container(e){this._container=e}static get container(){return this._container}static set placement(e){if(!Object.values(p).includes(e))throw new Error(`Invalid placement value: ${e}`);this._placement=e}static get placement(){return this._placement}static get appearance(){return this._appearance}static set appearance(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(([e,t])=>{if("launcher"!==e)throw new Error(`Invalid appearance property: ${e}`);if(!this.isPlainObject(t))throw new Error(`Appearance ${e} must be an object`);Object.entries(t).forEach(([t,s])=>{if("iconUrl"!==t)throw new Error(`Invalid appearance launcher property: ${t}`);if(null!=s&&"string"!=typeof s)throw new Error(`Invalid appearance ${e}.${t} value: ${s}`)})}),this._appearance=e}static get number(){return this._number}static set number(e){if(null!=e&&"string"!=typeof e)throw new Error(`Invalid number value: ${e}`);this._number=e}static get body(){return this._body}static set body(e){if(null!=e&&"string"!=typeof e)throw new Error(`Invalid body value: ${e}`);this._body=e}static assign(e){return e&&Object.entries(e).forEach(([e,t])=>{this[e]=t}),this}static isPlainObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}class g{static serviceWorkerUrl=null;static channelId=null;static assign(e){return this.serviceWorkerUrl=e?.serviceWorkerUrl||null,this.channelId=e?.channelId||null,this}}class f{static apiRoot="https://api.hellotext.com/v1";static actionCableUrl="wss://www.hellotext.com/cable";static autoGenerateSession=!0;static session=null;static tracking=!0;static forms=a;static popup=c;static webchat=d;static whatsapp=m;static push=g;static assign(e){if(e){const t=Object.prototype.hasOwnProperty.call(e,"apiRoot")&&!Object.prototype.hasOwnProperty.call(e,"actionCableUrl");Object.entries(e).forEach(([e,t])=>{"forms"===e?this.forms=a.assign(t):"popup"===e?this.popup=c.assign(t):"webchat"===e?this.webchat=d.assign(t):"whatsappWidget"===e?this.whatsapp=m.assign(t):"push"===e?this.push=g.assign(t):this[e]=t}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}static set locale(e){o.identifier=e}static get locale(){return o.toString()}static endpoint(e){return`${this.apiRoot}/${e}`}static actionCableUrlForApiRoot(e){try{const t=new URL(e),s="https:"===t.protocol?"wss:":"ws:";return t.protocol=s,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}const y=class{static get endpoint(){return f.endpoint("public/businesses")}static async get(e){return fetch(`${this.endpoint}/${e}`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json","Content-Type":"application/json"}})}};class b{static get inPreviewMode(){return(new this).inPreviewMode}constructor(){this.urlSearchParams=new URLSearchParams(window.location.search)}get(e){return this.urlSearchParams.get(this.toHellotextParam(e))}has(e){return this.urlSearchParams.has(this.toHellotextParam(e))}get inPreviewMode(){return this.has("preview")}get session(){return this.get("session")}get popup(){return this.get("popup")}toHellotextParam(e){return`hello_${e}`}}class v{#i;constructor(e,t){this.response=t,this.#i=e}get data(){return this.response}async json(){return await this.response.json()}get failed(){return!1===this.#i}get succeeded(){return!0===this.#i}}class w{static get endpoint(){return f.endpoint("track/events")}static async create({headers:e,body:t,keepalive:s=!1}){if(b.inPreviewMode)return new v(!0,{received:!0});const i={method:"POST",headers:e,body:JSON.stringify(t)};s&&(i.keepalive=!0);const n=await fetch(this.endpoint,i);return new v(200===n.status,await n.json())}}class T{static get endpoint(){return f.endpoint("public/forms")}static async get(e){const t=new URL(`${this.endpoint}/${e}`);return t.searchParams.append("session",Lt.session),t.searchParams.append("locale",o.toString()),fetch(t,{method:"GET",headers:Lt.headers})}static async submit(e,t){const s=await fetch(`${this.endpoint}/${e}/submissions`,{method:"POST",headers:Lt.headers,body:JSON.stringify({session:Lt.session,...t})});return new v(s.ok,s)}}const S=class{static get endpoint(){return f.endpoint("public/identifications")}static async create(e={}){const t=await fetch(this.endpoint,{method:"POST",headers:Lt.headers,body:JSON.stringify({session:Lt.session,...e})});return new v(t.ok,t)}},C=class{static get endpoint(){return f.endpoint("public/popups")}static async get(e,{linked:t=!1}={}){const s=new URL(`${this.endpoint}/${e}`);s.searchParams.append("session",Lt.session),s.searchParams.append("locale",o.toString()),s.searchParams.append("device",this.runtimeDevice),t&&s.searchParams.append("linked","true");const i=await this.fetchPopup(s);if(!i.ok)return null;const n=await this.parsePopupResponse(i);return n&&!1!==n.eligible&&n.html?(Lt.business.data||(Lt.business.setData(n.business),Lt.business.setLocale(n.locale)),(new DOMParser).parseFromString(n.html,"text/html").querySelector("article")):null}static async submit(e,t,s=this.idempotencyKey()){const i=await fetch(`${this.endpoint}/${e}/submissions`,{method:"POST",headers:{...Lt.headers,"Idempotency-Key":s},body:JSON.stringify({session:Lt.session,popup_submission:t})});return new v(i.ok,i)}static async resend(e,t,s){const i=await fetch(`${this.endpoint}/${e}/submissions/${t}/resend`,{method:"POST",headers:Lt.headers,body:JSON.stringify({token:s})});return new v(i.ok,i)}static async cancel(e,t,s){const i=await fetch(`${this.endpoint}/${e}/submissions/${t}/cancel`,{method:"POST",headers:Lt.headers,body:JSON.stringify({token:s})});return new v(i.ok,i)}static idempotencyKey(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}static async fetchPopup(e){try{return await fetch(e,{method:"GET",headers:Lt.headers})}catch(e){return{ok:!1}}}static get runtimeDevice(){return"auto"!==f.popup.device?f.popup.device:window.innerWidth<=767?"mobile":"desktop"}static async parsePopupResponse(e){try{return await e.json()}catch(e){return null}}},A=class{static get endpoint(){return f.endpoint("public/webchats")}static async get(e){const t=new URL(`${this.endpoint}/${e}`);t.searchParams.append("session",Lt.session),t.searchParams.append("locale",o.toString()),Object.entries(f.webchat.style).forEach(([e,s])=>{t.searchParams.append(`style[${e}]`,s)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",f.webchat.placement);const s=await fetch(t,{method:"GET",headers:Lt.headers}),i=await s.json();return Lt.business.data||(Lt.business.setData(i.business),Lt.business.setLocale(i.locale)),(new DOMParser).parseFromString(i.html,"text/html").querySelector("article")}static appendWebchatOverrides(e){const{appearance:t,whatsapp:s}=f.webchat;this.appendIfSupplied(e,"webchat[appearance][header][name]",t.header?.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",t.launcher?.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",s.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",s.restrictToChannel)}static appendIfSupplied(e,t,s){null!=s&&e.searchParams.append(t,String(s))}},E=class{static get endpoint(){return f.endpoint("public/widgets/whatsapp")}static async get(e){const t=new URL(`${this.endpoint}/${e}`);Lt.session&&t.searchParams.append("session",Lt.session),t.searchParams.append("locale",o.toString()),t.searchParams.append("placement",f.whatsapp.placement),this.appendWhatsAppOverrides(t);const s=await this.fetchWidget(t);if(!s.ok)return null;const i=await this.parseWidgetResponse(s);return i?(Lt.business.data||(Lt.business.setData(i.business),Lt.business.setLocale(i.locale)),(new DOMParser).parseFromString(i.html,"text/html").querySelector("article")):null}static appendWhatsAppOverrides(e){const{appearance:t,body:s,number:i}=f.whatsapp;this.appendIfSupplied(e,"whatsapp[appearance][launcher][icon_url]",t.launcher?.iconUrl),this.appendIfSupplied(e,"whatsapp[number]",i),this.appendIfSupplied(e,"whatsapp[body]",s)}static appendIfSupplied(e,t,s){null!=s&&e.searchParams.append(t,String(s))}static async fetchWidget(e){try{return await fetch(e,{method:"GET",headers:Lt.headers})}catch(e){return{ok:!1}}}static async parseWidgetResponse(e){try{return await e.json()}catch(e){return null}}},O=class{static get endpoint(){return f.endpoint("public/acks")}static async send(e={}){const t={...e,session:Lt.session,at:(new Date).toISOString()};fetch(this.endpoint,{method:"POST",headers:Lt.headers,body:JSON.stringify(t),keepalive:!0})}},x=class{static get endpoint(){return f.endpoint("public/push/identities")}static async create(e={}){const t=await fetch(this.endpoint,{method:"POST",keepalive:!0,headers:Lt.headers,body:JSON.stringify({...e,session:Lt.session,origin:window.location.origin})});return new v(t.ok,t)}static async destroy(e={}){const t=await fetch(this.endpoint,{method:"DELETE",keepalive:!0,headers:Lt.headers,body:JSON.stringify({...e,session:Lt.session,origin:window.location.origin})});return new v(t.ok,t)}},k=class{static get endpoint(){return f.endpoint("public/push/alerts")}static async create({section:e,kind:t,page:s,pushIdentity:i}){const n=await fetch(this.endpoint,{method:"POST",keepalive:!0,headers:Lt.headers,body:JSON.stringify({session:Lt.session,section:e,kind:t,page:s,push_identity:i})});return new v(n.ok,n)}};function M(e){const t=JSON.stringify(e);return"undefined"==typeof Blob?t.length<6e4:new Blob([t]).size<6e4}class I{static get businesses(){return y}static get events(){return w}static get forms(){return T}static get popups(){return C}static get popups(){return C}static get webchats(){return A}static get whatsappWidgets(){return E}static get identifications(){return S}static get acks(){return O}static get pushAlerts(){return k}static get pushIdentities(){return x}}const P="data-hellotext-stylesheet";class L{constructor(e){this.id=e,this.data=null,this.stylesheet=null,this.stylesheetLoaded=Promise.resolve(!1)}async hydrate(){try{const e=await y.get(this.id);if(!1===e.ok)return null;const t=await e.json();return t?(this.setData(t),this.setLocale(o.toString()),t):null}catch(e){return null}}setData(e){this.data=e,"undefined"!=typeof document&&e.style_url?(this.stylesheet=this.constructor.ensureStylesheet(e.style_url),this.stylesheetLoaded=this.constructor.waitForStylesheet(this.stylesheet)):(this.stylesheet=null,this.stylesheetLoaded=Promise.resolve(!1))}static get stylesheetSelector(){return`link[rel="stylesheet"][${P}]`}static ensureStylesheet(e){const t=this.normalizedStylesheetUrl(e),s=this.stylesheetLinks.find(e=>e.href===t);if(s)return s.setAttribute(P,"true"),s;const i=document.createElement("link");return i.rel="stylesheet",i.href=e,i.setAttribute(P,"true"),this.waitForStylesheet(i),document.head.append(i),i}static get stylesheetLinks(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}static get latestStylesheet(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}static normalizedStylesheetUrl(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}static waitForStylesheet(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{let s;const i=i=>{clearTimeout(s),e.removeEventListener("load",n),e.removeEventListener("error",r),e.dataset.hellotextStylesheetLoaded=i?"true":"false",t(i)},n=()=>i(this.stylesheetIsLoaded(e)),r=()=>i(!1);e.addEventListener("load",n),e.addEventListener("error",r),s=setTimeout(()=>i(this.stylesheetIsLoaded(e)),1e4),s.unref&&s.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}static stylesheetIsLoaded(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}get subscription(){return this.data.subscription}get country(){return this.data.country}get enabledWhitelist(){return"disabled"!==this.data.whitelist}setLocale(e){this.data||(this.data={});const t=e?.toLowerCase().split("-")[0];this.data.locale=Object.prototype.hasOwnProperty.call(this.data.locales||{},t)?t:"en"}get locale(){const e=this.data?.locales;return e?.[this.data.locale]||e?.en}get features(){return this.data.features}}class _{static set(e,t){if("undefined"!=typeof document){const s="https:"===window.location.protocol?"; Secure":"",i=V.getRootDomain(),n=31536e4;document.cookie=i?`${e}=${t}; path=/${s}; domain=${i}; max-age=${n}; SameSite=Lax`:`${e}=${t}; path=/${s}; max-age=${n}; SameSite=Lax`}return"hello_session"===e&&Lt.eventEmitter.dispatch("session-set",t),"hello_utm"===e&&Lt.eventEmitter.dispatch("utm-set",t),t}static get(e){return"undefined"!=typeof document?document.cookie.match("(^|;)\\s*"+e+"\\s*=\\s*([^;]+)")?.pop():void 0}static delete(e){if("undefined"!=typeof document){const t=V.getRootDomain(),s="https:"===window.location.protocol?"; Secure":"";document.cookie=t?`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT${s}; domain=${t}; SameSite=Lax`:`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT${s}; SameSite=Lax`}}}class N{static get documentSearch(){try{const e=window.performance?.getEntriesByType?.("navigation")?.[0];if(e?.name)return new URL(e.name).search}catch(e){}return window.location.search}static get sameSiteReferrer(){try{if("undefined"==typeof document||!document.referrer||!window.location.hostname)return null;const e=new URL(document.referrer);return V.getRootDomain(e.hostname)===V.getRootDomain(window.location.hostname)?e:null}catch(e){return null}}static get restored(){try{const e=window.performance?.getEntriesByType?.("navigation")?.[0]?.type;return"reload"===e||"back_forward"===e}catch(e){return!1}}}const D=["source","medium","campaign","term","content"],R="hello_utm",F="hello_utm_internal";class ${constructor(){const e=$.fromSearch(window.location.search);e&&($.isArrival(e)?this.saveArrival(e):$.isHellotext(e)?this.saveHellotext(e):this.saveIfChanged(F,e))}save(e){this.recordClick(e)}get current(){return $.read(R)}get internal(){return $.read(F)}saveArrival(e){const t=this.current,s=$.restored(e)||$.observedDuringThisDocument(t)||Boolean(N.sameSiteReferrer);$.same(e,t)&&s||this.recordClick(e)}saveHellotext(e){const t=this.current;$.restored(e)&&$.complete(t)||$.same(e,t)&&$.observedDuringThisDocument(t)||this.recordClick(e)}recordClick(e){$.complete(e)&&(Object.keys(this.internal).length&&_.delete(F),this.write(R,e))}saveIfChanged(e,t){$.same(t,$.read(e))||this.write(e,t)}write(e,t){if(!$.complete(t))return;const s=Object.fromEntries(Object.entries(t).filter(([e,t])=>t&&"observed_at"!==e));s.observed_at=(new Date).toISOString(),_.set(e,JSON.stringify(s))}static complete(e){return Boolean(e?.source&&e?.medium)}static fromSearch(e){const t=$.paramsFrom(e);return t.source&&t.medium?t:null}static paramsFrom(e){const t=new URLSearchParams(e||"");return Object.fromEntries(D.map(e=>[e,t.get(`utm_${e}`)]).filter(([e,t])=>t))}static isArrival(e){if(!$.same(e,$.fromSearch(N.documentSearch)))return!1;if($.restored(e)){const t=$.read(R);return!$.complete(t)||$.same(e,t)}const t=N.sameSiteReferrer;return!t||!$.same(e,$.read(F))&&$.same(e,$.fromSearch(t.search))}static isHellotext(e){return"hellotext"===String(e.source).toLowerCase()}static same(e,t){return!(!e||!t)&&D.every(s=>(e[s]||"")===(t[s]||""))}static read(e){try{return JSON.parse(_.get(e))||{}}catch(e){return{}}}static restored(e){return N.restored&&$.same(e,$.fromSearch(N.documentSearch))}static observedDuringThisDocument(e){const t=window.performance?.timeOrigin,s=Date.parse(e?.observed_at);return Boolean(t)&&!Number.isNaN(s)&&s>=t}}const B=["homepage","product_collection","product_details"];class V{static route(e=window.location.href){const t=new URL(e||window.location.href,window.location.href),s=t.hash.match(/^#!?\/[^?]*/)?.[0];return`${t.pathname}${s?.replace(/^#!/,"#")||""}`}constructor(e=null){this.utm=new $,this._url=e,this._section=null}get section(){return this._section&&this._section.route===V.route(this.url)?this._section.value:null}set section(e){this._section=B.includes(e)?{value:e,route:V.route(this.url)}:null}get url(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}get title(){return document.title}get path(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}get utmParams(){return this.utm.current}get trackingData(){const e=this.utm.internal||{},t=this.section;return{page:{url:this.url,title:this.title,path:this.path,...t&&{section:t}},utm_params:this.utmParams,...Object.keys(e).length&&{internal_utm_params:e}}}get domain(){try{const e=this.url;if(!e)return null;const t=new URL(e).hostname;return V.getRootDomain(t)}catch(e){return null}}static getRootDomain(e=null){try{if(!e){if("undefined"==typeof window||!window.location?.hostname)return null;e=window.location.hostname}const t=e.split(".");if(t.length<=1)return e;const s=["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"];for(const e of s){const s=e.split(".");if(t.slice(-s.length).join(".")===e&&t.length>s.length)return`.${t.slice(-(s.length+1)).join(".")}`}const i=t[t.length-1],n=t[t.length-2];return t.length>2&&2===i.length&&n.length<=3?`.${t.slice(-3).join(".")}`:`.${t.slice(-2).join(".")}`}catch(e){return null}}}class j{static#n;static#r;static#a;static get session(){return this.#n}static get ackPayload(){return{utm_params:this.#a?.utmParams||{}}}static set session(e){const t=_.get("hello_session");return this.#n=e,_.set("hello_session",e),t!==e&&_.delete("hello_session_ack_at"),_.get("hello_session_ack_at")||(I.acks.send(this.ackPayload),_.set("hello_session_ack_at",(new Date).toISOString())),this.#n}static initialize(e=new V){this.#a=e,this.#r=new b,this.session=this.#r.session||f.session||_.get("hello_session"),!this.session&&f.autoGenerateSession&&(this.session=crypto.randomUUID())}}class q{static build(e){const t=document.createElement("article"),s=document.createElement("label"),i=document.createElement("input");s.innerText=e.label,i.type=e.type,i.required=e.required,i.placeholder=e.placeholder,["first_name","last_name"].includes(e.kind)?(i.type="text",i.id=i.name=e.kind,s.setAttribute("for",e.kind)):(i.type=e.type,"email"===e.type?(i.id=i.name="email",s.setAttribute("for","email")):"tel"===i.type?(i.id=i.name="phone",s.setAttribute("for","phone"),i.value=`+${Lt.business.country.prefix}`,i.setAttribute("data-default-value",`+${Lt.business.country.prefix}`)):(i.name=i.id=`property_by_id[${e.property}]`,s.setAttribute("for",`property_by_id[${e.property}]`)));const n=document.createElement("main");n.appendChild(s),n.appendChild(i),t.appendChild(n),t.setAttribute("data-hellotext--form-target","inputContainer"),i.setAttribute("data-hellotext--form-target","input");const r=document.createElement("div");return r.setAttribute("data-error-container",""),t.appendChild(r),t}}class U{static build(){const e=document.createElement("div");return e.innerHTML=this.#o(),e.firstElementChild}static#o(){const e=`https://www.hellotext.com?hello_session=${Lt.session}`;return`\n
\n ${Lt.business.locale.white_label.powered_by}\n\n \n \n Hellotext\n \n \n \n
\n `}}function z(e,t){this.v=e,this.k=t}function W(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s2?s-2:0),n=2;n1?t-1:0),i=1;i1?s-1:0),n=1;n2&&void 0!==arguments[2]?arguments[2]:ge;if(J&&J(e,null),!ue(t))return e;let i=t.length;for(;i--;){let n=t[i];if("string"==typeof n){const e=s(n);e!==n&&(Y(t)||(t[i]=e),n=e)}e[n]=!0}return e}function Le(e){for(let t=0;t/g),Ge=ee(/\${[\w\W]*/g),Je=ee(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ye=ee(/^aria-[\-\w]+$/),Ze=ee(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Xe=ee(/^(?:\w+script|data):/i),Qe=ee(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),et=ee(/^html$/i),tt=ee(/^[a-z][.\w]*(-[.\w]+)+$/i),st=ee(/<[/\w!]/g),it=ee(/<[/\w]/g),nt=ee(/<\/no(script|embed|frames)/i),rt=ee(/\/>/i),at=Q(Pe({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),ot=function(){return"undefined"==typeof window?null:window},ct=function(e,t,s,i){return Ee(e,t)&&ue(e[t])?Pe(i.base?_e(i.base):{},e[t],i.transform):s},lt=function(e,t,s){const i=Ee(e,t)?e[t]:void 0;return i&&"object"==typeof i?_e(i):s()};var ht=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ot();const s=t=>e(t);if(s.version="3.4.17",s.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return s.isSupported=!1,s;let i=t.document;const n=i,r=n.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,o=t.Node,c=t.Element,l=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const h=t.DOMParser,u=t.trustedTypes,d=c.prototype,p=Ne(d,"cloneNode"),m=Ne(d,"remove"),g=Ne(d,"removeAttributeNode"),f=Ne(d,"nextSibling"),y=Ne(d,"childNodes"),b=Ne(d,"parentNode"),v=Ne(d,"shadowRoot"),w=Ne(d,"attributes"),T=o&&o.prototype?Ne(o.prototype,"nodeType"):null,S=o&&o.prototype?Ne(o.prototype,"nodeName"):null,C=o&&o.prototype?Ne(o.prototype,"ownerDocument"):null,A=function(e){return T?T(e):e.nodeType},E=function(e){return S?S(e):e.nodeName},O=function(e){for(;null!==e;){const t=X(e,"namespaceURI");if(t)return t.get?Me(t.get):null;e=Z(e)}return null}(d),x=function(e){return O?O(e):e.namespaceURI};if("function"==typeof a){const e=i.createElement("template");e.content&&e.content.ownerDocument&&(i=e.content.ownerDocument)}let k,M,I="",P=!1,L=0;const _=function(){if(L>0)throw ke('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},N=function(e){_(),L++;try{return k.createHTML(e)}finally{L--}},D=i,R=D.implementation,F=D.createNodeIterator,$=D.createDocumentFragment,B=D.getElementsByTagName,V=n.importNode;let j={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};s.isSupported="function"==typeof G&&"function"==typeof b&&R&&void 0!==R.createHTMLDocument;const q=Ke,U=He,z=Ge,W=Je,K=Ye,H=Xe,J=Qe,Y=tt;let se=Ze,ie=null;const ne=Pe({},[...De,...Re,...Fe,...Be,...je]);let Ie=null;const Le=Pe({},[...qe,...Ue,...ze,...We]);let ht=Object.seal(te(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ut=null,dt=null;const pt=Object.seal(te(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let mt=!0,gt=!0,ft=!1,yt=!0,bt=!1,vt=!0,wt=!1,Tt=!1,St=null,Ct=null,At=!1,Et=!1,Ot=!1,xt=!1,kt=!0,Mt=!1;const It="user-content-";let Pt=!0,Lt=!1,_t=null,Nt={},Dt=null;const Rt=Pe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Ft=null;const $t=Pe({},["audio","video","img","source","image","track"]);let Bt=null;const Vt=Pe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),jt="http://www.w3.org/1998/Math/MathML",qt="http://www.w3.org/2000/svg",Ut="http://www.w3.org/1999/xhtml";let zt=Ut,Wt=!1,Kt=null;const Ht=Pe({},[jt,qt,Ut],fe),Gt=Q(["mi","mo","mn","ms","mtext"]);let Jt=Pe({},Gt);const Yt=Q(["annotation-xml"]);let Zt=Pe({},Yt);const Xt=Pe({},["title","style","font","a","script"]);let Qt=null;const es=["application/xhtml+xml","text/html"];let ts=null,ss=null;const is=i.createElement("form"),ns=function(e){return e instanceof RegExp||e instanceof Function},rs=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ss&&ss===e)return;e&&"object"==typeof e||(e={}),e=_e(e),Qt=-1===es.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ts="application/xhtml+xml"===Qt?fe:ge,ie=ct(e,"ALLOWED_TAGS",ne,{transform:ts}),Ie=ct(e,"ALLOWED_ATTR",Le,{transform:ts}),Kt=ct(e,"ALLOWED_NAMESPACES",Ht,{transform:fe}),Bt=ct(e,"ADD_URI_SAFE_ATTR",Vt,{transform:ts,base:Vt}),Ft=ct(e,"ADD_DATA_URI_TAGS",$t,{transform:ts,base:$t}),Dt=ct(e,"FORBID_CONTENTS",Rt,{transform:ts}),ut=ct(e,"FORBID_TAGS",_e({}),{transform:ts}),dt=ct(e,"FORBID_ATTR",_e({}),{transform:ts}),Nt=!!Ee(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?_e(e.USE_PROFILES):e.USE_PROFILES),mt=!1!==e.ALLOW_ARIA_ATTR,gt=!1!==e.ALLOW_DATA_ATTR,ft=e.ALLOW_UNKNOWN_PROTOCOLS||!1,yt=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,bt=e.SAFE_FOR_TEMPLATES||!1,vt=!1!==e.SAFE_FOR_XML,wt=e.WHOLE_DOCUMENT||!1,Et=e.RETURN_DOM||!1,Ot=e.RETURN_DOM_FRAGMENT||!1,xt=e.RETURN_TRUSTED_TYPE||!1,At=e.FORCE_BODY||!1,kt=!1!==e.SANITIZE_DOM,Mt=e.SANITIZE_NAMED_PROPS||!1,Pt=!1!==e.KEEP_CONTENT,Lt=e.IN_PLACE||!1,se=function(e){try{return xe(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Ze,zt="string"==typeof e.NAMESPACE?e.NAMESPACE:Ut,Jt=lt(e,"MATHML_TEXT_INTEGRATION_POINTS",()=>Pe({},Gt)),Zt=lt(e,"HTML_INTEGRATION_POINTS",()=>Pe({},Yt));const t=lt(e,"CUSTOM_ELEMENT_HANDLING",()=>te(null));if(ht=te(null),Ee(t,"tagNameCheck")&&ns(t.tagNameCheck)&&(ht.tagNameCheck=t.tagNameCheck),Ee(t,"attributeNameCheck")&&ns(t.attributeNameCheck)&&(ht.attributeNameCheck=t.attributeNameCheck),Ee(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(ht.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),ee(ht),bt&&(gt=!1),Ot&&(Et=!0),Nt&&(ie=Pe({},je),Ie=te(null),!0===Nt.html&&(Pe(ie,De),Pe(Ie,qe)),!0===Nt.svg&&(Pe(ie,Re),Pe(Ie,Ue),Pe(Ie,We)),!0===Nt.svgFilters&&(Pe(ie,Fe),Pe(Ie,Ue),Pe(Ie,We)),!0===Nt.mathMl&&(Pe(ie,Be),Pe(Ie,ze),Pe(Ie,We))),pt.tagCheck=null,pt.attributeCheck=null,Ee(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?pt.tagCheck=e.ADD_TAGS:ue(e.ADD_TAGS)&&(ie===ne&&(ie=_e(ie)),Pe(ie,e.ADD_TAGS,ts))),Ee(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?pt.attributeCheck=e.ADD_ATTR:ue(e.ADD_ATTR)&&(Ie===Le&&(Ie=_e(Ie)),Pe(Ie,e.ADD_ATTR,ts))),Ee(e,"ADD_FORBID_CONTENTS")&&ue(e.ADD_FORBID_CONTENTS)&&(Dt===Rt&&(Dt=_e(Dt)),Pe(Dt,e.ADD_FORBID_CONTENTS,ts)),Pt&&(ie["#text"]=!0),wt&&Pe(ie,["html","head","body"]),ie.table&&(Pe(ie,["tbody"]),delete ut.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw ke('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw ke('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=k;k=e.TRUSTED_TYPES_POLICY;try{I=N("")}catch(e){throw k=t,e}}else null===e.TRUSTED_TYPES_POLICY?(k=void 0,I=""):(void 0===k&&(P||(M=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let s=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(s=t.getAttribute(i));const n="dompurify"+(s?"#"+s:"");try{return e.createPolicy(n,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+n+" could not be created."),null}}(u,r),P=!0),k=M),k&&"string"==typeof I&&(I=N("")));Q&&Q(e),ss=e},as=Pe({},[...Re,...Fe,...$e]),os=Pe({},[...Be,...Ve]),cs=function(e){ce(s.removed,{element:e});try{b(e).removeChild(e)}catch(t){if(m(e),!b(e))throw ke("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},ls=function(e,t,s){try{g(e,t)}catch(t){try{e.removeAttribute(s)}catch(e){}}},hs=function(e){ms(e);const t=y(e);t&&re(le(t),e=>{try{m(e)}catch(e){}});const s=1===A(e)?w(e):null;if(s)for(let t=s.length-1;t>=0;--t){const i=s[t],n=i&&i.name;"string"==typeof n&&ls(e,i,n)}},us=function(e,t,i){if(!i)try{i=t.getAttributeNode(e)}catch(e){i=null}ce(s.removed,{attribute:i||null,from:t});try{i?g(t,i):t.removeAttribute(e)}catch(s){try{t.removeAttribute(e)}catch(e){}}if("is"===e)if(Et||Ot)try{cs(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},ds=function(e){const t=w(e);if(t)for(let s=t.length-1;s>=0;--s){const i=t[s],n=i&&i.name;"string"!=typeof n||Ie[ts(n)]||ls(e,i,n)}},ps=function(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const i=[e];for(;i.length>0;){const e=i.pop();if(!1===t(e))continue;if(s&&1===A(e)){const t=v(e);Es(t)&&i.push(t)}const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)i.push(n[e])}},ms=function(e){ps(e,e=>{1===A(e)&&ds(e)})},gs=function(e){const t=[];return ps(e,e=>{t.push(e)},!0),t},fs=function(e,t){let i=!1;return re(s.removed,t=>{t.element&&(i=i||t.element===e,ms(t.element))}),function(e,t){const s=de();re(gs(e),e=>{1===A(e)&&pe(s,e)}),re(t,e=>{1!==A(e)||me(s,e)||ds(e)})}(e,t),i},ys=function(e,t,s,i){const n=ws(e);let r;for(;r=n.nextNode();)me(i,r)&&!me(_t,r)&&(t&&xs(j.uponSanitizeShadowNode,r,null),Ps(r,s),$s(r,s),Es(r.content)&&Bs(r.content))},bs=function(e,t){return!!vt&&("patchsrc"===e||"for"===e&&"label"!==t&&"output"!==t)},vs=function(e){let t=null,s=null;if(At)e=""+e;else{const t=ye(e,/^[\r\n\t ]+/);s=t&&t[0]}"application/xhtml+xml"===Qt&&zt===Ut&&(e=''+e+"");const n=k?N(e):e;if(zt===Ut)try{t=(new h).parseFromString(n,Qt)}catch(e){}if(!t||!t.documentElement){t=R.createDocument(zt,"template",null);try{t.documentElement.innerHTML=Wt?I:n}catch(e){}}const r=t.body||t.documentElement;return e&&s&&r.insertBefore(i.createTextNode(s),r.childNodes[0]||null),zt===Ut?B.call(t,wt?"html":"body")[0]:wt?t.documentElement:r},ws=function(e){const t=C?C(e):e.ownerDocument;return F.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ts=function(e){return e=be(e,q," "),e=be(e,U," "),be(e,z," ")},Ss=function(e){var t;Cs(e);const s=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");s&&re(s,e=>{Es(e.content)&&Ss(e.content)})},Cs=function(e){e.normalize();const t=C?C(e):e.ownerDocument,s=F.call(t||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let i=s.nextNode();for(;i;)i.data=Ts(i.data),i=s.nextNode()},As=function(e){const t=S?S(e):null;return"string"==typeof t&&"form"===ts(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==w(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.removeAttributeNode||"function"!=typeof e.getAttributeNode||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==T(e)||e.childNodes!==y(e))},Es=function(e){if(!T||"object"!=typeof e||null===e)return!1;try{return 11===T(e)}catch(e){return!1}},Os=function(e){if(!T||"object"!=typeof e||null===e)return!1;try{return"number"==typeof T(e)}catch(e){return!1}};function xs(e,t,i){0!==e.length&&re(e,e=>{e.call(s,t,i,ss)})}const ks=function(e,t){if(e instanceof RegExp)return xe(e,t);if(e instanceof Function){for(var s=arguments.length,i=new Array(s>2?s-2:0),n=2;n=0;--n){const r=e===s?p(i[n],!0):i[n];t.insertBefore(r,f(e))}}return cs(e),!0}(e,i,t);return!(!1!==s||(xs(j.afterSanitizeElements,e,null),!Is(e,t)))||s}if(1===A(e)&&!function(e){const t=x(e),s=ge(E(e)),i=b(e);let n,r;return i&&1===A(i)?(n={namespaceURI:x(i)},r=ge(E(i))):(n={namespaceURI:zt},r="template"),!!Kt[t]&&(t===qt?function(e,t,s){return t.namespaceURI===Ut?"svg"===e:t.namespaceURI===jt?"svg"===e&&("annotation-xml"===s||Jt[s]):Boolean(as[e])}(s,n,r):t===jt?function(e,t,s){return t.namespaceURI===Ut?"math"===e:t.namespaceURI===qt?"math"===e&&Zt[s]:Boolean(os[e])}(s,n,r):t===Ut?function(e,t,s){return!(t.namespaceURI===qt&&!Zt[s])&&!(t.namespaceURI===jt&&!Jt[s])&&!os[e]&&(Xt[e]||!as[e])}(s,n,r):!("application/xhtml+xml"!==Qt||!Kt[t]))}(e))return cs(e),!0;if(("noscript"===i||"noembed"===i||"noframes"===i)&&xe(nt,e.innerHTML))return cs(e),!0;if(bt&&3===e.nodeType){const t=Ts(e.textContent);e.textContent!==t&&(ce(s.removed,{element:e.cloneNode()}),e.textContent=t)}return xs(j.afterSanitizeElements,e,null),Is(e,t)},Ls=function(e,t,s){if(dt[t])return!1;if(bs(t,e))return!1;if(kt&&("id"===t||"name"===t)&&(s in i||s in is))return!1;const n=Ie[t]||pt.attributeCheck instanceof Function&&pt.attributeCheck(t,e);return!(!gt||!xe(W,t))||!(!mt||!xe(K,t))||(n?!(!Bt[t]&&!xe(se,be(s,J,""))&&("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==ve(s,"data:")||!Ft[e])&&(!ft||xe(H,be(s,J,"")))&&s):Ns(e)&&ks(ht.tagNameCheck,e)&&ks(ht.attributeNameCheck,t,e)||"is"===t&&ht.allowCustomizedBuiltInElements&&ks(ht.tagNameCheck,s))},_s=Pe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Ns=function(e){return!_s[ge(e)]&&xe(Y,e)},Ds=function(e,t,s,i){if(k&&"object"==typeof u&&"function"==typeof u.getAttributeType&&!s)switch(u.getAttributeType(e,t)){case"TrustedHTML":return N(i);case"TrustedScriptURL":return function(e){_(),L++;try{return k.createScriptURL(e)}finally{L--}}(i)}return i},Rs=function(e,t,s,i){try{return s?e.setAttributeNS(s,t,i):e.setAttribute(t,i),!As(e)||(cs(e),!1)}catch(s){return us(t,e),!1}},Fs=function(e,t){return!(!vt||!xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,t))||"attributename"===ge(e)&&null!==ye(t,"href")},$s=function(e,t){if(xs(j.beforeSanitizeAttributes,e,null),Is(e,t))return;const i=e.attributes;if(!i||As(e))return;Ie=Ms(j.uponSanitizeAttribute,Ie,Le,Ct);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ie,forceKeepAttr:void 0};let r=i.length;const a=ts(e.nodeName);for(;r--;){const t=i[r],o=t.name,c=t.namespaceURI,l=t.value,h=ts(o),u=l;let d="value"===o?u:we(u),p=!1;n.attrName=h,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,xs(j.uponSanitizeAttribute,e,n),d=n.attrValue,!Mt||"id"!==h&&"name"!==h||0===ve(d,It)||(us(o,e,t),d=It+d,p=!0),Fs(o,d)?us(o,e,t):n.forceKeepAttr||(!n.keepAttr||!yt&&xe(rt,d)?us(o,e,t):(bt&&(d=Ts(d)),Ls(a,h,d)?(d=Ds(a,h,c,d),d!==u&&Rs(e,o,c,d)&&p&&oe(s.removed)):us(o,e,t)))}xs(j.afterSanitizeAttributes,e,null),Is(e,t)},Bs=function(e){let t=null;const s=ws(e);for(xs(j.beforeSanitizeShadowDOM,e,null);t=s.nextNode();)if(xs(j.uponSanitizeShadowNode,t,null),Ps(t,e),$s(t,e),Es(t.content)&&Bs(t.content),1===A(t)){const e=v(t);Es(e)&&(Vs(e),Bs(e))}bt&&Cs(e),xs(j.afterSanitizeShadowDOM,e,null)},Vs=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){Bs(e.shadow);continue}const s=e.node,i=1===A(s),n=y(s);if(n)for(let e=n.length-1;e>=0;--e)t.push({node:n[e],shadow:null});if(i){const e=S?S(s):null;if("string"==typeof e&&"template"===ts(e)){const e=s.content;Es(e)&&t.push({node:e,shadow:null})}}if(i){const e=v(s);Es(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return s.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=null,r=null,a=null,o=null;if(Wt=!e,Wt&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Os(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return Te(e);case"boolean":return Se(e);case"bigint":return Ce?Ce(e):"0";case"symbol":return Ae?Ae(e):"Symbol()";case"undefined":default:return Oe(e);case"function":case"object":{if(null===e)return Oe(e);const t=e,s=Ne(t,"toString");if("function"==typeof s){const e=s(t);return"string"==typeof e?e:Oe(e)}return Oe(e)}}}(e)))throw ke("dirty is not a string, aborting");if(!s.isSupported)return e;Tt?(ie=St,Ie=Ct):rs(t),(j.uponSanitizeElement.length>0||j.uponSanitizeAttribute.length>0)&&(ie=_e(ie)),j.uponSanitizeAttribute.length>0&&(Ie=_e(Ie)),s.removed=[];const c=Lt&&"string"!=typeof e&&Os(e);let l=[];const h=_t;if(c){vt&&ps(e,e=>{const t=A(e);if(7===t||8===t&&xe(it,e.data)){try{m(e)}catch(e){}return!1}if(1===t){const t=e,s=ts(E(e));try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&bs("for",s)&&t.removeAttribute("for")}catch(e){}}return!0});const t=E(e);if("string"==typeof t){const s=ts(t);if(!ie[s]||ut[s])throw hs(e),ke("root node is forbidden and cannot be sanitized in-place")}if(As(e))throw hs(e),ke("root node is clobbered and cannot be sanitized in-place");l=gs(e),_t=de()}else if(Os(e))i=vs("\x3c!----\x3e"),r=i.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?i=r:i.appendChild(r),Vs(i);else{if(!Et&&!bt&&!wt&&-1===e.indexOf("<"))return k&&xt?N(e):e;if(i=vs(e),!i)return Et?null:xt?I:""}i&&At&&cs(i.firstChild);const u=c?e:i;try{c&&Vs(e);const t=ws(u);for(;a=t.nextNode();)Ps(a,u),$s(a,u),Es(a.content)&&Bs(a.content);c&&function(e,t){const s=_t;let i=null;const n=()=>(i||(i=de(),re(t,e=>{pe(i,e)})),i);for(let t=0;;t++){const i=gs(e),r=[e];let a=!1;if(re(i,e=>{11===A(e)?ce(r,e):a||me(s,e)||(a=me(n(),e))}),!a)return;if(t>=8)throw ke("the tree kept changing during in-place sanitization; refusing to return it");re(r,(t,s)=>{ys(t,s>0,e,n())})}}(e,l)}catch(t){throw c&&(hs(e),fs(e,l)),t}finally{_t=h}if(c){if(fs(e,l))throw ke("a node selected for removal could not be safely returned; refusing to sanitize in place");return bt&&Ss(e),e}if(Et){if(bt&&Ss(i),Ot)for(o=$.call(i.ownerDocument);i.firstChild;)o.appendChild(i.firstChild);else o=i;return(Ie.shadowroot||Ie.shadowrootmode)&&(o=V.call(n,o,!0)),o}let d=wt?i.outerHTML:i.innerHTML;return wt&&ie["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&xe(et,i.ownerDocument.doctype.name)&&(d="\n"+d),bt&&(d=Ts(d)),k&&xt?N(d):d},s.setConfig=function(){rs(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Tt=!0,St=ie,Ct=Ie},s.clearConfig=function(){ss=null,Tt=!1,St=null,Ct=null,k=M,I=""},s.isValidAttribute=function(e,t,s){ss||rs({});const i=ts(e),n=ts(t);return("string"!=typeof s||!(Fs(t,s)||!yt&&xe(rt,s)))&&Ls(i,n,s)},s.addHook=function(e,t){"function"==typeof t&&Ee(j,e)&&ce(j[e],t)},s.removeHook=function(e,t){if(Ee(j,e)){if(void 0!==t){const s=ae(j[e],t);return-1===s?void 0:he(j[e],s,1)[0]}return oe(j[e])}},s.removeHooks=function(e){Ee(j,e)&&(j[e]=[])},s.removeAllHooks=function(){j={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},s}();const ut={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},dt={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}},pt={RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function mt(e,t){const s=ht.sanitize(e,t);return s.querySelectorAll('a[target="_blank"]').forEach(e=>{const t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),s}function gt(e,t){e.replaceChildren(function(e){return mt(e,ut)}(t))}class ft{constructor(e,t=null){this.data=e,this.element=t||document.querySelector(`[data-hello-form="${this.id}"]`)||document.createElement("form")}async mount({ifCompleted:e=!0}={}){if(e&&this.hasBeenCompleted)return this.element?.remove(),Lt.eventEmitter.dispatch("form:completed",{id:this.id,...JSON.parse(localStorage.getItem(`hello-form-${this.id}`))});const t=this.data.steps[0];this.buildHeader(t.header),this.buildInputs(t.inputs),this.buildButton(t.button),this.buildFooter(t.footer),this.elementAttributes.forEach(e=>{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Lt.business.features.white_label||this.element.prepend(U.build())}buildHeader(e){const t=this.#c("[data-form-header]","header");gt(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}buildInputs(e){const t=this.#c("[data-form-inputs]","main");e.map(e=>q.build(e)).forEach(e=>t.appendChild(e)),this.element.querySelector("[data-form-inputs]")?this.element.querySelector("[data-form-inputs]").replaceWith(t):this.element.querySelector("[data-form-header]").insertAdjacentHTML("afterend",t.outerHTML)}buildButton(e){const t=this.#c("[data-form-button]","button");t.innerText=e.text,t.setAttribute("data-action","click->hellotext--form#submit"),t.setAttribute("data-hellotext--form-target","button"),this.element.querySelector("[data-form-button]")?this.element.querySelector("[data-form-button]").replaceWith(t):this.element.querySelector("[data-form-inputs]").insertAdjacentHTML("afterend",t.outerHTML)}buildFooter(e){const t=this.#c("[data-form-footer]","footer");gt(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}markAsCompleted(e){const t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem(`hello-form-${this.id}`,JSON.stringify(t)),Lt.recordActivity("form.completed"),Lt.eventEmitter.dispatch("form:completed",t)}get hasBeenCompleted(){return null!==localStorage.getItem(`hello-form-${this.id}`)}get id(){return this.data.id}get localeAuthKey(){const e=this.data.steps[0];return e.inputs.some(e=>"email"===e.kind)&&e.inputs.some(e=>"phone"===e.kind)?"phone_and_email":e.inputs.some(e=>"email"===e.kind)?"email":e.inputs.some(e=>"phone"===e.kind)?"phone":"none"}get elementAttributes(){return[{name:"data-controller",value:"hellotext--form"},{name:"data-hello-form",value:this.id},{name:"data-hellotext--form-data-value",value:JSON.stringify(this.data)}]}#c(e,t){const s=this.element.querySelector(e);if(s)return s.cloneNode(!0);const i=document.createElement(t);return i.setAttribute(e.replace("[","").replace("]",""),""),i}}class yt extends Error{constructor(){super("You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"),this.name="NotInitializedError"}}class bt{constructor(){this.forms=[],this.initializationVersion=Lt.initializationVersion,this.includes=this.includes.bind(this),this.excludes=this.excludes.bind(this),this.add=this.add.bind(this),"undefined"!=typeof MutationObserver&&(this.mutationObserver=new MutationObserver(this.formMutationObserver.bind(this)),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}collectExistingFormsOnPage(){Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}formMutationObserver(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}async collect(){if(Lt.notInitialized)throw new yt;if(this.fetching)return;if(!this.current)return;if("undefined"==typeof document||!("querySelectorAll"in document))return console.warn("Document is not defined, collection is not possible. Please make sure to initialize the library after the document is loaded.");const e=this.#l;if(0===e.length)return;const t=e.map(e=>T.get(e).then(e=>e.json()));this.fetching=!0;try{const e=await Promise.all(t);if(!this.current)return;e.forEach(this.add),Lt.eventEmitter.dispatch("forms:collected",this),f.forms.autoMount&&this.forms.forEach(e=>e.mount())}finally{this.fetching=!1}}forEach(e){this.forms.forEach(e)}map(e){return this.forms.map(e)}add(e){this.includes(e.id)||(Lt.business.data||(Lt.business.setData(e.business),Lt.business.setLocale(o.toString())),Lt.business.enabledWhitelist||console.warn("No whitelist has been configured. It is advised to whitelist the domain to avoid bots from submitting forms."),this.forms.push(new ft(e)))}getById(e){return this.forms.find(t=>t.id===e)}getByIndex(e){return this.forms[e]}includes(e){return this.forms.some(t=>t.id===e)}excludes(e){return!this.includes(e)}get length(){return this.forms.length}get current(){return Lt.initializationVersion===this.initializationVersion}get#l(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}}const vt=/^[A-Za-z0-9_-]{1,64}$/;class wt{static get linkedId(){const e=(new b).popup;if(!e||!vt.test(e))return null;if(N.restored&&wt.idIn(N.documentSearch)===e)return null;const t=N.sameSiteReferrer;return t&&wt.idIn(t.search)===e?null:e}static browser(e=("undefined"==typeof navigator?"":navigator.userAgent)){return/Android/i.test(e)?"android":/Edg\//.test(e)?"edge":/Firefox\//.test(e)?"firefox":/Chrome\//.test(e)?"chrome":/Safari\//.test(e)?"safari":"other"}static idIn(e){return new URLSearchParams(e||"").get("hello_popup")}static finished(e){if(!vt.test(e||""))return!1;const t=wt.finishedKey(e),s=_.get(t);if("0"===s){try{localStorage.removeItem(t)}catch(e){}return!1}let i=null;try{i=localStorage.getItem(t)}catch(e){}const n=Boolean(s||i);return n&&wt.markFinished(e),n}static markFinished(e){if(!vt.test(e||""))return;const t=wt.finishedKey(e);_.set(t,"1");try{localStorage.setItem(t,"1")}catch(e){}}static forgetFinished(e){if(!vt.test(e||""))return;const t=wt.finishedKey(e);_.set(t,"0");try{localStorage.removeItem(t)}catch(e){}}static finishedKey(e){return`hello_popup_submitted_${e}`}static async load(e,t={}){const s=new wt({id:e,html:await I.popups.get(e,{linked:t.linked})},t);return s.rendered=s.render(),s}constructor(e,{container:t=f.popup.container,linked:s=!1,shouldMount:i=()=>!0,onActivity:n=()=>{}}={}){this.data=e,this.container=t,this.linked=s,this.mounted=!1,this.rendered=Promise.resolve(!1),this.shouldMount=i,this.onActivity=n}async render(){if(!this.data.html||!this.shouldMount())return!1;const e=this.containerToAppendTo;return e?!!this.shouldMount()&&(this.linked&&this.data.html.setAttribute("data-hellotext--popup-linked-value","true"),this.data.html.addEventListener("hellotext--popup:activity",e=>{this.onActivity(e.detail.active)}),e.appendChild(this.data.html),this.mounted=!0,this.shouldMount()||this.unmount(),this.mounted):(console.warn(`Hellotext popup was not mounted because the container ${this.container} was not found.`),!1)}unmount(){this.data.html?.remove(),this.mounted=!1}get containerToAppendTo(){try{return document.querySelector(this.container)}catch(e){return null}}}class Tt{constructor(e){this.publicKey=e.public_key,this.serviceWorkerUrl=f.push.serviceWorkerUrl,this.channelId=f.push.channelId,this.ready=null,this.registrationPromise=null,this.subscribePromise=null,this.unsubscribePromise=null,this.syncPromise=null,this.subscription=null,this.retryTimeout=null,this.retryAttempts=0,this.disposed=!1}initialize(){return this.ready=this.restoreSubscription(),this.ready}async restoreSubscription(){const e=await this.getRegistration(),t=await e.pushManager.getSubscription();!this.disposed&&!this.unsubscribePromise&&t&&this.owns(t)&&(this.subscription=t,await this.sync())}subscribe({onPermission:e}={}){if(this.disposed)return Promise.resolve();if(this.unsubscribePromise)return Promise.reject(new Error("Push unsubscribe is in progress"));if(this.subscribePromise)return this.subscribePromise;const t="default"===Notification.permission?Notification.requestPermission():Promise.resolve(Notification.permission);return this.subscribePromise=this.createSubscription(t,e).finally(()=>{this.subscribePromise=null}),this.subscribePromise}async createSubscription(e,t){const s=await e;if(t?.(s),"granted"!==s)throw new Error("Push permission was not granted");const i=await this.getRegistration();if(this.disposed)return;let n=await i.pushManager.getSubscription();if(!this.disposed){if(n&&!this.owns(n))throw new Error("The existing Push subscription belongs to a different application");if(n||=await i.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this.applicationServerKey}),!this.disposed)return this.subscription=n,this.sync()}}unsubscribe(){return this.disposed?Promise.resolve():(this.unsubscribePromise||(this.clearRetryTimeout(),this.unsubscribePromise=this.removeSubscription().finally(()=>{this.unsubscribePromise=null})),this.unsubscribePromise)}subscriptionForSubmission(){return this.disposed||"undefined"==typeof Notification||"granted"!==Notification.permission||!this.subscription?null:{subscription:this.subscription.toJSON(),channel_id:this.channelId}}async removeSubscription(){await(this.ready?.catch(()=>{})),await(this.subscribePromise?.catch(()=>{})),await(this.syncPromise?.catch(()=>{}));const e=await this.getRegistration(),t=await e.pushManager.getSubscription()||this.subscription;if(this.disposed)return;if(!t)return Lt.eventEmitter.dispatch("push:unsubscribed"),null;if(!this.owns(t))throw new Error("The existing Push subscription belongs to a different application");this.subscription=t;const s=await I.pushIdentities.destroy({subscription:t.toJSON()});return s.failed?s:this.disposed?void 0:(await t.unsubscribe(),this.subscription=null,this.clearRetryTimeout(),Lt.eventEmitter.dispatch("push:unsubscribed"),s)}sync(){return this.disposed?Promise.resolve():(this.syncPromise||(this.clearRetryTimeout(),this.syncPromise=this.registerIdentity().finally(()=>{this.syncPromise=null})),this.syncPromise)}async registerIdentity(){try{const e=await I.pushIdentities.create({subscription:this.subscription.toJSON(),...this.channelId?{channel_id:this.channelId}:{}});return e.succeeded?this.retryAttempts=0:this.scheduleRetry(),e}catch(e){throw this.scheduleRetry(),e}}scheduleRetry(){this.disposed||this.unsubscribePromise||this.retryTimeout||this.retryAttempts>=3||(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.sync().catch(()=>{})},1e3*2**this.retryAttempts),this.retryAttempts+=1)}clearRetryTimeout(){clearTimeout(this.retryTimeout),this.retryTimeout=null}dispose(){this.disposed=!0,this.clearRetryTimeout()}get subscribed(){return!!this.subscription}get applicationServerKey(){const e=this.publicKey.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(4*Math.ceil(e.length/4),"=")),e=>e.charCodeAt(0))}owns(e){const t=e.options?.applicationServerKey;if(!t)return!1;const s=new Uint8Array(t),i=this.applicationServerKey;return s.length===i.length&&s.every((e,t)=>e===i[t])}getRegistration(){return this.registrationPromise||(this.registrationPromise=this.loadRegistration().catch(e=>{throw this.registrationPromise=null,e})),this.registrationPromise}async loadRegistration(){if(this.serviceWorkerUrl){const e=await navigator.serviceWorker.register(this.serviceWorkerUrl);!e.active||e.installing||e.waiting||await e.update();const t=e.installing||e.waiting||e.active;return"activated"===t?.state?e:new Promise((s,i)=>{const n=setTimeout(()=>r(new Error("Push service worker did not become active")),1e4),r=r=>{clearTimeout(n),t?.removeEventListener("statechange",a),r?i(r):s(e)},a=()=>{"activated"===t?.state&&r(),"redundant"===t?.state&&r(new Error("Push service worker installation failed"))};t?.addEventListener("statechange",a),a()})}return new Promise((e,t)=>{const s=setTimeout(()=>t(new Error("Push service worker is not available")),1e4);navigator.serviceWorker.ready.then(t=>{clearTimeout(s),e(t)},e=>{clearTimeout(s),t(e)})})}static get supported(){return"undefined"!=typeof window&&!0===window.isSecureContext&&"undefined"!=typeof navigator&&"serviceWorker"in navigator&&"undefined"!=typeof PushManager&&"undefined"!=typeof Notification}}class St{constructor(e,t,s){this.business=t,this.push=s,this.disposed=!1,this.showRequest=0,this.controller=null,this.suspended=!1,this.resumed=Promise.resolve(),this.element=(new DOMParser).parseFromString(e.html,"text/html").querySelector('[data-controller~="hellotext--alert"]'),this.connected=new Promise(e=>{this.resolveConnected=e}),this.onConnect=this.onConnect.bind(this),this.ready=this.render()}onConnect(e){this.controller=e.detail.controller,this.controller.alert=this,this.resolveConnected(!0)}async render(){return!!this.element&&(this.element.addEventListener("hellotext--alert:connected",this.onConnect),!(!await this.business.stylesheetLoaded||this.disposed)&&(document.body.appendChild(this.element),this.connected))}async show(e,t={}){const s=++this.showRequest;return!(!await this.ready||this.disposed||s!==this.showRequest)&&(await this.resumed,!this.disposed&&s===this.showRequest&&this.controller.show(e,t))}hide(){this.showRequest+=1,this.controller?.close()}suspend(){this.disposed||this.suspended||(this.suspended=!0,this.resumed=new Promise(e=>{this.resolveResumed=e}),this.controller?.close())}resume(){!this.disposed&&this.suspended&&(this.suspended=!1,this.resolveResumed())}dispose(){this.disposed=!0,this.hide(),this.resolveConnected(!1),this.resolveResumed?.(),this.element?.removeEventListener("hellotext--alert:connected",this.onConnect),this.element?.remove()}}class Ct{static async load(e){const t=new Ct({id:e,html:await I.webchats.get(e)});return t.rendered=t.render(),t}constructor(e){this.data=e,this.mounted=!1,this.rendered=Promise.resolve(!1)}async render(){return this.applyBehaviourOverride(),await this.stylesheetLoaded?(this.containerToAppendTo.appendChild(this.data.html),this.markCoexistingWidgets(),this.mounted=!0,!0):(console.warn("Hellotext webchat was not mounted because its stylesheet failed to load."),!1)}applyBehaviourOverride(){f.webchat.hasBehaviourOverride&&f.webchat.behaviour&&this.data.html.setAttribute("data-hellotext--webchat-behaviour-value",JSON.stringify(this.serializedBehaviour))}get serializedBehaviour(){const e=f.webchat.behaviour;return{trigger:this.serializeTrigger(e.trigger),delay_seconds:e.delaySeconds,first_visit_only:e.firstVisitOnly,once_per_session:e.oncePerSession}}serializeTrigger(e){return"onLoad"===e?"on_load":"onClick"===e?"on_click":e}get containerToAppendTo(){return document.querySelector(f.webchat.container)}get stylesheetLoaded(){return L.waitForStylesheet(L.latestStylesheet)}markCoexistingWidgets(){const e=this.data.html,t=document.querySelector(".hellotext--whatsapp-widget");e&&t&&(e.classList.add("hellotext--with-whatsapp-widget"),t.classList.add("hellotext--with-webchat"))}}class At{static async load(e){const t=new At({id:e,html:await I.whatsappWidgets.get(e)});return t.rendered=t.render(),t}constructor(e){this.data=e,this.mounted=!1,this.rendered=Promise.resolve(!1)}async render(){if(!this.data.html)return!1;const e=this.containerToAppendTo;return e?await this.stylesheetLoaded?(this.linkThroughClickEndpoint(),e.appendChild(this.data.html),this.markCoexistingWidgets(),this.mounted=!0,!0):(console.warn("Hellotext WhatsApp widget was not mounted because its stylesheet failed to load."),!1):(console.warn(`Hellotext WhatsApp widget was not mounted because the container ${f.whatsapp.container} was not found.`),!1)}linkThroughClickEndpoint(){const e=this.data.html.getAttribute("data-hellotext--whatsapp-widget-click-url-value"),t=j.session;e&&t&&this.data.html.querySelectorAll("a[href]").forEach(s=>{const i=this.clickHref(e,s.getAttribute("href"),t);i&&s.setAttribute("href",i)})}clickHref(e,t,s){try{const i=new URL(e),n=new URL(t,i);return n.origin!==i.origin||n.pathname!==i.pathname?null:(["number","text"].forEach(e=>{const t=n.searchParams.get(e);t&&i.searchParams.set(e,t)}),i.searchParams.set("session",s),i.toString())}catch(e){return null}}get containerToAppendTo(){try{return document.querySelector(f.whatsapp.container)}catch(e){return null}}get stylesheetLoaded(){return L.waitForStylesheet(L.latestStylesheet)}markCoexistingWidgets(){const e=document.querySelector(".hellotext--webchat:not(.hellotext--whatsapp-widget)"),t=this.data.html;e&&t&&(e.classList.add("hellotext--with-whatsapp-widget"),t.classList.add("hellotext--with-webchat"))}}class Et{static get id(){return _.get("hello_user_id")}static get source(){return _.get("hello_user_source")}static get fingerprint(){return _.get("hello_user_identification_hash")}static remember(e,t,s){t&&_.set("hello_user_source",t),s&&_.set("hello_user_identification_hash",s),_.set("hello_user_id",e)}static forget(){_.delete("hello_user_id"),_.delete("hello_user_source"),_.delete("hello_user_identification_hash")}static get identificationData(){return this.id?{id:this.id,source:this.source}:{}}}function Ot(e){if(null!=e){if("string"==typeof e){const t=e.trim();return""===t?void 0:t}if(Array.isArray(e))return e.map(e=>Ot(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){const t=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,s)=>{const i=Ot(e[s]);return void 0!==i&&(t[s]=i),t},{});return Object.keys(t).length>0?t:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function xt(e,t,s={}){const i=Ot({session:e,user_id:t,...s})||{};return JSON.stringify(i)}class kt{static matches(e,t){return!!e&&e===t}static async generate(e,t,s={}){return await async function(e){if(!globalThis.crypto?.subtle||"undefined"==typeof TextEncoder)return function(e){let t=5381;for(let s=0;s>>0).toString(16)}`}(e);const t=await globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e));return`v1:${Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}`}(xt(e,t,s))}}const Mt=["source","medium","campaign"],It={"product.viewed":"activity.product_viewed","cart.added":"activity.cart_added","order.placed":"activity.purchase_completed","product.purchased":"activity.purchase_completed","form.completed":"activity.form_completed"};class Pt{static eventEmitter=new r;static activities=new Set;static pageViews=1;static visitCampaign={};static visitorType="new";static visitSignalsLoaded=!1;static lastPageUrl;static lastPageRoute;static pageStartedAt;static visitStartedAt;static forms;static business;static popup;static webchat;static whatsapp;static push;static alert;static initializationVersion=0;static async initialize(e,t={}){const s=++this.initializationVersion;this.popup?.unmount?.(),this.popup=void 0,this.alert?.dispose(),this.alert=null,this.push?.dispose(),this.push=null;const i=new L(e);this.business=i,this.page=new V,f.assign({push:{},...t}),j.initialize(this.page),this.initializeVisitSignals(),this.forms?.mutationObserver?.disconnect(),this.forms=new bt,this.query=new b;const n=wt.linkedId,r=await i.hydrate();if(this.business!==i)return;!1!==t.push&&r?.push?.public_key&&Tt.supported&&(this.push=new Tt(r.push),this.push.initialize().catch(e=>{console.warn("Hellotext Push initialization failed:",e)}),r.alert?.html&&(this.alert=new St(r.alert,i,this.push)));const a=!1!==t.popup&&this.deepMergePlainObjects(r&&r.popup||{},n?{...t.popup,id:n}:t.popup||{}),o=!1!==t.webchat&&this.mergeWebchatConfig(r&&r.webchat||{},t.webchat||{}),c=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(r&&r.whatsapp||{},t.whatsappWidget||{}),l=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");f.webchat.behaviourOverride=l;const h=[];if(o&&o.id&&(f.webchat.assign(o),h.push(Ct.load(o.id).then(e=>{this.business===i&&(this.webchat=e)}))),c&&c.id&&(f.whatsapp.assign(c),h.push(At.load(c.id).then(e=>{this.business===i&&(this.whatsapp=e)}))),a&&a.id&&(n||!wt.finished(a.id))){const e={container:"body",device:"auto",...a};f.popup.assign(e);const t=this.alert;let r=!1;t?.suspend(),h.push(wt.load(e.id,{container:e.container,linked:Boolean(n),shouldMount:()=>this.business===i&&this.initializationVersion===s,onActivity:e=>{e?(r=!0,t?.suspend()):r?t?.dispose():t?.resume()}}).then(e=>{e.mounted||t?.resume(),this.business===i&&this.initializationVersion===s&&(this.popup=e)}).catch(e=>{throw t?.resume(),e}))}await Promise.all(h),this.business===i&&this.initializationVersion===s&&"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}static mergeWebchatConfig(e,t){return this.deepMergePlainObjects(e,t)}static mergeWhatsAppConfig(e,t){return this.deepMergePlainObjects(e,t)}static deepMergePlainObjects(e,t){const s={...e};return Object.entries(t).forEach(([e,t])=>{this.isPlainObject(t)&&this.isPlainObject(s[e])?s[e]=this.deepMergePlainObjects(s[e],t):s[e]=t}),s}static isPlainObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static async track(e,t={}){if(this.notInitialized)throw new yt;if(!1===f.tracking)return;const s=this.business,i=this.session,n={...t&&t.headers||{},...this.headers},r={...Et.identificationData,...t.user_parameters||{}},a=t&&t.url?new V(t.url):this.page,o={session:i,user_parameters:r,action:e,...t,...a.trackingData};delete o.headers;const c=await I.events.create({headers:n,body:o,keepalive:M(o)}),l=this.trackedAtMilliseconds(t.tracked_at);return c.succeeded&&this.business===s&&this.session===i&&(null===l||l>=this.visitStartedAt)&&this.recordActivity(e),c}static recordActivity(e){const t=It[e];t&&(this.activities.add(t),this.writeStorage("sessionStorage",this.visitStorageKey("activities"),JSON.stringify([...this.activities])),this.eventEmitter.dispatch("activity:occurred",{action:e,field:t}))}static trackedAtMilliseconds(e){return null==e||""===e?null:"number"==typeof e?Number.isFinite(e)?e<1e12?1e3*e:e:Number.NaN:new Date(e).getTime()}static initializeVisitSignals(){const e=!this.visitSignalsLoaded;if(this.visitSignalsLoaded=!0,e){this.pageViews=0,this.lastPageUrl=void 0,this.lastPageRoute=void 0,this.activities=new Set(this.readStoredActivities()),this.visitCampaign=this.readStoredVisitCampaign();const e=this.readStorage("sessionStorage",this.visitStorageKey("visitor-type"));this.visitorType=["new","returning"].includes(e)?e:void 0,this.visitorType||(this.visitorType=this.readStorage("localStorage",this.visitStorageKey("seen"))?"returning":"new",this.writeStorage("sessionStorage",this.visitStorageKey("visitor-type"),this.visitorType),this.writeStorage("localStorage",this.visitStorageKey("seen"),"1"));const t=Number(this.readStorage("sessionStorage",this.visitStorageKey("started-at")));this.visitStartedAt=Number.isFinite(t)&&t>0?t:this.initialPageStartedAt(),this.writeStorage("sessionStorage",this.visitStorageKey("started-at"),String(this.visitStartedAt))}this.rememberVisitCampaign($.paramsFrom(window.location.search)),(e||this.lastPageRoute!==this.pageRoute())&&this.recordPageView()}static rememberVisitCampaign(e){const t=Object.fromEntries(Mt.flatMap(t=>{const s="string"==typeof e?.[t]?e[t].trim():"";return""===s?[]:[[t,s]]}));0!==Object.keys(t).length&&(this.visitCampaign=t,this.writeStorage("sessionStorage",this.visitStorageKey("campaign"),JSON.stringify(t)))}static readStoredVisitCampaign(){try{const e=JSON.parse(this.readStorage("sessionStorage",this.visitStorageKey("campaign"))||"{}");return null===e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([e,t])=>Mt.includes(e)&&"string"==typeof t))}catch(e){return{}}}static recordPageView(){const e=this.visitStorageKey("page-views"),t=Number(this.readStorage("sessionStorage",e)),s=!this.lastPageUrl;this.pageViews=Number.isInteger(t)&&t>0?t+1:this.pageViews+1,this.lastPageUrl=window.location.href,this.lastPageRoute=this.pageRoute(),this.pageStartedAt=s?this.initialPageStartedAt():Date.now(),this.writeStorage("sessionStorage",e,String(this.pageViews))}static initialPageStartedAt(){const e=window.performance?.getEntriesByType?.("navigation")?.[0]?.name;return e&&this.pageRoute(e)!==this.pageRoute()?Date.now():window.performance?.timeOrigin||Date.now()}static pageRoute(e=window.location.href){return V.route(e)}static readStoredActivities(){try{const e=JSON.parse(this.readStorage("sessionStorage",this.visitStorageKey("activities"))||"[]");return Array.isArray(e)?e.filter(e=>Object.values(It).includes(e)):[]}catch(e){return[]}}static visitStorageKey(e){return`hellotext:visit:${e}`}static storage(e){try{return window[e]}catch(e){return null}}static readStorage(e,t){try{return this.storage(e)?.getItem(t)}catch(e){return null}}static writeStorage(e,t,s){try{this.storage(e)?.setItem(t,s)}catch(e){}}static async identify(e,t={}){const s=await kt.generate(this.session,e,t);if(kt.matches(Et.fingerprint,s))return new v(!0,{json:async()=>({already_identified:!0})});const i=await I.identifications.create({user_id:e,...t});return i.succeeded&&Et.remember(e,t.source,s),i}static forget(){Et.forget()}static on(e,t){this.eventEmitter.addSubscriber(e,t)}static removeEventListener(e,t){this.eventEmitter.removeSubscriber(e,t)}static get session(){return j.session}static get isInitialized(){return void 0!==j.session}static get notInitialized(){return!this.business||void 0===this.business.id}static get headers(){if(this.notInitialized)throw new yt;return{Authorization:`Bearer ${this.business.id}`,Accept:"application/json","Content-Type":"application/json"}}}const Lt=Pt,_t=new Map,Nt=class extends i.xI{static values={sections:Array};static targets=["title","description","primaryAction","secondaryAction"];initialize(){this.showRequest=0,this.submitting=!1,this.registrationResumed=Promise.resolve(),this.onStorage=this.onStorage.bind(this),this.onUnsubscribed=this.onUnsubscribed.bind(this)}connect(){this.dispatch("connected",{detail:{controller:this}}),window.addEventListener("storage",this.onStorage),Lt.eventEmitter.addSubscriber("push:unsubscribed",this.onUnsubscribed),this.registrationResumed=this.resumeRegistration()}disconnect(){this.close(),window.removeEventListener("storage",this.onStorage),Lt.eventEmitter.removeSubscriber("push:unsubscribed",this.onUnsubscribed)}onUnsubscribed(){this.alert&&(this.pendingRegistration=null)}onStorage(e){e.key===this.storageKey&&this.dismissal.dismissedUntil>Date.now()&&this.close()}async show(e,{force:t=!1,title:s,description:i,primaryAction:n,secondaryAction:r}={}){const a=++this.showRequest,o=this.sectionsValue.find(t=>t.kind===e);return o?(await(this.alert.push.ready?.catch(()=>{})),await this.registrationResumed,!(a!==this.showRequest||this.alert.disposed||!this.element.isConnected||(this.unavailable||!t&&this.dismissal.dismissedUntil>Date.now()?(this.close(),1):(this.titleTarget.textContent=s??o.title,this.descriptionTarget.textContent=i??o.description,this.primaryActionTarget.textContent=n??o.primary_action,this.secondaryActionTarget.textContent=r??o.secondary_action,this.kind=e,this.page=Lt.page.trackingData.page,this.element.hidden=!1,this.record("shown"),Lt.eventEmitter.dispatch("alert:shown",{kind:e}),0)))):(this.close(),!1)}hide(){if(this.element.hidden||this.submitting)return;const e=this.dismissal.dismissals+1,t={dismissals:e,dismissedUntil:Date.now()+864e5*(1===e?7:30)};_t.set(this.storageKey,t);try{localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(e){}this.close(),this.record("dismissed"),Lt.eventEmitter.dispatch("alert:dismissed",{kind:this.kind})}close(){this.showRequest+=1,this.element.hidden=!0}async subscribe(){if(this.submitting||this.element.hidden)return;if(this.unavailable)return this.close();this.submitting=!0,this.primaryActionTarget.disabled=!0,this.secondaryActionTarget.disabled=!0,this.element.setAttribute("aria-busy","true");const e={section:this.kind,page:this.page};try{this.record("accepted"),Lt.eventEmitter.dispatch("alert:accepted",{kind:this.kind});const t=await this.alert.push.subscribe({onPermission:t=>this.recordPermission(t,e)});return t?.succeeded&&this.recordRegistration(t,e),this.unavailable&&this.close(),t?.failed&&this.dispatch("error",{detail:{response:t}}),t}catch(e){this.unavailable&&this.close(),this.dispatch("error",{detail:{error:e}})}finally{this.submitting=!1,this.primaryActionTarget.disabled=!1,this.secondaryActionTarget.disabled=!1,this.element.removeAttribute("aria-busy")}}async record(e,{section:t=this.kind,page:s=this.page,pushIdentity:i}={}){try{const n=await I.pushAlerts.create({section:t,kind:e,page:s,pushIdentity:i});n.failed&&console.warn("Hellotext Smart Alert submission failed:",n)}catch(e){console.warn("Hellotext Smart Alert submission failed:",e)}}recordPermission(e,t){"granted"===e&&(this.pendingRegistration=t),"granted"!==e&&"denied"!==e||this.record(e,t)}async recordRegistration(e,t){this.pendingRegistration=null;try{const{id:s}=await e.data.clone().json();s&&this.record("registered",{...t,pushIdentity:s})}catch(e){console.warn("Hellotext Smart Alert submission failed:",e)}}async resumeRegistration(){if(!this.alert)return;const e=this.pendingRegistration;if(e&&(await(this.alert.push.ready?.catch(()=>{})),!this.alert.disposed&&this.pendingRegistration))if("undefined"!=typeof Notification&&"granted"===Notification.permission)try{const t=await this.alert.push.subscribe();t?.succeeded&&this.recordRegistration(t,e)}catch(e){}else this.pendingRegistration=null}get pendingRegistration(){try{const e=JSON.parse(localStorage.getItem(this.registrationKey));return"string"==typeof e?.section?e:null}catch(e){return null}}set pendingRegistration(e){try{e?localStorage.setItem(this.registrationKey,JSON.stringify(e)):localStorage.removeItem(this.registrationKey)}catch(e){}}get registrationKey(){return`${this.storageKey}:registration`}get unavailable(){return this.alert.push.disposed||this.alert.push.subscribed||"undefined"==typeof Notification||"denied"===Notification.permission}get storageKey(){return`hellotext:alert:${this.alert.business.id}`}get dismissal(){try{const e=JSON.parse(localStorage.getItem(this.storageKey));Number.isSafeInteger(e?.dismissals)&&e.dismissals>0&&Number.isFinite(e.dismissedUntil)&&e.dismissedUntil>=0&&_t.set(this.storageKey,e)}catch(e){}return _t.get(this.storageKey)||{dismissals:0,dismissedUntil:0}}},Dt=class extends i.xI{static values={data:Object,step:{type:Number,default:1}};static targets=["inputContainer","input","button","otpContainer"];initialize(){this.form=new ft(this.dataValue,this.element),this.onInput=this.trackStart.bind(this)}connect(){super.connect(),this.element.addEventListener("submit",this.submit.bind(this)),this.element.addEventListener("input",this.onInput),"INPUT"!==document.activeElement.tagName&&this.inputTargets[0].focus()}disconnect(){this.element.removeEventListener("input",this.onInput)}async trackStart(){if(this.trackingStart)return;const e=`hellotext--form--${this.form.id}--tracked-start`,t=`${Lt.session}:${this.localDate}`;if(Lt.readStorage("localStorage",e)!==t){this.trackingStart=!0;try{const s=await Lt.track("form.started",{form_id:this.form.id,tracked_at:(new Date).toISOString()});s?.succeeded&&Lt.writeStorage("localStorage",e,t)}catch(e){}finally{this.trackingStart=!1}}}get localDate(){const e=new Date;return[e.getFullYear(),e.getMonth()+1,e.getDate()].map(e=>String(e).padStart(2,"0")).join("-")}async submit(e){if(e.preventDefault(),this.invalid)return this.showErrorMessages();this.clearErrorMessages(),this.formData=Object.fromEntries(new FormData(this.element)),this.buttonTarget.disabled=!0;const t=await T.submit(this.form.id,this.formData);this.buttonTarget.disabled=!1;const s=await t.json();if(t.failed)return s.errors.forEach(e=>{const{type:t,parameter:s}=e,i=this.inputTargets.find(e=>e.name===s);i.setCustomValidity(Lt.business.locale.errors[t]),i.reportValidity(),i.addEventListener("input",()=>{i.setCustomValidity(""),i.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()}completed(){if(this.form.markAsCompleted(this.formData),!f.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof f.forms.successMessage?this.element.innerHTML=f.forms.successMessage:this.element.innerHTML=Lt.business.locale.forms[this.form.localeAuthKey]}showErrorMessages(){this.inputTargets.forEach(e=>{const t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}clearErrorMessages(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}inputTargetConnected(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}get requiredInputs(){return this.inputTargets.filter(e=>e.required)}get invalid(){return!this.element.checkValidity()}},Rt=class extends i.xI{static values={fadeDistance:{type:Number,default:64},id:String,kind:String,pageStartOffset:{type:Number,default:0},utm:Object};static targets=["carouselContainer","leftFade","rightFade","carouselCard"];connect(){this.updateFades(),this.observeContainerSize()}disconnect(){this.resizeObserver?.disconnect()}setId({detail:e}){this.idValue=e,this.element.id=e}onScroll(){this.updateFades()}quickReply({currentTarget:e}){const t=e.closest('[data-hellotext--message-target="carouselCard"]'),s=e.closest('[data-controller~="hellotext--message"]'),i=e.dataset.text||e.textContent.trim();this.dispatch("quickReply",{detail:{id:this.idValue,product:t?.dataset.id,buttonId:e.dataset.id,body:i,cardElement:t||s||e}})}addToCart({currentTarget:e}){const t=e.closest('[data-hellotext--message-target="carouselCard"]'),{id:s,reference:i,source:n}=t.dataset,r={product:s,quantity:1};this.hasUtmValue&&Lt.page.utm.save(this.utmValue),Lt.eventEmitter.dispatch("cart.added",{object_parameters:{items:[{...r,...i&&{reference:i},...n&&{source:n}}]},source:{kind:this.kindValue,message_id:this.idValue,button_id:e.dataset.id}})}moveToLeft(){if(!this.hasCarouselContainerTarget)return;const e=this.getPreviousPageScrollLeft(),t=this.carouselContainerTarget.scrollLeft-e;t<1||this.carouselContainerTarget.scrollBy({left:-t,behavior:"smooth"})}moveToRight(){if(!this.hasCarouselContainerTarget)return;const e=this.getNextPageScrollLeft()-this.carouselContainerTarget.scrollLeft;e<1||this.carouselContainerTarget.scrollBy({left:e,behavior:"smooth"})}getScrollAmount(){return this.getCardScrollAmount()}getCardScrollAmount(){const e=this.carouselContainerTarget.querySelector(".message__carousel_card");return e?e.offsetWidth+this.getGap():280}getPageScrollAmount(){const e=this.carouselContainerTarget.clientWidth-this.getGap();return e>0?e:this.getCardScrollAmount()}getNextPageScrollLeft(){const e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,s=this.getCardMetrics().find(e=>e.end>t+1),i=s?this.getPageAlignedScrollLeft(s.start):e+this.getPageScrollAmount(),n=e+this.getPageScrollAmount();return this.clampScrollLeft(i>e+1?i:n)}getPreviousPageScrollLeft(){const e=this.getCurrentScrollLeft();if(e<=1)return 0;const t=Math.max(e-this.getPageScrollAmount(),0);if(t<=1)return 0;const s=this.getCardMetrics(),i=s.find(s=>s.start>=t-1&&s.startt.start{const t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}getCardScrollLeft(e){const t=e.getBoundingClientRect(),s=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||s.left||s.width?t.left-s.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}getCurrentScrollLeft(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}clampScrollLeft(e){const t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}getGap(){const e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}getFadeDistance(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}getPageStartOffset(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}observeContainerSize(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}updateFades(){if(!this.hasCarouselContainerTarget)return;const e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);const t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),s=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/s),this.setFadeOpacity(this.rightFadeTarget,(e-t)/s)}setFadeOpacity(e,t){const s=Math.min(Math.max(t,0),1);s<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=s.toFixed(3),e.style.pointerEvents="auto")}hideFade(e){e.style.opacity="0",e.style.pointerEvents="none",e.setAttribute("aria-hidden","true"),e.setAttribute("tabindex","-1"),"disabled"in e&&(e.disabled=!0),e.classList.add("hidden")}},Ft="exact",$t="contains",Bt=["contains","does_not_contain"],Vt=/^https?:\/\/[^/?#]+/i,jt=/^\/\/[^/?#]+/,qt=/^[a-z][a-z0-9+.-]*:/i,Ut=/^(?:(?:[a-z0-9-]+\.)+[a-z]{2,}|localhost)(?::\d+)?\//i,zt=/(?:%[0-9a-f]{2})+/gi,Wt=/%(?:21|23|24|25|26|27|28|29|2a|2b|2c|2f|3a|3b|3d|3f|40|5b|5d)/i,Kt=/(^|\/)index\.(?:html?|php)$/;class Ht{static EXACT=Ft;static CONTAINS=$t;static modeFor(e){return Bt.includes(e)?$t:Ft}static canonical(e,{mode:t=Ft}={}){let s=String(e??"").trim();if(""===s)return"";if(s=this.withoutOrigin(s),null===s)return"";s=this.routePath(s),s=this.decoded(s),s=s.toLowerCase().replace(/ς/g,"σ").normalize("NFC").replace(/\/{2,}/g,"/");const i=Kt.test(s);return s=s.replace(Kt,"$1"),t===$t?(i&&(s=s.replace(/\/$/,"")),"/"===s?"":s):this.resolved(s)}static withoutOrigin(e){return Vt.test(e)?e.replace(Vt,""):jt.test(e)?e.replace(jt,""):qt.test(e)||Ut.test(e)?null:e}static routePath(e){const t=e.indexOf("#"),s=(-1===t?e:e.slice(0,t)).split("?")[0],i=-1===t?"":e.slice(t+1),n=i.startsWith("/")?i:i.startsWith("!/")?i.slice(1):"";return n?`${s}/${n.split("?")[0]}`:s}static decoded(e){return e.replace(zt,e=>{const t=e.match(/%[0-9a-f]{2}/gi)??[],s=[];let i=[];const n=()=>{i.length>0&&s.push(i.join("")),i=[]};return t.forEach(e=>{Wt.test(e)?(n(),s.push(e)):i.push(e)}),n(),s.map(e=>{if(Wt.test(e))return e;try{return decodeURIComponent(e)}catch(t){return e}}).join("")})}static resolved(e){const t=[];return e.split("/").forEach(e=>{""!==e&&"."!==e&&(".."===e?t.pop():t.push(e))}),`/${t.join("/")}`}}const Gt=["does_not_contain","is_not"],Jt=["session.scroll_depth","session.time_on_page","session.page_views"],Yt=["at_least","at_most","greater_than","less_than"],Zt=["page.path","page.title","session.referrer","session.language","session.visitor_type","session.browser","session.utm_source","session.utm_medium","session.utm_campaign"],Xt=["session.utm_source","session.utm_medium","session.utm_campaign"],Qt=["activity.product_viewed","activity.cart_added","activity.purchase_completed","activity.form_completed"],es={"session.language":["en","es","pt","fr","nl"],"session.visitor_type":["new","returning"],"session.browser":["chrome","safari","firefox","edge"]},ts={"session.scroll_depth":[1,100],"session.time_on_page":[1,3600],"session.page_views":[1,1e3]},ss=["contains","does_not_contain","is","is_not"],is=["is","is_not"];class ns{constructor(e){this.valid=null!==e&&"object"==typeof e&&!Array.isArray(e)&&Array.isArray(e.lanes),this.lanes=(this.valid?e.lanes:[]).map(e=>Array.isArray(e)?e:[null])}get empty(){return this.valid&&0===this.lanes.length}get needsMeasurements(){return this.lanes.some(e=>e.some(e=>Jt.includes(e?.field)))}get needsNavigation(){return this.lanes.some(e=>e.some(e=>this.validCondition(e)))}get needsTitle(){return this.lanes.some(e=>e.some(e=>"page.title"===e?.field))}get needsActivities(){return this.lanes.some(e=>e.some(e=>Qt.includes(e?.field)))}matches(e){return!!this.valid&&(!!this.empty||this.lanes.some(t=>this.laneMatches(t,e)))}laneMatches(e,t){if(!e.every(e=>this.validCondition(e)))return!1;const s=new Map;return e.forEach(e=>{const t=s.get(e?.field)||[];t.push(e),s.set(e?.field,t)}),[...s.entries()].every(([e,s])=>this.fieldGroupMatches(e,s,t))}fieldGroupMatches(e,t,s){if(!Zt.includes(e))return t.every(e=>this.conditionMatches(e,s));const i=t.filter(e=>!Gt.includes(e?.operator)),n=t.filter(e=>Gt.includes(e?.operator));return(0===i.length||i.some(e=>this.conditionMatches(e,s)))&&n.every(e=>this.conditionMatches(e,s))}conditionMatches(e,t){if(!this.validCondition(e))return!1;if(Qt.includes(e.field))return t.activities?.has?.(e.field)||t.activities?.includes?.(e.field);const s=this.actualValue(e.field,t);return Jt.includes(e.field)?this.thresholdMatches(e,s):"page.path"===e.field?this.pathMatches(e,s,t):this.stringMatches(e,s)}actualValue(e,t){switch(e){case"page.path":return void 0===t.path||null===t.path?t.path:`${t.path}${t.hash??""}`;case"page.title":return t.title;case"session.referrer":return t.referrer;case"session.scroll_depth":return t.scrollDepth;case"session.time_on_page":return t.timeOnPage;case"session.page_views":return t.pageViews;case"session.language":return t.language;case"session.visitor_type":return t.visitorType;case"session.browser":return t.browser;case"session.utm_source":return t.utm?.source;case"session.utm_medium":return t.utm?.medium;case"session.utm_campaign":return t.utm?.campaign;default:return}}validCondition(e){if(!e||"object"!=typeof e||!Array.isArray(e.values))return!1;if(Jt.includes(e.field)){const t=e.values[0],s=Number(t),[i,n]=ts[e.field];return Yt.includes(e.operator)&&1===e.values.length&&("number"==typeof t||"string"==typeof t&&/^\d+$/.test(t))&&Number.isInteger(s)&&s>=i&&s<=n}if(Qt.includes(e.field))return"occurred"===e.operator&&0===e.values.length;const t=es[e.field]?is:ss;if(!(Zt.includes(e.field)&&t.includes(e.operator)&&e.values.length>0&&e.values.every(e=>"string"==typeof e&&e.trim().length>0&&e.length<=512)))return!1;const s=es[e.field];return!s||e.values.every(e=>s.includes(e))}thresholdMatches(e,t){if(null==t||""===t)return!1;const s=Number(t),i=Number(e.values[0]);switch(e.operator){case"at_least":return s>=i;case"at_most":return s<=i;case"greater_than":return s>i;case"less_than":return sString(e).trim().toLowerCase():e=>String(e).toLowerCase(),n=i(t),r=e.values.some(t=>this.compare(e.operator,n,i(t)));return s?!r:r}pathMatches(e,t,s){const i=Gt.includes(e.operator);if(null==t)return i;const n=Ht.modeFor(e.operator),r=e.values.map(e=>Ht.canonical(e,{mode:n}));if(r.includes(""))return!1;const a=Ht.canonical(t),o=r.some(e=>n===Ht.CONTAINS?a.includes(e):a===e);return i?!o:o}compare(e,t,s){switch(e){case"contains":case"does_not_contain":return t.includes(s);case"is":case"is_not":return t===s;case"starts_with":return t.startsWith(s);case"ends_with":return t.endsWith(s);default:return!1}}}const rs=class extends i.xI{static targets=["bubble","dialog","step","completed","input","submitButton","globalError","resendButton","changeDestinationButton","deliveryCopy","pushDeliveryCopy","noDeliveryCopy","pushRequired","pushRequiredBrowser","pushRequiredError"];static values={capture:Object,device:String,hasBubble:Boolean,id:String,linked:Boolean,rules:Object};initialize(){this.stepIndex=0,this.trackingSteps=new Set,this.resendLabel=this.hasResendButtonTarget?this.resendButtonTarget.textContent.trim():"",this.rules=new ns(this.rulesValue),this.connectedAt=this.pageStartedAt()}connect(){Lt.eventEmitter.dispatch("popup:mounted"),this.hideUnsupportedPushFields(),this.requiredPushUnavailable&&(this.dismissed=!0),this.syncRequiredPush=this.syncRequiredPush.bind(this),this.element.addEventListener("change",this.syncRequiredPush),this.trackStepStart=this.trackStepStart.bind(this),this.element.addEventListener("input",this.trackStepStart),this.syncRequiredPush(),this.requireBirthdays(),this.linkedValue||this.submissionId||!wt.finished(this.idValue)||(this.dismissed=!0),this.deviceMatches=this.matchesDevice(),this.watchNavigation(),this.watchActivities(),this.evaluateDisplay(),this.watchMeasurements(),this.reportActivity(),this.closeIfFinishedElsewhere=this.closeIfFinishedElsewhere.bind(this),window.addEventListener("storage",this.closeIfFinishedElsewhere),window.addEventListener("pageshow",this.closeIfFinishedElsewhere)}disconnect(){this.stopResendCooldown(),this.stopWatchingMeasurements(),this.stopWatchingNavigation(),this.stopWatchingActivities(),window.removeEventListener("storage",this.closeIfFinishedElsewhere),window.removeEventListener("pageshow",this.closeIfFinishedElsewhere),this.element.removeEventListener("change",this.syncRequiredPush),this.element.removeEventListener("input",this.trackStepStart),this.reportActivity(!1)}pageStartedAt(){if(Number.isFinite(Lt.pageStartedAt))return Lt.pageStartedAt;const e=window.performance?.timeOrigin;return Number.isFinite(e)&&e<=Date.now()?e:Date.now()}watchNavigation(){if(this.onNavigation)return;this.lastRoute=this.pageRoute(),this.onNavigation=()=>this.scheduleNavigationEvaluation(),window.addEventListener("popstate",this.onNavigation),window.addEventListener("hashchange",this.onNavigation),window.addEventListener("turbo:load",this.onNavigation),window.addEventListener("turbo:render",this.onNavigation),this.rules.needsTitle&&document.head&&(this.titleObserver=new MutationObserver(()=>this.scheduleNavigationEvaluation()),this.titleObserver.observe(document.head,{childList:!0,characterData:!0,subtree:!0}));const e=window.history.pushState,t=window.history.replaceState;let s=!0;this.originalPushState=e,this.originalReplaceState=t,this.stopNavigationWrapper=()=>{s=!1},this.patchedPushState=(...t)=>{const i=e.apply(window.history,t);return s&&this.scheduleNavigationEvaluation(),i},this.patchedReplaceState=(...e)=>{const i=t.apply(window.history,e);return s&&this.scheduleNavigationEvaluation(),i},window.history.pushState=this.patchedPushState,window.history.replaceState=this.patchedReplaceState}scheduleNavigationEvaluation(){this.navigationTimer||(this.navigationTimer=setTimeout(()=>{this.navigationTimer=void 0;const e=this.pageRoute();e!==this.lastRoute&&(Lt.recordPageView(),this.connectedAt=Date.now()),this.lastRoute=e,this.currentUtmParams(),this.displayed||this.reevaluateDisplay()}))}pageRoute(){return Lt.pageRoute()}stopWatchingNavigation(){this.stopNavigationWrapper?.(),this.stopNavigationWrapper=void 0,this.titleObserver?.disconnect(),this.titleObserver=void 0,this.onNavigation&&(window.removeEventListener("popstate",this.onNavigation),window.removeEventListener("hashchange",this.onNavigation),window.removeEventListener("turbo:load",this.onNavigation),window.removeEventListener("turbo:render",this.onNavigation),this.onNavigation=void 0),this.navigationTimer&&(clearTimeout(this.navigationTimer),this.navigationTimer=void 0),window.history.pushState===this.patchedPushState&&(window.history.pushState=this.originalPushState),window.history.replaceState===this.patchedReplaceState&&(window.history.replaceState=this.originalReplaceState),this.patchedPushState=void 0,this.patchedReplaceState=void 0,this.originalPushState=void 0,this.originalReplaceState=void 0}watchMeasurements(){!this.displayed&&this.rules.needsMeasurements&&(this.onScroll=()=>this.reevaluateDisplay(),window.addEventListener("scroll",this.onScroll,{passive:!0}),this.measurementTimer=setInterval(()=>this.reevaluateDisplay(),1e3))}stopWatchingMeasurements(){this.onScroll&&(window.removeEventListener("scroll",this.onScroll),this.onScroll=void 0),this.measurementTimer&&(clearInterval(this.measurementTimer),this.measurementTimer=void 0)}watchActivities(){this.displayed||!this.rules.needsActivities||this.onActivity||(this.onActivity=()=>this.reevaluateDisplay(),Lt.on("activity:occurred",this.onActivity))}stopWatchingActivities(){this.onActivity&&(Lt.removeEventListener("activity:occurred",this.onActivity),this.onActivity=void 0)}closeIfFinishedElsewhere(e){"storage"===e.type&&e.key!==wt.finishedKey(this.idValue)||("pageshow"!==e.type||e.persisted)&&(this.submissionId||this.linkedValue||this.dismissed||wt.finished(this.idValue)&&this.close())}open(e){e&&e.preventDefault(),this.hasBubbleTarget&&(this.bubbleTarget.hidden=!0),this.dialogTarget.hidden=!1,Lt.eventEmitter.dispatch("popup:opened"),this.reportActivity(),this.trackStepView()}close(e){e&&e.preventDefault(),this.dismissed=!0,wt.markFinished(this.idValue),this.dialogTarget.hidden=!0,this.hasBubbleTarget&&(this.bubbleTarget.hidden=!0),this.element.hidden=!0,Lt.eventEmitter.dispatch("popup:closed"),this.reportActivity()}closeOnEscape(e){"Escape"!==e.key||this.element.hidden||this.dialogTarget.hidden||e.defaultPrevented||e.isComposing||this.close(e)}async next(e){if(e&&e.preventDefault(),!this.advancingStep){this.advancingStep=!0;try{if(this.clearCustomValidity(),!this.currentStepValid())return void this.showErrorMessages(this.currentStepInputs);if(this.clearErrorMessages(this.currentStepInputs),await this.subscribeForPushOnCurrentStep(),this.stepIndex{e.disabled=!0});let t=!1;try{await this.subscribeForPushOnCurrentStep(),t=this.requiredPushPending;const e=this.submissionPayload(),s=await C.submit(this.idValue,e,this.idempotencyKeyFor(e));if(s.failed)return void await this.handleSubmissionError(s);const i=await s.json();t||wt.markFinished(this.idValue),this.submissionId=i.id,this.submissionVerificationState=i.verification_state,this.submissionActionToken=i.action_token,this.submissionDeliveryStatus=i.delivery_status,this.submissionDeliveryChannel=i.delivery_channel,this.submissionDestination=i.destination,this.submissionCouponPush=!0===i.coupon_push,this.resetSubmissionRequest()}catch(e){return void this.showGlobalError()}finally{this.submitting=!1,this.submitButtonTargets.forEach(e=>{e.disabled=!1}),this.syncRequiredPush()}t?this.showPushRequired():this.showCompleted()}showPushRequired(){if(!this.hasPushRequiredTarget)return this.showCompleted();this.stepTargets.forEach(e=>{e.hidden=!0}),this.completedTarget.hidden=!0,this.hasPushRequiredErrorTarget&&(this.pushRequiredErrorTarget.hidden=!0);const e=wt.browser(),t=this.pushRequiredBrowserTargets.some(t=>t.dataset.pushBrowser===e);this.pushRequiredBrowserTargets.forEach(s=>{s.hidden=s.dataset.pushBrowser!==(t?e:"other")}),this.pushRequiredTarget.hidden=!1}async retryPush(e){e&&e.preventDefault(),this.submitting||this.pushSubscriptionPromise||(this.hasPushRequiredErrorTarget&&(this.pushRequiredErrorTarget.hidden=!0),"denied"!==("undefined"==typeof Notification?"denied":Notification.permission)&&(this.pushPermissionState=null,await this.subscribeForPush(e?.currentTarget?[e.currentTarget]:[])),"granted"===this.pushPermissionState?(this.pushRequiredTarget.hidden=!0,await this.submit(),this.completedTarget.hidden&&(this.pushRequiredTarget.hidden=!1)):this.hasPushRequiredErrorTarget&&(this.pushRequiredErrorTarget.hidden=!1))}showPushLoading(e){const t=this.element.dataset.pushLoadingLabel||"Enable notifications",s=e.map(e=>({button:e,content:e.innerHTML,busy:e.getAttribute("aria-busy")})),i=document.createElement("span"),n=document.createElement("span");n.setAttribute("aria-hidden","true"),n.style.visibility="hidden";let r=0;const a=()=>{r=(r+1)%4,i.textContent=".".repeat(r),n.textContent=".".repeat(3-r)};e.forEach(e=>{e.replaceChildren(document.createTextNode(t),i,n),e.setAttribute("aria-busy","true")}),a();const o=setInterval(a,450);return()=>{clearInterval(o),s.forEach(({button:e,content:t,busy:s})=>{!function(e,t){e.replaceChildren(mt(t,pt))}(e,t),null===s?e.removeAttribute("aria-busy"):e.setAttribute("aria-busy",s)})}}async subscribeForPushOnCurrentStep(){if(!this.currentStepInputs.some(e=>"push"===e.dataset.popupFieldKind&&e.checked)||this.pushPermissionState)return;const e=this.stepTargets[this.stepIndex]?.querySelectorAll('[data-hellotext--popup-target~="submitButton"], [data-action~="click->hellotext--popup#next"]')||[];return this.subscribeForPush(Array.from(e))}async subscribeForPush(e){if(!Lt.push)return;if(this.pushSubscriptionPromise)return this.pushSubscriptionPromise;const t=e.map(e=>({button:e,disabled:e.disabled}));t.forEach(({button:e})=>{e.disabled=!0});const s=this.showPushLoading(t.map(({button:e})=>e)),i="undefined"==typeof Notification?"default":Notification.permission;let n,r;try{n=Lt.push.subscribe()}catch(e){return this.pushPermissionState="denied"===i?"denied":"registration_failed",s(),void t.forEach(({button:e,disabled:t})=>{e.disabled=t})}const a=new Promise(e=>{r=setTimeout(()=>{this.pushPermissionState||="registration_failed",e()},15e3)}),o=n.then(e=>{this.pushPermissionState=e?.failed?"registration_failed":"undefined"!=typeof Notification&&"granted"===Notification.permission?"granted":"denied"===i?"denied":"dismissed"}).catch(()=>{this.pushPermissionState="undefined"!=typeof Notification&&"denied"===Notification.permission?"denied":"undefined"!=typeof Notification&&"default"===Notification.permission?"dismissed":"registration_failed"});return this.pushSubscriptionPromise=Promise.race([o,a]).finally(()=>{clearTimeout(r),s(),t.forEach(({button:e,disabled:t})=>{e.disabled=t}),this.pushSubscriptionPromise=null}),this.pushSubscriptionPromise}get requiredPushUnavailable(){return this.inputTargets.some(e=>"push"===e.dataset.popupFieldKind&&e.required&&e.disabled)}get requiredPushPending(){return this.inputTargets.some(e=>"push"===e.dataset.popupFieldKind&&e.required&&!e.disabled&&e.checked)&&"granted"!==this.pushPermissionState}syncRequiredPush(){this.submitting||this.pushSubscriptionPromise||this.stepTargets.forEach(e=>{const t=this.inputsForStep(e).some(e=>"push"===e.dataset.popupFieldKind&&e.required&&!e.disabled&&!e.checked);e.querySelectorAll('[data-hellotext--popup-target~="submitButton"], [data-action~="click->hellotext--popup#next"]').forEach(e=>{e.disabled=t})})}hideUnsupportedPushFields(){this.inputTargets.filter(e=>"push"===e.dataset.popupFieldKind).forEach(e=>{if("true"===e.dataset.popupPushAvailable&&Lt.push)return;e.checked=!1,e.disabled=!0;const t=e.closest(".hellotext--popup-field")||e.parentElement;t&&(t.hidden=!0)})}reevaluateDisplay(){const e=this.displayed;this.evaluateDisplay(),this.displayed&&!e&&this.reportActivity()}evaluateDisplay(){this.dismissed||!this.linkedValue&&!this.deviceMatches?this.element.hidden=!0:this.displayed||(this.linkedValue||this.rules.matches(this.pageContext())?(this.displayed=!0,this.stopWatchingMeasurements(),this.stopWatchingActivities(),this.showInitialState()):this.element.hidden=!0)}pageContext(){return{url:window.location.href,path:window.location.pathname,hash:window.location.hash,title:document.title,referrer:document.referrer||void 0,scrollDepth:this.scrollDepth(),timeOnPage:Math.floor((Date.now()-this.connectedAt)/1e3),pageViews:Lt.pageViews,language:this.browserLanguage(),visitorType:Lt.visitorType,browser:this.browserName(),utm:this.currentUtmParams(),activities:Lt.activities}}currentUtmParams(){const e=window.location.hash.match(/^#!?\/[^?]*\?(.*)$/)?.[1],t=this.popupUtmParams($.paramsFrom(e)),s=this.popupUtmParams($.paramsFrom(window.location.search)),i=Object.keys(s).length>0?s:t;return Object.keys(i).length>0?(Lt.rememberVisitCampaign(i),i):this.popupUtmParams(Lt.visitCampaign)}popupUtmParams(e){return Object.fromEntries(Object.entries(e||{}).flatMap(([e,t])=>["source","medium","campaign"].includes(e)&&"string"==typeof t?""===t.trim()?[]:[[e,t.trim()]]:[]))}browserName(){const e=window.navigator.userAgentData?.brands;if(Array.isArray(e)){const t=e.map(({brand:e})=>e?.toLowerCase()||"");if(t.some(e=>e.includes("edge")))return"edge";if(t.some(e=>e.includes("opera")||e.includes("samsung")))return;if(t.some(e=>e.includes("chrome")))return"chrome"}const t=window.navigator.userAgent?.toLowerCase()||"";return/edg([ea]|ios)?\//.test(t)?"edge":t.includes("opr/")||t.includes("opera/")||t.includes("samsungbrowser/")?void 0:t.includes("firefox/")||t.includes("fxios/")?"firefox":t.includes("chrome/")||t.includes("crios/")?"chrome":t.includes("safari/")?"safari":void 0}browserLanguage(){const e=window.navigator.languages?.[0]||window.navigator.language;return e?.split("-")[0]?.toLowerCase()}scrollDepth(){const e=Math.max(document.documentElement.scrollHeight,window.innerHeight),t=window.scrollY+window.innerHeight;return Math.max(0,Math.min(100,Math.round(t/e*100)))}showInitialState(){if(this.element.hidden=!1,this.hasBubbleValue&&this.hasBubbleTarget&&!this.linkedValue)return this.bubbleTarget.hidden=!1,void(this.dialogTarget.hidden=!0);this.hasBubbleTarget&&(this.bubbleTarget.hidden=!0),this.dialogTarget.hidden=!1,Lt.eventEmitter.dispatch("popup:opened"),this.trackStepView()}showStep(e){this.stepIndex=e,this.stepTargets.forEach((t,s)=>{t.hidden=s!==e}),this.completedTarget.hidden=!0,this.hasPushRequiredTarget&&(this.pushRequiredTarget.hidden=!0),this.reportActivity(),this.trackStepView()}showCompleted(){this.stepTargets.forEach(e=>{e.hidden=!0}),this.interpolateCompletionCopy(),this.configureCompletionActions(),this.hasPushRequiredTarget&&(this.pushRequiredTarget.hidden=!0),this.completedTarget.hidden=!1,this.reportActivity()}trackStepView(){this.element.hidden||this.dialogTarget.hidden||!this.completedTarget.hidden||this.trackStep("popup.step_viewed",this.stepTargets[this.stepIndex])}trackStepStart(e){const t=e.target?.dataset?.popupStepId;t&&this.trackStep("popup.step_started",this.stepTargets.find(e=>e.dataset.stepId===t))}async trackStep(e,t){const s=t?.dataset.stepId;if(!s)return;const i=`hellotext--popup--${this.idValue}--${s}--${e}`,n=`${Lt.session}:${this.localDate}`;if(!this.trackingSteps.has(i)&&Lt.readStorage("localStorage",i)!==n){this.trackingSteps.add(i);try{const t=await Lt.track(e,{popup_id:this.idValue,step_id:s,tracked_at:(new Date).toISOString()});t?.succeeded&&Lt.writeStorage("localStorage",i,n)}catch(e){}finally{this.trackingSteps.delete(i)}}}get localDate(){const e=new Date;return[e.getFullYear(),e.getMonth()+1,e.getDate()].map(e=>String(e).padStart(2,"0")).join("-")}reportActivity(e=!this.element.hidden&&!this.dialogTarget.hidden&&this.completedTarget.hidden){this.element.dispatchEvent(new CustomEvent("hellotext--popup:activity",{bubbles:!0,detail:{active:e}}))}interpolateCompletionCopy(){const e=this.completedIdentity;if(!e)return;const t={destination:e.value,channel:this.completionChannelLabel(this.submissionDeliveryChannel||e.kind)};this.completionTextTemplates.forEach(({node:e,template:s})=>{e.nodeValue=s.replace(/\{(destination|channel)\}/g,(e,s)=>t[s]||e)})}completionChannelLabel(e){return this.element.dataset[`channelLabel${e[0]?.toUpperCase()}${e.slice(1)}`]||e}identityValue(e){const t=this.inputValue(e).trim();if(!t)return"";if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;const s=this.phoneCountryPrefix(e);if(s)return`${s}${this.phoneDigits(t)}`;const i=e.dataset.popupPhonePrefix;return i?`${i}${t.replace(/^0+/,"")}`:t}asciiDigits(e){const t=e=>/\p{Nd}/u.test(e);return e.replace(/\p{Nd}/gu,e=>{let s=e.codePointAt(0);const i=s;for(;t(String.fromCodePoint(s-1));)s-=1;return(i-s)%10})}phoneDigits(e){return this.asciiDigits(e).replace(/\D/g,"")}phoneCountryPrefix(e){const t=e.closest("[data-popup-phone]")?.querySelector("[data-popup-phone-country]");return t?.selectedOptions?.[0]?.dataset.prefix}selectPhoneCountry(e){const t=e.target,s=t.closest("[data-popup-phone]")?.querySelector("[data-popup-phone-country-label]");s&&(s.textContent=t.selectedOptions[0]?.dataset.label||"")}filterPhone(e){const t=e.target,s=t.value.replace(/[^\p{Nd}+() .\-]/gu,"");s!==t.value&&(t.value=s)}requireBirthdays(){this.element.querySelectorAll("[data-popup-birthday]").forEach(e=>{const t=e.querySelector('[data-popup-field-kind="birthday"]');t&&(t.required=Boolean(e.querySelector("select[required]")))})}selectBirthday(e){const t=e.target.closest("[data-popup-birthday]"),s=t?.querySelector('[data-popup-field-kind="birthday"]');if(!s)return;const[i,n,r]=["day","month","year"].map(e=>t.querySelector(`[data-popup-birthday-part="${e}"]`)),a=n.value?new Date(Date.UTC(Number(r.value)||2e3,Number(n.value),0)).getUTCDate():31;Array.from(i.options).forEach(e=>{e.value&&(e.disabled=Number(e.value)>a)}),Number(i.value)>a&&(i.value=""),s.value=i.value&&n.value&&r.value?`${r.value}-${n.value}-${i.value}`:""}submissionValue(e){const t=this.inputValue(e),s="phone"===e.dataset.popupFieldKind&&this.phoneCountryPrefix(e),i="string"==typeof t?t.trim():"";return s&&i?i.startsWith("+")?this.asciiDigits(t):`${s}${this.phoneDigits(i)}`:t}configureCompletionActions(){const e="not_required"!==this.submissionDeliveryStatus;if(this.revealCompletionCopy(e),!e)return void this.completedTarget.querySelector("[data-delivery-actions]")?.setAttribute("hidden","");const t=this.completedIdentity;t&&(this.hasChangeDestinationButtonTarget&&(this.changeDestinationButtonTarget.textContent=this.changeDestinationButtonTarget.dataset[`${t.kind}Label`],this.changeDestinationButtonTarget.hidden=!1),this.submissionId&&this.submissionActionToken&&"queued"===this.submissionDeliveryStatus&&"unverified"===this.submissionVerificationState&&this.hasResendButtonTarget&&(this.resendButtonTarget.hidden=!1,this.startResendCooldown(60)))}async resend(e){if(e&&e.preventDefault(),this.submissionId&&this.submissionActionToken&&!this.resendPending&&!this.resendCooldownActive&&this.completedIdentity){this.resendPending=!0,this.resendButtonTarget.disabled=!0;try{const e=await C.resend(this.idValue,this.submissionId,this.submissionActionToken),t=Number(e.data.headers?.get("Retry-After"))||60;e.succeeded||429===e.data.status?this.startResendCooldown(t):this.resendButtonTarget.disabled=!1}catch(e){this.resendButtonTarget.disabled=!1}finally{this.resendPending=!1}}}async changeDestination(e){if(e&&e.preventDefault(),!this.submissionId||!this.submissionActionToken||this.changeDestinationPending)return;const t=this.completedIdentity?.input;if(!t)return;const s=this.stepTargets.findIndex(e=>e.dataset.stepId===t.dataset.popupStepId);if(!(s<0)){this.changeDestinationPending=!0,this.changeDestinationButtonTarget.disabled=!0;try{if((await C.cancel(this.idValue,this.submissionId,this.submissionActionToken)).failed)return;wt.forgetFinished(this.idValue),this.stopResendCooldown(),this.submissionId=null,this.submissionActionToken=null,this.submissionVerificationState=null,this.submissionDeliveryStatus=null,this.submissionDeliveryChannel=null,this.submissionDestination=null,this.submissionCouponPush=!1,this.resetSubmissionRequest(),this.showStep(s),t.focus()}catch(e){}finally{this.changeDestinationPending=!1,this.changeDestinationButtonTarget.disabled=!1}}}startResendCooldown(e){this.stopResendCooldown(),this.resendCooldownEndsAt=Date.now()+1e3*Math.max(e,1),this.updateResendCountdown(),this.resendTimer=window.setInterval(()=>this.updateResendCountdown(),1e3)}stopResendCooldown(){this.resendTimer&&window.clearInterval(this.resendTimer),this.resendTimer=null,this.resendCooldownEndsAt=null}updateResendCountdown(){const e=Math.max(0,Math.ceil((this.resendCooldownEndsAt-Date.now())/1e3));if(0===e)return this.stopResendCooldown(),this.resendButtonTarget.textContent=this.resendLabel,void(this.resendButtonTarget.disabled=!1);const t=`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`,s=this.resendButtonTarget.dataset.countdownLabel||`${this.resendLabel} %{time}`;this.resendButtonTarget.textContent=s.replace("%{time}",t),this.resendButtonTarget.disabled=!0}get resendCooldownActive(){return this.resendCooldownEndsAt>Date.now()}get completionIdentity(){return this.identityInputs.map(e=>({input:e,kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(({value:e})=>e)}get completedIdentity(){if(this.submissionDestination&&this.submissionDeliveryChannel){const e="email"===this.submissionDeliveryChannel?"email":"phone";return{input:this.identityInputs.find(t=>t.dataset.popupFieldKind===e),kind:e,value:this.submissionDestination}}return this.completionIdentity}revealCompletionCopy(e){const t=e&&!0===this.submissionCouponPush;this.hasDeliveryCopyTarget&&this.deliveryCopyTargets.forEach(s=>{s.hidden=!e||t}),this.hasPushDeliveryCopyTarget&&this.pushDeliveryCopyTargets.forEach(e=>{e.hidden=!t}),this.hasNoDeliveryCopyTarget&&this.noDeliveryCopyTargets.forEach(t=>{t.hidden=e})}currentStepValid(){return this.currentStepInputs.every(e=>e.checkValidity())}showErrorMessages(e){e.forEach(e=>{const t=e.closest(".hellotext--popup-field")?.querySelector("[data-error-container]");t&&(t.textContent=e.validity.valid?"":e.validationMessage)})}clearErrorMessages(e=this.inputTargets){e.forEach(e=>{const t=e.closest(".hellotext--popup-field")?.querySelector("[data-error-container]");t&&(t.textContent="")})}clearCustomValidity(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}clearGlobalError(){this.hasGlobalErrorTarget&&(this.globalErrorTarget.textContent="",this.globalErrorTarget.hidden=!0)}showGlobalError(e=null){this.hasGlobalErrorTarget&&(this.globalErrorTarget.textContent=e||this.globalErrorTarget.dataset.submitError||"Unable to submit. Please try again.",this.globalErrorTarget.hidden=!1)}async handleSubmissionError(e){let t;try{t=await e.json()}catch(e){return void this.showGlobalError()}const s=t.errors||[],i=[],n=[];s.forEach(e=>{const t=this.inputForError(e);t?(t.setCustomValidity(e.description||t.validationMessage),n.push(t)):e.description&&i.push(e.description)});const r=this.stepTargets.findIndex(e=>n.some(t=>this.inputsForStep(e).includes(t)));r>=0&&this.showStep(r),n.forEach(e=>e.reportValidity()),this.showErrorMessages(this.inputTargets),i.length?this.showGlobalError(i.join(" ")):s.length||this.showGlobalError()}inputForError(e){const t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}submissionPayload(){const e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{const s={};this.inputsForStep(t).forEach(t=>{const i=this.submissionValue(t),n=t.dataset.popupFieldKey||t.name;s[n]=i,e.metadata.fields[n]=i,"email"===t.dataset.popupFieldKind&&(e.email=i),"phone"===t.dataset.popupFieldKind&&(e.phone=i)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:s})}),this.inputTargets.some(e=>"push"===e.dataset.popupFieldKind&&e.checked)&&(e.metadata.push_subscription=Lt.push?.subscriptionForSubmission()||null,e.metadata.push_permission=this.pushPermissionState||"unavailable"),e}idempotencyKeyFor(e){const t=JSON.stringify(e);return this.submissionPayloadSnapshot!==t&&(this.submissionPayloadSnapshot=t,this.submissionIdempotencyKey=C.idempotencyKey()),this.submissionIdempotencyKey}resetSubmissionRequest(){this.submissionPayloadSnapshot=null,this.submissionIdempotencyKey=null}inputValue(e){return"checkbox"===e.type?e.checked:e.value}inputsForStep(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}get identityInputs(){const e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}get completionTextTemplates(){if(this._completionTextTemplates)return this._completionTextTemplates;const e=document.createTreeWalker(this.completedTarget,NodeFilter.SHOW_TEXT);for(this._completionTextTemplates=[];e.nextNode();)this._completionTextTemplates.push({node:e.currentNode,template:e.currentNode.nodeValue});return this._completionTextTemplates}matchesDevice(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}get currentStep(){return this.stepTargets[this.stepIndex]}get currentStepInputs(){return this.inputsForStep(this.currentStep)}},as=["start","end"],os=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+as[0],t+"-"+as[1]),[]),cs=Math.min,ls=Math.max,hs=Math.round,us=Math.floor,ds=e=>({x:e,y:e}),ps={left:"right",right:"left",bottom:"top",top:"bottom"},ms={start:"end",end:"start"};function gs(e,t,s){return ls(e,cs(t,s))}function fs(e,t){return"function"==typeof e?e(t):e}function ys(e){return e.split("-")[0]}function bs(e){return e.split("-")[1]}function vs(e){return"x"===e?"y":"x"}function ws(e){return"y"===e?"height":"width"}const Ts=new Set(["top","bottom"]);function Ss(e){return Ts.has(ys(e))?"y":"x"}function Cs(e){return vs(Ss(e))}function As(e,t,s){void 0===s&&(s=!1);const i=bs(e),n=Cs(e),r=ws(n);let a="x"===n?i===(s?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[r]>t.floating[r]&&(a=Is(a)),[a,Is(a)]}function Es(e){return e.replace(/start|end/g,e=>ms[e])}const Os=["left","right"],xs=["right","left"],ks=["top","bottom"],Ms=["bottom","top"];function Is(e){return e.replace(/left|right|bottom|top/g,e=>ps[e])}function Ps(e){const{x:t,y:s,width:i,height:n}=e;return{width:i,height:n,top:s,left:t,right:t+i,bottom:s+n,x:t,y:s}}function Ls(e,t,s){let{reference:i,floating:n}=e;const r=Ss(t),a=Cs(t),o=ws(a),c=ys(t),l="y"===r,h=i.x+i.width/2-n.width/2,u=i.y+i.height/2-n.height/2,d=i[o]/2-n[o]/2;let p;switch(c){case"top":p={x:h,y:i.y-n.height};break;case"bottom":p={x:h,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:u};break;case"left":p={x:i.x-n.width,y:u};break;default:p={x:i.x,y:i.y}}switch(bs(t)){case"start":p[a]-=d*(s&&l?-1:1);break;case"end":p[a]+=d*(s&&l?-1:1)}return p}async function _s(e,t){var s;void 0===t&&(t={});const{x:i,y:n,platform:r,rects:a,elements:o,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:h="viewport",elementContext:u="floating",altBoundary:d=!1,padding:p=0}=fs(t,e),m=function(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}(p),g=o[d?"floating"===u?"reference":"floating":u],f=Ps(await r.getClippingRect({element:null==(s=await(null==r.isElement?void 0:r.isElement(g)))||s?g:g.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(o.floating)),boundary:l,rootBoundary:h,strategy:c})),y="floating"===u?{x:i,y:n,width:a.floating.width,height:a.floating.height}:a.reference,b=await(null==r.getOffsetParent?void 0:r.getOffsetParent(o.floating)),v=await(null==r.isElement?void 0:r.isElement(b))&&await(null==r.getScale?void 0:r.getScale(b))||{x:1,y:1},w=Ps(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:y,offsetParent:b,strategy:c}):y);return{top:(f.top-w.top+m.top)/v.y,bottom:(w.bottom-f.bottom+m.bottom)/v.y,left:(f.left-w.left+m.left)/v.x,right:(w.right-f.right+m.right)/v.x}}const Ns=new Set(["left","top"]);function Ds(){return"undefined"!=typeof window}function Rs(e){return Bs(e)?(e.nodeName||"").toLowerCase():"#document"}function Fs(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function $s(e){var t;return null==(t=(Bs(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Bs(e){return!!Ds()&&(e instanceof Node||e instanceof Fs(e).Node)}function Vs(e){return!!Ds()&&(e instanceof Element||e instanceof Fs(e).Element)}function js(e){return!!Ds()&&(e instanceof HTMLElement||e instanceof Fs(e).HTMLElement)}function qs(e){return!(!Ds()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Fs(e).ShadowRoot)}const Us=new Set(["inline","contents"]);function zs(e){const{overflow:t,overflowX:s,overflowY:i,display:n}=si(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+s)&&!Us.has(n)}const Ws=new Set(["table","td","th"]);function Ks(e){return Ws.has(Rs(e))}const Hs=[":popover-open",":modal"];function Gs(e){return Hs.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const Js=["transform","translate","scale","rotate","perspective"],Ys=["transform","translate","scale","rotate","perspective","filter"],Zs=["paint","layout","strict","content"];function Xs(e){const t=Qs(),s=Vs(e)?si(e):e;return Js.some(e=>!!s[e]&&"none"!==s[e])||!!s.containerType&&"normal"!==s.containerType||!t&&!!s.backdropFilter&&"none"!==s.backdropFilter||!t&&!!s.filter&&"none"!==s.filter||Ys.some(e=>(s.willChange||"").includes(e))||Zs.some(e=>(s.contain||"").includes(e))}function Qs(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const ei=new Set(["html","body","#document"]);function ti(e){return ei.has(Rs(e))}function si(e){return Fs(e).getComputedStyle(e)}function ii(e){return Vs(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ni(e){if("html"===Rs(e))return e;const t=e.assignedSlot||e.parentNode||qs(e)&&e.host||$s(e);return qs(t)?t.host:t}function ri(e){const t=ni(e);return ti(t)?e.ownerDocument?e.ownerDocument.body:e.body:js(t)&&zs(t)?t:ri(t)}function ai(e,t,s){var i;void 0===t&&(t=[]),void 0===s&&(s=!0);const n=ri(e),r=n===(null==(i=e.ownerDocument)?void 0:i.body),a=Fs(n);if(r){const e=oi(a);return t.concat(a,a.visualViewport||[],zs(n)?n:[],e&&s?ai(e):[])}return t.concat(n,ai(n,[],s))}function oi(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ci(e){const t=si(e);let s=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const n=js(e),r=n?e.offsetWidth:s,a=n?e.offsetHeight:i,o=hs(s)!==r||hs(i)!==a;return o&&(s=r,i=a),{width:s,height:i,$:o}}function li(e){return Vs(e)?e:e.contextElement}function hi(e){const t=li(e);if(!js(t))return ds(1);const s=t.getBoundingClientRect(),{width:i,height:n,$:r}=ci(t);let a=(r?hs(s.width):s.width)/i,o=(r?hs(s.height):s.height)/n;return a&&Number.isFinite(a)||(a=1),o&&Number.isFinite(o)||(o=1),{x:a,y:o}}const ui=ds(0);function di(e){const t=Fs(e);return Qs()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ui}function pi(e,t,s,i){void 0===t&&(t=!1),void 0===s&&(s=!1);const n=e.getBoundingClientRect(),r=li(e);let a=ds(1);t&&(i?Vs(i)&&(a=hi(i)):a=hi(e));const o=function(e,t,s){return void 0===t&&(t=!1),!(!s||t&&s!==Fs(e))&&t}(r,s,i)?di(r):ds(0);let c=(n.left+o.x)/a.x,l=(n.top+o.y)/a.y,h=n.width/a.x,u=n.height/a.y;if(r){const e=Fs(r),t=i&&Vs(i)?Fs(i):i;let s=e,n=oi(s);for(;n&&i&&t!==s;){const e=hi(n),t=n.getBoundingClientRect(),i=si(n),r=t.left+(n.clientLeft+parseFloat(i.paddingLeft))*e.x,a=t.top+(n.clientTop+parseFloat(i.paddingTop))*e.y;c*=e.x,l*=e.y,h*=e.x,u*=e.y,c+=r,l+=a,s=Fs(n),n=oi(s)}}return Ps({width:h,height:u,x:c,y:l})}function mi(e,t){const s=ii(e).scrollLeft;return t?t.left+s:pi($s(e)).left+s}function gi(e,t,s){void 0===s&&(s=!1);const i=e.getBoundingClientRect();return{x:i.left+t.scrollLeft-(s?0:mi(e,i)),y:i.top+t.scrollTop}}const fi=new Set(["absolute","fixed"]);function yi(e,t,s){let i;if("viewport"===t)i=function(e,t){const s=Fs(e),i=$s(e),n=s.visualViewport;let r=i.clientWidth,a=i.clientHeight,o=0,c=0;if(n){r=n.width,a=n.height;const e=Qs();(!e||e&&"fixed"===t)&&(o=n.offsetLeft,c=n.offsetTop)}return{width:r,height:a,x:o,y:c}}(e,s);else if("document"===t)i=function(e){const t=$s(e),s=ii(e),i=e.ownerDocument.body,n=ls(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),r=ls(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let a=-s.scrollLeft+mi(e);const o=-s.scrollTop;return"rtl"===si(i).direction&&(a+=ls(t.clientWidth,i.clientWidth)-n),{width:n,height:r,x:a,y:o}}($s(e));else if(Vs(t))i=function(e,t){const s=pi(e,!0,"fixed"===t),i=s.top+e.clientTop,n=s.left+e.clientLeft,r=js(e)?hi(e):ds(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:n*r.x,y:i*r.y}}(t,s);else{const s=di(e);i={x:t.x-s.x,y:t.y-s.y,width:t.width,height:t.height}}return Ps(i)}function bi(e,t){const s=ni(e);return!(s===t||!Vs(s)||ti(s))&&("fixed"===si(s).position||bi(s,t))}function vi(e,t,s){const i=js(t),n=$s(t),r="fixed"===s,a=pi(e,!0,r,t);let o={scrollLeft:0,scrollTop:0};const c=ds(0);function l(){c.x=mi(n)}if(i||!i&&!r)if(("body"!==Rs(t)||zs(n))&&(o=ii(t)),i){const e=pi(t,!0,r,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else n&&l();r&&!i&&n&&l();const h=!n||i||r?ds(0):gi(n,o);return{x:a.left+o.scrollLeft-c.x-h.x,y:a.top+o.scrollTop-c.y-h.y,width:a.width,height:a.height}}function wi(e){return"static"===si(e).position}function Ti(e,t){if(!js(e)||"fixed"===si(e).position)return null;if(t)return t(e);let s=e.offsetParent;return $s(e)===s&&(s=s.ownerDocument.body),s}function Si(e,t){const s=Fs(e);if(Gs(e))return s;if(!js(e)){let t=ni(e);for(;t&&!ti(t);){if(Vs(t)&&!wi(t))return t;t=ni(t)}return s}let i=Ti(e,t);for(;i&&Ks(i)&&wi(i);)i=Ti(i,t);return i&&ti(i)&&wi(i)&&!Xs(i)?s:i||function(e){let t=ni(e);for(;js(t)&&!ti(t);){if(Xs(t))return t;if(Gs(t))return null;t=ni(t)}return null}(e)||s}const Ci={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:s,offsetParent:i,strategy:n}=e;const r="fixed"===n,a=$s(i),o=!!t&&Gs(t.floating);if(i===a||o&&r)return s;let c={scrollLeft:0,scrollTop:0},l=ds(1);const h=ds(0),u=js(i);if((u||!u&&!r)&&(("body"!==Rs(i)||zs(a))&&(c=ii(i)),js(i))){const e=pi(i);l=hi(i),h.x=e.x+i.clientLeft,h.y=e.y+i.clientTop}const d=!a||u||r?ds(0):gi(a,c,!0);return{width:s.width*l.x,height:s.height*l.y,x:s.x*l.x-c.scrollLeft*l.x+h.x+d.x,y:s.y*l.y-c.scrollTop*l.y+h.y+d.y}},getDocumentElement:$s,getClippingRect:function(e){let{element:t,boundary:s,rootBoundary:i,strategy:n}=e;const r=[..."clippingAncestors"===s?Gs(t)?[]:function(e,t){const s=t.get(e);if(s)return s;let i=ai(e,[],!1).filter(e=>Vs(e)&&"body"!==Rs(e)),n=null;const r="fixed"===si(e).position;let a=r?ni(e):e;for(;Vs(a)&&!ti(a);){const t=si(a),s=Xs(a);s||"fixed"!==t.position||(n=null),(r?!s&&!n:!s&&"static"===t.position&&n&&fi.has(n.position)||zs(a)&&!s&&bi(e,a))?i=i.filter(e=>e!==a):n=t,a=ni(a)}return t.set(e,i),i}(t,this._c):[].concat(s),i],a=r[0],o=r.reduce((e,s)=>{const i=yi(t,s,n);return e.top=ls(i.top,e.top),e.right=cs(i.right,e.right),e.bottom=cs(i.bottom,e.bottom),e.left=ls(i.left,e.left),e},yi(t,a,n));return{width:o.right-o.left,height:o.bottom-o.top,x:o.left,y:o.top}},getOffsetParent:Si,getElementRects:async function(e){const t=this.getOffsetParent||Si,s=this.getDimensions,i=await s(e.floating);return{reference:vi(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:s}=ci(e);return{width:t,height:s}},getScale:hi,isElement:Vs,isRTL:function(e){return"rtl"===si(e).direction}};function Ai(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const Ei=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var s,i;const{x:n,y:r,placement:a,middlewareData:o}=t,c=await async function(e,t){const{placement:s,platform:i,elements:n}=e,r=await(null==i.isRTL?void 0:i.isRTL(n.floating)),a=ys(s),o=bs(s),c="y"===Ss(s),l=Ns.has(a)?-1:1,h=r&&c?-1:1,u=fs(t,e);let{mainAxis:d,crossAxis:p,alignmentAxis:m}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return o&&"number"==typeof m&&(p="end"===o?-1*m:m),c?{x:p*h,y:d*l}:{x:d*l,y:p*h}}(t,e);return a===(null==(s=o.offset)?void 0:s.placement)&&null!=(i=o.arrow)&&i.alignmentOffset?{}:{x:n+c.x,y:r+c.y,data:{...c,placement:a}}}}},Oi=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:s,y:i,placement:n}=t,{mainAxis:r=!0,crossAxis:a=!1,limiter:o={fn:e=>{let{x:t,y:s}=e;return{x:t,y:s}}},...c}=fs(e,t),l={x:s,y:i},h=await _s(t,c),u=Ss(ys(n)),d=vs(u);let p=l[d],m=l[u];if(r){const e="y"===d?"bottom":"right";p=gs(p+h["y"===d?"top":"left"],p,p-h[e])}if(a){const e="y"===u?"bottom":"right";m=gs(m+h["y"===u?"top":"left"],m,m-h[e])}const g=o.fn({...t,[d]:p,[u]:m});return{...g,data:{x:g.x-s,y:g.y-i,enabled:{[d]:r,[u]:a}}}}}},xi=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var s,i;const{placement:n,middlewareData:r,rects:a,initialPlacement:o,platform:c,elements:l}=t,{mainAxis:h=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...f}=fs(e,t);if(null!=(s=r.arrow)&&s.alignmentOffset)return{};const y=ys(n),b=Ss(o),v=ys(o)===o,w=await(null==c.isRTL?void 0:c.isRTL(l.floating)),T=d||(v||!g?[Is(o)]:function(e){const t=Is(e);return[Es(e),t,Es(t)]}(o)),S="none"!==m;!d&&S&&T.push(...function(e,t,s,i){const n=bs(e);let r=function(e,t,s){switch(e){case"top":case"bottom":return s?t?xs:Os:t?Os:xs;case"left":case"right":return t?ks:Ms;default:return[]}}(ys(e),"start"===s,i);return n&&(r=r.map(e=>e+"-"+n),t&&(r=r.concat(r.map(Es)))),r}(o,g,m,w));const C=[o,...T],A=await _s(t,f),E=[];let O=(null==(i=r.flip)?void 0:i.overflows)||[];if(h&&E.push(A[y]),u){const e=As(n,a,w);E.push(A[e[0]],A[e[1]])}if(O=[...O,{placement:n,overflows:E}],!E.every(e=>e<=0)){var x,k;const e=((null==(x=r.flip)?void 0:x.index)||0)+1,t=C[e];if(t&&("alignment"!==u||b===Ss(t)||O.every(e=>Ss(e.placement)!==b||e.overflows[0]>0)))return{data:{index:e,overflows:O},reset:{placement:t}};let s=null==(k=O.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!s)switch(p){case"bestFit":{var M;const e=null==(M=O.filter(e=>{if(S){const t=Ss(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:M[0];e&&(s=e);break}case"initialPlacement":s=o}if(n!==s)return{reset:{placement:s}}}return{}}}},ki=e=>{Object.assign(e,{show(){this.cancelBehaviourOpen?.(),this.openValue=!0},hide(){this.openValue=!1},toggle(){this.cancelBehaviourOpen?.(),this.openValue=!this.openValue},setupFloatingUI({trigger:e,popover:t,strategy:s}){this.floatingUICleanup=function(e,t,s,i){void 0===i&&(i={});const{ancestorScroll:n=!0,ancestorResize:r=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:o="function"==typeof IntersectionObserver,animationFrame:c=!1}=i,l=li(e),h=n||r?[...l?ai(l):[],...ai(t)]:[];h.forEach(e=>{n&&e.addEventListener("scroll",s,{passive:!0}),r&&e.addEventListener("resize",s)});const u=l&&o?function(e,t){let s,i=null;const n=$s(e);function r(){var e;clearTimeout(s),null==(e=i)||e.disconnect(),i=null}return function a(o,c){void 0===o&&(o=!1),void 0===c&&(c=1),r();const l=e.getBoundingClientRect(),{left:h,top:u,width:d,height:p}=l;if(o||t(),!d||!p)return;const m={rootMargin:-us(u)+"px "+-us(n.clientWidth-(h+d))+"px "+-us(n.clientHeight-(u+p))+"px "+-us(h)+"px",threshold:ls(0,cs(1,c))||1};let g=!0;function f(t){const i=t[0].intersectionRatio;if(i!==c){if(!g)return a();i?a(!1,i):s=setTimeout(()=>{a(!1,1e-7)},1e3)}1!==i||Ai(l,e.getBoundingClientRect())||a(),g=!1}try{i=new IntersectionObserver(f,{...m,root:n.ownerDocument})}catch(e){i=new IntersectionObserver(f,m)}i.observe(e)}(!0),r}(l,s):null;let d,p=-1,m=null;a&&(m=new ResizeObserver(e=>{let[i]=e;i&&i.target===l&&m&&(m.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var e;null==(e=m)||e.observe(t)})),s()}),l&&!c&&m.observe(l),m.observe(t));let g=c?pi(e):null;return c&&function t(){const i=pi(e);g&&!Ai(g,i)&&s(),g=i,d=requestAnimationFrame(t)}(),s(),()=>{var e;h.forEach(e=>{n&&e.removeEventListener("scroll",s),r&&e.removeEventListener("resize",s)}),null==u||u(),null==(e=m)||e.disconnect(),m=null,c&&cancelAnimationFrame(d)}}(e,t,()=>{((e,t,s)=>{const i=new Map,n={platform:Ci,...s},r={...n.platform,_c:i};return(async(e,t,s)=>{const{placement:i="bottom",strategy:n="absolute",middleware:r=[],platform:a}=s,o=r.filter(Boolean),c=await(null==a.isRTL?void 0:a.isRTL(t));let l=await a.getElementRects({reference:e,floating:t,strategy:n}),{x:h,y:u}=Ls(l,i,c),d=i,p={},m=0;for(let s=0;s{const n={left:`${e}px`,top:`${s}px`,position:i};Object.assign(t.style,n)})})},openValueChanged(){this.disabledValue||(this.openValue?(this.preparePopoverOpenAnimation?.(),this.popoverTarget.showPopover(),this.popoverTarget.setAttribute("aria-expanded","true"),this.onPopoverOpened&&this.onPopoverOpened()):(this.popoverTarget.hidePopover(),this.popoverTarget.removeAttribute("aria-expanded"),this.onPopoverClosed&&this.onPopoverClosed()))}})},Mi=class extends i.xI{static targets=["button","popover"];static values={placement:{type:String,default:"bottom-end"},open:{type:Boolean,default:!1},autoPlacement:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1},size:{type:Number,default:24},perLine:{type:Number,default:9}};initialize(){this.onEmojiSelect=this.onEmojiSelect.bind(this),this.pickerLoaded=!1,this.pickerLoadPromise=null,this.connected=!1,super.initialize()}connect(){this.connected=!0,ki(this),this.setupFloatingUI({trigger:this.buttonTarget,popover:this.popoverTarget,strategy:"absolute"}),super.connect()}disconnect(){this.connected=!1,this.pickerLoadPromise=null,this.floatingUICleanup(),super.disconnect()}onEmojiSelect(e){this.dispatch("selected",{detail:e.native}),this.hide()}onClickOutside(e){this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}async onPopoverOpened(){await this.loadPicker()}async loadPicker(){if(this.pickerLoaded)return;this.pickerLoadPromise||=this.loadPickerDependencies();const{Picker:e,i18n:t}=await this.pickerLoadPromise;this.connected&&!this.pickerLoaded&&(this.popoverTarget.appendChild(this.buildPicker(e,t)),this.pickerLoaded=!0)}async loadPickerDependencies(){const[e,t]=await Promise.all([s.e(160).then(s.bind(s,6)),this.loadI18n()]);return{Picker:e.Picker,i18n:t.default||t}}loadI18n(){return"es"===Hellotext.business.locale?s.e(437).then(s.t.bind(s,810,19)):s.e(200).then(s.t.bind(s,329,19))}buildPicker(e,t){return new e({onEmojiSelect:this.onEmojiSelect,theme:"light",dynamicWidth:!0,previewPosition:"none",skinTonePosition:"none",emojiSize:this.sizeValue,perLine:this.perLineValue,i18n:t})}get middlewares(){return[Ei(5),Oi({padding:24}),(e={allowedPlacements:["top","bottom"]},void 0===e&&(e={}),{name:"autoPlacement",options:e,async fn(t){var s,i,n;const{rects:r,middlewareData:a,placement:o,platform:c,elements:l}=t,{crossAxis:h=!1,alignment:u,allowedPlacements:d=os,autoAlignment:p=!0,...m}=fs(e,t),g=void 0!==u||d===os?function(e,t,s){return(e?[...s.filter(t=>bs(t)===e),...s.filter(t=>bs(t)!==e)]:s.filter(e=>ys(e)===e)).filter(s=>!e||bs(s)===e||!!t&&Es(s)!==s)}(u||null,p,d):d,f=await _s(t,m),y=(null==(s=a.autoPlacement)?void 0:s.index)||0,b=g[y];if(null==b)return{};const v=As(b,r,await(null==c.isRTL?void 0:c.isRTL(l.floating)));if(o!==b)return{reset:{placement:g[0]}};const w=[f[ys(b)],f[v[0]],f[v[1]]],T=[...(null==(i=a.autoPlacement)?void 0:i.overflows)||[],{placement:b,overflows:w}],S=g[y+1];if(S)return{data:{index:y+1,overflows:T},reset:{placement:S}};const C=T.map(e=>{const t=bs(e.placement);return[e.placement,t&&h?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),A=(null==(n=C.filter(e=>e[2].slice(0,bs(e[0])?2:3).every(e=>e<=0))[0])?void 0:n[0])||C[0][0];return A!==o?{data:{index:y+1,overflows:T},reset:{placement:A}}:{}}})];var e}};class Ii{static get endpoint(){return f.endpoint("public/webchats/:id/messages")}constructor(e){this.webchatId=e}async index(e){const t=new URL(this.url);return Object.entries(e).forEach(([e,s])=>{t.searchParams.append(e,s)}),await fetch(t,{method:"GET",headers:Lt.headers})}catchUp(e){return this.index({after_id:e,session:Lt.session})}async create(e){this.appendPage(e);const t=await fetch(this.url,{method:"POST",headers:{Authorization:`Bearer ${Lt.business.id}`},body:e});return new v(t.ok,t)}markAsSeen(e=null){const t=e?this.url+`/${e}`:this.url+"/seen";fetch(t,{method:"PATCH",headers:Lt.headers,body:JSON.stringify({session:Lt.session})})}get url(){return Ii.endpoint.replace(":id",this.webchatId)}appendPage(e){const t=Lt.page?.trackingData?.page||{};Object.entries(t).forEach(([t,s])=>{s&&e.append(`message[page][${t}]`,s)})}}const Pi=Ii;class Li{static webSocket;static channels=new Set;static messageHandlers=new Set;static disconnectHandlers=new Set;static subscriptionConfirmHandlers=new Set;static reconnectTimeout=null;static reconnectAttempts=0;static reconnectBaseDelay=500;static reconnectMaxDelay=1e4;static reconnectJitter=.3;static needsResubscribe=!1;constructor(){Li.channels.add(this)}send({command:e,identifier:t,data:s}){const i={command:e,identifier:JSON.stringify(t),data:JSON.stringify(s||{})},n=Li.ensureWebSocket(),r=JSON.stringify(i);n.readyState===WebSocket.OPEN?n.send(r):n.addEventListener("open",()=>{n.send(r)})}onMessage(e){const t=t=>{const s=JSON.parse(t.data),{type:i,message:n}=s;this.ignoredEvents.includes(i)||e(n)};Li.messageHandlers.add(t),Li.ensureWebSocket().addEventListener("message",t)}onDisconnect(e){Li.disconnectHandlers.add(e)}onSubscriptionConfirmed(e){Li.subscriptionConfirmHandlers.add(e)}get webSocket(){return Li.ensureWebSocket()}static ensureWebSocket(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}static openWebSocket(){this.clearReconnectTimeout();const e=new WebSocket(f.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}static installWebSocketHandlers(e){e.addEventListener("open",()=>this.handleOpen(e)),e.addEventListener("close",()=>this.handleDisconnect(e)),e.addEventListener("error",()=>this.handleDisconnect(e)),e.addEventListener("message",e=>this.handleControlMessage(e)),this.messageHandlers.forEach(t=>{e.addEventListener("message",t)})}static handleOpen(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}static handleControlMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}static handleDisconnect(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}static scheduleReconnect(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}static clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}static resubscribeChannels(){this.channels.forEach(e=>{const t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}static closedWebSocket(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}static get reconnectDelay(){const e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}get ignoredEvents(){return["ping","confirm_subscription","welcome"]}}const _i=Li,Ni=class extends _i{constructor(e,t,s){super(),this.id=e,this.session=t,this.conversation=s,this.subscribed=!1,this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks=new Set,this.onSubscriptionConfirmed(e=>this.handleSubscriptionConfirmed(e)),this.subscribe()}subscribe(){this.subscribed=!0;const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}unsubscribe(){this.subscribed=!1;const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}resubscribe(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}onReconnect(e){this.reconnectCallbacks.add(e)}handleSubscriptionConfirmed(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}matchesIdentifier(e){let t;try{t="string"==typeof e?JSON.parse(e):e}catch{return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}startTypingIndicator(){const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}stopTypingIndicator(){const e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}onMessage(e){super.onMessage(t=>{"message"===t.type&&e(t)})}onReaction(e){super.onMessage(t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)})}onTypingStart(e){super.onMessage(t=>{"started_typing"===t.type&&e(t)})}updateSubscriptionWith(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}},Di=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(!this.shouldAutoOpenFromBehaviour())return;const e=1e3*Number(this.behaviourValue.delay_seconds||0);this.behaviourOpenTimeout=window.setTimeout(()=>{this.behaviourOpenTimeout=null,this.openValue||(this.openValue=!0,this.markBehaviourAutoOpened())},e)},cancelBehaviourOpen(){window.clearTimeout(this.behaviourOpenTimeout),this.behaviourOpenTimeout=null},shouldAutoOpenFromBehaviour(){const e=this.behaviourValue;return!(!e||"on_load"!==e.trigger||e.first_visit_only&&localStorage.getItem(this.firstVisitKey())||e.once_per_session&&sessionStorage.getItem(this.sessionKey()))},markBehaviourAutoOpened(){this.behaviourValue.first_visit_only&&localStorage.setItem(this.firstVisitKey(),"1"),this.behaviourValue.once_per_session&&sessionStorage.setItem(this.sessionKey(),"1")},firstVisitKey(){return`hellotext--webchat--${this.idValue}--auto-opened`},sessionKey(){return`hellotext--webchat--${this.idValue}--auto-opened-session`}})},Ri=e=>{Object.assign(e,{setupOpeningSequence(){this.openingSequenceStarted=!1,this.openingSequenceCancelled=!1,this.openingSequenceTimeout=null,this.openingSequenceMessages=[],this.revealedOpeningSequenceMessageIds=[]},teardownOpeningSequence(){this.cancelOpeningSequence()},startOpeningSequence(){this.openingSequenceMessages=Array.from(this.openingSequenceMessageTargets||[]),this.openingSequenceCanStart()&&(this.openingSequenceStarted=!0,this.openingSequenceCancelled=!1,this.revealedOpeningSequenceMessageIds=[],this.playOpeningSequenceMessageAt(0))},openingSequenceCanStart(){return!this.conversationIdValue&&this.hasOpeningSequenceTarget&&this.openingSequenceMessages.length>0&&!this.openingSequenceStarted},playOpeningSequenceMessageAt(e){const t=this.openingSequenceMessages[e];if(!t)return;const s=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},s)},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){const t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){const t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},scrollOpeningSequenceToBottom(){this.messagesContainerTarget.scroll&&this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"smooth"})},cancelOpeningSequence(){this.openingSequenceCancelled=!0,null!==this.openingSequenceTimeout&&void 0!==this.openingSequenceTimeout&&(window.clearTimeout(this.openingSequenceTimeout),this.openingSequenceTimeout=null)},appendOpeningSequenceMessageIds(e){this.cancelOpeningSequence(),(this.revealedOpeningSequenceMessageIds||[]).forEach(t=>{e.append("message[opening_sequence_message_ids][]",t)})},clearRevealedOpeningSequenceMessageIds(){this.revealedOpeningSequenceMessageIds=[]}})},Fi=e=>{Object.assign(e,{setupTeaser(){this.teaserCycleTimeout=null,this.teaserMessages=[],this.boundOnTeaserClick=this.boundOnTeaserClick||this.onTeaserClick.bind(this),this.hasTeaserTarget&&(this.teaserTarget.addEventListener("click",this.boundOnTeaserClick),this.startTeaserPresentation())},teardownTeaser(){this.stopTeaserCycle(),this.hasTeaserTarget&&this.boundOnTeaserClick&&this.teaserTarget.removeEventListener("click",this.boundOnTeaserClick)},collectTeaserMessages(){return this.hasTeaserTarget?Array.from(this.teaserTarget.querySelectorAll("[data-teaser-message]")):[]},startTeaserPresentation(){this.stopTeaserCycle(),this.teaserMessages=this.collectTeaserMessages(),this.hasTeaserTarget&&(0!==this.teaserMessages.length?this.openValue||this.conversationIdValue||this.hasRenderedConversationMessages()?this.dismissTeaserForSession():this.teaserSeenForSession()?this.hideTeaser():this.teaserMessageDelay(this.teaserMessages[0])>0?this.scheduleTeaserMessage(0):(this.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.scheduleTeaserMessage(1)):this.hideTeaser())},scheduleTeaserMessage(e){const t=this.teaserMessages[e];if(!t)return;const s=this.teaserPresentationDelay(t);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(e),this.scheduleTeaserMessage(e+1)},s)},showTeaserMessage(e){this.teaserMessages.forEach((t,s)=>{t.classList.toggle("hidden",s!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){const t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){let e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){const e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?`:${e}`:"";return`hellotext:webchat:${this.idValue||this.element.id}:teaser-seen${t}`},teaserSeenForSession(){try{return"true"===window.sessionStorage.getItem(this.teaserSeenKey())}catch(e){return!1}},markTeaserSeenForSession(){try{window.sessionStorage.setItem(this.teaserSeenKey(),"true")}catch(e){}},dismissTeaserForSession(){this.markTeaserSeenForSession(),this.hideTeaser()},hideTeaser(){this.stopTeaserCycle(),this.hasTeaserTarget&&this.teaserTarget.classList.add("invisible")},onTeaserClick(e){e.target.closest("a")||(this.dismissTeaserForSession(),this.show())}})},$i={hour:"numeric",minute:"2-digit"},Bi=/Android|iPhone|iPad|iPod/i,Vi={capture:!0,passive:!0},ji=class extends i.xI{static messageTimestampFormatters={};static values={id:String,conversationId:String,media:Object,fileSizeErrorMessage:String,placement:{type:String,default:"bottom-end"},open:{type:Boolean,default:!1},autoPlacement:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1},nextPage:{type:Number,default:void 0},fullScreenThreshold:{type:Number,default:1024},typingIndicatorKeepAlive:{type:Number,default:3e4},offset:{type:Number,default:24},padding:{type:Number,default:24},optimisticTypingIndicatorWait:{type:Number,default:1e3},teaser:Object,messageTeaser:String,behaviour:Object};static classes=["fadeOut"];static targets=["trigger","popover","input","attachmentInput","attachmentButton","errorMessageContainer","attachmentTemplate","attachmentContainer","attachment","messageTemplate","messagesContainer","title","attachmentImage","footer","toolbar","message","unreadCounter","typingIndicator","typingIndicatorTemplate","teaser","teaserMessage","inboundMessageTeaser","inboundMessageTeaserBody","openingSequence","openingSequenceMessage"];initialize(){this.messagesAPI=new Pi(this.idValue),this.webChatChannel=new Ni(this.idValue,Lt.session,this.conversationIdValue),this.files=[],this.messageIds=new Set,this.catchUpAfterMessageId=null,this.fetchingCatchUpMessages=!1,this.onMessageReceived=this.onMessageReceived.bind(this),this.onMessageReaction=this.onMessageReaction.bind(this),this.onTypingStart=this.onTypingStart.bind(this),this.captureCatchUpCursor=this.captureCatchUpCursor.bind(this),this.catchUpMessages=this.catchUpMessages.bind(this),this.onScroll=this.onScroll.bind(this),this.onOutboundMessageSent=this.onOutboundMessageSent.bind(this),this.closePopoverOnEscape=this.closePopoverOnEscape.bind(this),this.broadcastChannel=new BroadcastChannel(`hellotext--webchat--${this.idValue}`),this.webChatChannel.onDisconnect(this.captureCatchUpCursor),this.webChatChannel.onReconnect(this.catchUpMessages),super.initialize()}connect(){Di(this),ki(this),Ri(this),Fi(this),this.setupFloatingUI({trigger:this.triggerTarget,popover:this.popoverTarget}),this.hasTeaserTarget&&this.setupFloatingUI({trigger:this.triggerTarget,popover:this.teaserTarget,strategy:"absolute"}),this.setupTeaser(),this.setupOpeningSequence(),this.localizeMessageTimestamps(),this.webChatChannel.onMessage(this.onMessageReceived),this.webChatChannel.onTypingStart(this.onTypingStart),this.webChatChannel.onReaction(this.onMessageReaction),this.setupMessagesContainerScrollIsolation(),this.messagesContainerTarget.addEventListener("scroll",this.onScroll),this.messagesContainerTarget.addEventListener("wheel",this.stopHostScrollPropagation,Vi),this.messagesContainerTarget.addEventListener("touchmove",this.stopHostScrollPropagation,Vi),this.shouldOpenOnMount&&(this.openValue=!0),Lt.eventEmitter.dispatch("webchat:mounted"),this.broadcastChannel.addEventListener("message",this.onOutboundMessageSent),window.addEventListener("keydown",this.closePopoverOnEscape,!0),this.scheduleBehaviourOpen(),super.connect()}disconnect(){this.cancelBehaviourOpen(),this.clearPopoverOpenAnimation(),this.teardownTeaser(),this.teardownOpeningSequence(),this.broadcastChannel.removeEventListener("message",this.onOutboundMessageSent),this.messagesContainerTarget.removeEventListener("scroll",this.onScroll),this.messagesContainerTarget.removeEventListener("wheel",this.stopHostScrollPropagation,Vi),this.messagesContainerTarget.removeEventListener("touchmove",this.stopHostScrollPropagation,Vi),window.removeEventListener("keydown",this.closePopoverOnEscape,!0),this.clearTypingIndicator(),this.broadcastChannel.close(),this.floatingUICleanup(),super.disconnect()}setupMessagesContainerScrollIsolation(){this.messagesContainerTarget.style.overscrollBehavior="contain",this.messagesContainerTarget.style.webkitOverflowScrolling="touch",this.messagesContainerTarget.style.touchAction="pan-y",this.messagesContainerTarget.setAttribute("data-lenis-prevent",""),this.messagesContainerTarget.setAttribute("data-lenis-prevent-wheel",""),this.messagesContainerTarget.setAttribute("data-lenis-prevent-touch","")}stopHostScrollPropagation(e){e.stopPropagation()}onTypingStart(){if(this.typingIndicatorVisible)return this.resetTypingIndicatorTimer();this.showTypingIndicator()}showOptimisticTypingIndicator(){this.typingIndicatorVisible||this.showTypingIndicator()}showTypingIndicator(){this.clearTypingIndicator(),this.typingIndicatorVisible=!0;const e=this.typingIndicatorTemplateTarget.cloneNode(!0);e.setAttribute("data-hellotext--webchat-target","typingIndicator"),e.style.display="flex",this.messagesContainerTarget.appendChild(e),requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});const t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}resetTypingIndicatorTimer(){if(!this.typingIndicatorVisible)return;clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);const e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}clearTypingIndicator(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}onMessageInputChange(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}onOutboundMessageSent(e){const{data:t}=e,s={"message:sent":e=>{const t=(new DOMParser).parseFromString(e.element,"text/html").body.firstElementChild;this.localizeMessageTimestamps(t),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(t,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(t),t.scrollIntoView({behavior:"instant"})},"message:failed":e=>{const t=this.messagesContainerTarget.querySelector(`#${e.id}`);this.markMessageFailed(t,e.reason)}};s[t.type]?s[t.type](t):console.log(`Unhandled message event: ${t.type}`)}async onScroll(){if(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)return;this.fetchingNextPage=!0;const e=await this.messagesAPI.index({page:this.nextPageValue,session:Lt.session}),{next:t,messages:s}=await e.json();this.nextPageValue=t,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,s.forEach(e=>{const{body:t,attachments:s}=e,i=e.created_at||e.createdAt,n=this.messageTemplateTarget.cloneNode(!0);n.classList.add("hellotext--webchat-message"),n.setAttribute("data-hellotext--webchat-target","message"),n.setAttribute("data-id",e.id),i&&n.setAttribute("data-created-at",i),n.style.removeProperty("display"),gt(n.querySelector("[data-body]"),t),"received"===e.state?n.classList.add("received"):n.classList.remove("received"),s&&s.forEach(e=>{const t=this.attachmentImageTarget.cloneNode(!0);t.removeAttribute("data-hellotext--webchat-target"),t.src=e,t.style.display="block",this.messageAttachmentsContainer(n)?.appendChild(t)}),n.setAttribute("data-body",t),this.localizeMessageTimestamp(n.querySelector("[data-message-timestamp]"),i),this.messagesContainerTarget.prepend(n)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}onClickOutside(e){d.mode===u.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}closePopover(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}preparePopoverOpenAnimation(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.popoverTarget.classList.add("hellotext--webchat-popover-opening"),this.popoverOpenAnimationTimeout=setTimeout(()=>{this.popoverTarget.classList.remove("hellotext--webchat-popover-opening"),this.popoverOpenAnimationTimeout=null},120)}clearPopoverOpenAnimation(){this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),this.popoverTarget?.classList.remove("hellotext--webchat-popover-opening")}onPopoverOpened(){this.popoverTarget.classList.remove(...this.fadeOutClasses),this.dismissTeaserForSession?.(),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Lt.eventEmitter.dispatch("webchat:opened"),localStorage.setItem(`hellotext--webchat--${this.idValue}`,"opened"),this.trackOpen(),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}onPopoverClosed(){this.clearPopoverOpenAnimation(),Lt.eventEmitter.dispatch("webchat:closed"),localStorage.setItem(`hellotext--webchat--${this.idValue}`,"closed")}async trackOpen(){const e=`hellotext--webchat--${this.idValue}--tracked-open`,t=`${Lt.session}:${this.localDate}`;if(Lt.readStorage("localStorage",e)!==t)try{const s=await Lt.track("webchat.opened",{webchat_id:this.idValue,tracked_at:(new Date).toISOString()});s?.succeeded&&Lt.writeStorage("localStorage",e,t)}catch(e){}}onMessageReaction(e){const{message:t,reaction:s,type:i}=e,n=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===i)return n.querySelector(`[data-id="${s.id}"]`).remove();if(n.querySelector(`[data-id="${s.id}"]`))n.querySelector(`[data-id="${s.id}"]`).innerText=s.emoji;else{const e=document.createElement("span");e.innerText=s.emoji,e.setAttribute("data-id",s.id),n.appendChild(e)}}onMessageReceived(e,t={}){const{id:s,body:i,attachments:n,teaser:r}=e,a=e.created_at||e.createdAt;if(!this.claimMessageId(s))return;if(this.hideTeaser?.(),e.carousel)return this.insertCarouselMessage(e,t);const o=this.messageTemplateTarget.cloneNode(!0);o.classList.add("hellotext--webchat-message"),o.style.display="flex",gt(o.querySelector("[data-body]"),i),o.setAttribute("data-id",s),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,a),this.localizeMessageTimestamp(o.querySelector("[data-message-timestamp]"),a),n&&n.forEach(e=>{const t=this.attachmentImageTarget.cloneNode(!0);t.src=e,t.style.display="block",this.messageAttachmentsContainer(o)?.appendChild(t)}),this.clearTypingIndicator(),this.insertMessageElement(o),Lt.eventEmitter.dispatch("webchat:message:received",{...e,body:o.querySelector("[data-body]").innerText}),!1!==t.scroll&&o.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(r),this.openValue?this.messagesAPI.markAsSeen(s):this.incrementUnreadCounter()}claimMessageId(e){const t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}captureCatchUpCursor(){this.catchUpAfterMessageId=this.lastRenderedMessageId}async catchUpMessages(){const e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{const t=await this.messagesAPI.catchUp(e),{messages:s=[]}=await t.json();s.forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}get lastRenderedMessageId(){const e=this.persistedMessageElements;return e[e.length-1]?.dataset.id||null}get persistedMessageElements(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}setMessageCreatedAt(e,t){t&&e.setAttribute("data-created-at",t)}insertMessageElement(e){const t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}nextMessageElementFor(e){const t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(s=>{if(s===e)return!1;const i=Date.parse(s.dataset.createdAt);return!Number.isNaN(i)&&i>t})}updateMessageTeaser(e){this.messageTeaserValue=e,this.messageTeaserValue&&this.hasTeaserTarget&&this.hasInboundMessageTeaserTarget&&this.hasInboundMessageTeaserBodyTarget&&(this.teaserMessageTargets.forEach(e=>e.classList.add("hidden")),this.inboundMessageTeaserBodyTarget.textContent=this.messageTeaserValue,this.inboundMessageTeaserTarget.classList.remove("hidden"),this.teaserTarget.classList.toggle("invisible",this.openValue))}insertCarouselMessage(e,t={}){const s=e.html,i=e.created_at||e.createdAt,n=function(e){return mt(e,dt)}(s).firstElementChild;n.classList.add("hellotext--webchat-message"),n.setAttribute("data-id",e.id),n.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(n,i),this.localizeMessageTimestamps(n),this.clearTypingIndicator(),this.insertMessageElement(n),!1!==t.scroll&&n.scrollIntoView({behavior:"smooth"}),Lt.eventEmitter.dispatch("webchat:message:received",{...e,body:n.querySelector("[data-body]")?.innerText||""}),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}resizeInput(){this.inputTarget.style.height="auto";const e=this.inputTarget.scrollHeight;this.inputTarget.style.height=`${Math.min(e,96)}px`}async sendQuickReplyMessage({detail:{id:e,product:t,buttonId:s,body:i,cardElement:n}}){this.dismissTeaserForSession?.();const r=new FormData;r.append("message[body]",i),e&&r.append("message[replied_to]",e),t&&r.append("message[product]",t),s&&r.append("message[button]",s),r.append("session",Lt.session),r.append("locale",o.toString()),this.appendOpeningSequenceMessageIds(r);const a=this.buildMessageElement(),c=n?.querySelector("img")?.cloneNode(!0);a.querySelector("[data-body]").innerText=i,c&&(c.removeAttribute("width"),c.removeAttribute("height"),this.messageAttachmentsContainer(a)?.appendChild(c)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(a,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(a),a.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:a.outerHTML});const l=await this.messagesAPI.create(r);if(l.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(l,a);const h=await l.json();this.dispatch("set:id",{target:a,detail:h.id}),this.localizeMessageTimestamp(a.querySelector("[data-message-timestamp]"),h.created_at||h.createdAt),this.clearRevealedOpeningSequenceMessageIds();const u={id:h.id,body:i,attachments:c?[c.src]:[],replied_to:e,product:t,button:s,type:"quick_reply"};Lt.eventEmitter.dispatch("webchat:message:sent",u)}async sendTeaserQuickReply(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,s=(t.dataset.value||"").trim(),i=[t.dataset.text,t.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),n=s||i;if(!n)return;this.dismissTeaserForSession?.(),this.show();const r=(t.dataset.type||"").trim()||"quick_reply",a=new FormData;a.append("message[body]",n),a.append("session",Lt.session),a.append("locale",o.toString()),this.appendOpeningSequenceMessageIds(a);const c=this.buildMessageElement();c.querySelector("[data-body]").innerText=n,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(c,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(c),c.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:c.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));const l=await this.messagesAPI.create(a);if(l.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(l,c);const h=await l.json();c.setAttribute("data-id",h.id),this.localizeMessageTimestamp(c.querySelector("[data-message-timestamp]"),h.created_at||h.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Lt.eventEmitter.dispatch("webchat:message:sent",{id:h.id,body:n,attachments:[],type:"quick_reply",teaser:{text:i||n,value:s||n,type:r}}),h.conversation&&h.conversation!==this.conversationIdValue&&(this.conversationIdValue=h.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}async sendMessage(e){const t={body:this.inputTarget.value,attachments:this.files};if(0===this.inputTarget.value.trim().length&&0===this.files.length)return void(e&&e.target&&e.preventDefault());this.dismissTeaserForSession?.();const s=new FormData;this.inputTarget.value.trim().length>0?s.append("message[body]",this.inputTarget.value):delete t.body,this.files.forEach(e=>{s.append("message[attachments][]",e)}),s.append("session",Lt.session),s.append("locale",o.toString()),this.appendOpeningSequenceMessageIds(s);const i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();const n=this.attachmentContainerTarget.querySelectorAll("img");n.length>0&&n.forEach(e=>{this.messageAttachmentsContainer(i)?.appendChild(e.cloneNode(!0))}),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(i,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(i),i.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:i.outerHTML}),this.inputTarget.value="",this.resizeInput(),this.files=[],this.attachmentInputTarget.value="",this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none",this.errorMessageContainerTarget.style.display="none",this.focusComposeInput(),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));const r=await this.messagesAPI.create(s);if(r.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(r,i);const a=await r.json();i.setAttribute("data-id",a.id),t.id=a.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),a.created_at||a.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Lt.eventEmitter.dispatch("webchat:message:sent",t),a.conversation!==this.conversationIdValue&&(this.conversationIdValue=a.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}buildMessageElement(){const e=this.messageTemplateTarget.cloneNode(!0);return e.id=`hellotext--webchat--${this.idValue}--message--${Date.now()}`,e.classList.add("received"),e.style.removeProperty("display"),e.setAttribute("data-controller","hellotext--message"),e.setAttribute("data-hellotext--webchat-target","message"),this.localizeMessageTimestamp(e.querySelector("[data-message-timestamp]"),new Date),e}focusCompose(e){const{target:t}=e,s=["button","a","input","textarea","select","label",'[role="button"]',"em-emoji-picker",'[data-hellotext--webchat--emoji-target~="popover"]','[data-controller~="hellotext--webchat--emoji"]'].join(", ");this.hasInputTarget&&!t.closest(s)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}closePopoverFromHeader(e){const{target:t}=e;t.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}closePopoverOnEscape(e){"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),this.triggerTarget?.focus?.())}async markMessageFailedFromResponse(e,t){const s=await this.messageFailureReason(e);this.markMessageFailed(t,s),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:s})}markMessageFailed(e,t){if(!e)return;if(e.classList.add("failed"),!t)return;const s=e.querySelector("[data-message-timestamp]");s&&(s.textContent=t)}localizeMessageTimestamps(e=this.element){e&&(e.matches?.("time[datetime][data-message-timestamp]")?[e]:Array.from(e.querySelectorAll?.("time[datetime][data-message-timestamp]")||[])).forEach(e=>this.localizeMessageTimestamp(e))}localizeMessageTimestamp(e,t=e?.getAttribute("datetime")){if(!e||!t)return;const s=t instanceof Date?t:new Date(t);Number.isNaN(s.getTime())||(e.setAttribute("datetime",s.toISOString()),e.textContent=this.formatMessageTimestamp(s))}formatMessageTimestamp(e){return this.constructor.messageTimestampFormatterFor(o.toString()).format(e)}static messageTimestampFormatterFor(e){const t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}static buildMessageTimestampFormatter(e){try{return new Intl.DateTimeFormat(e||void 0,$i)}catch(e){return new Intl.DateTimeFormat(void 0,$i)}}async messageFailureReason(e){const t=e?.data||e?.response,s=t?.statusText||"Message failed";try{const e=t?.clone?t.clone():t,s=await(e?.json?.()),i=this.messageFailureReasonFromPayload(s);if(i)return i}catch(e){}try{const e=t?.clone?t.clone():t,i=await(e?.text?.());return this.messageFailureReasonFromText(i)||s}catch(e){return s}}messageFailureReasonFromText(e){if("string"!=typeof e)return null;const t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}messageFailureReasonFromPayload(e){return e?[e.error?.message,e.message,e.errors?.message,e.errors?.[0]?.message,e.errors?.[0]?.description].find(e=>"string"==typeof e&&e.trim().length>0):null}messageAttachmentsContainer(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}incrementUnreadCounter(){this.unreadCounterTarget.style.display="flex";const e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}openAttachment(){this.attachmentInputTarget.click()}onFileInputChange(){this.errorMessageContainerTarget.style.display="none";const e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";const t=e.find(e=>{const t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}createAttachmentElement(e){const t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){const s=this.attachmentImageTarget.cloneNode(!0);s.src=URL.createObjectURL(e),s.style.display="block",t.appendChild(s),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{const s=t.querySelector("main");s.style.height="5rem",s.style.borderRadius="0.375rem",s.style.backgroundColor="#e5e7eb",s.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}removeAttachment({currentTarget:e}){const t=e.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}attachmentTargetDisconnected(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}attachmentElement(){const e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}onEmojiSelect({detail:e}){const t=this.inputTarget.value,s=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=t.slice(0,s)+e+t.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=s+e.length,this.focusComposeInput()}focusComposeInput({moveCursorToEnd:e=!1}={}){if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),e&&"number"==typeof this.inputTarget.selectionStart){const e=this.inputTarget.value.length;this.inputTarget.setSelectionRange(e,e)}return!0}byteToMegabyte(e){return Math.ceil(e/1024/1024)}get middlewares(){return[Ei(this.offsetValue),Oi({padding:this.paddingValue}),xi()]}get localDate(){const e=new Date;return[e.getFullYear(),e.getMonth()+1,e.getDate()].map(e=>String(e).padStart(2,"0")).join("-")}get shouldOpenOnMount(){return"opened"===localStorage.getItem(`hellotext--webchat--${this.idValue}`)&&!this.onMobile}get shouldAutofocusCompose(){return!this.usesVirtualKeyboard}get usesVirtualKeyboard(){if("undefined"==typeof navigator)return!1;const e=navigator.userAgent||"",t="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,s=Bi.test(e),i=!0===navigator.userAgentData?.mobile;return s||t||i||this.hasTouchOnlyPointer}get hasTouchOnlyPointer(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}get onMobile(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(`(max-width: ${this.fullScreenThresholdValue}px)`).matches}},qi=i.lg.start();qi.register("hellotext--alert",Nt),qi.register("hellotext--form",Dt),qi.register("hellotext--popup",rs),qi.register("hellotext--webchat",ji),qi.register("hellotext--webchat--emoji",Mi),qi.register("hellotext--message",Rt),window.Hellotext=Lt;const Ui=Lt}};const t={};function s(i){const n=t[i];if(void 0!==n)return n.exports;const r=t[i]={exports:{}};return e[i](r,r.exports,s),r.exports}s.m=e,(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;s.t=function(i,n){if(1&n&&(i=this(i)),8&n)return i;if("object"==typeof i&&i){if(4&n&&i.__esModule)return i;if(16&n&&"function"==typeof i.then)return i}const r=Object.create(null);s.r(r);const a={};t=t||[null,e({}),e([]),e(e)];for(var o=2&n&&i;("object"==typeof o||"function"==typeof o)&&!~t.indexOf(o);o=e(o))Object.getOwnPropertyNames(o).forEach(e=>a[e]=()=>i[e]);return a.default=()=>i,s.d(r,a),r}})(),s.d=(e,t)=>{if(Array.isArray(t))for(var i=0;iPromise.all(Object.keys(s.f).reduce((t,i)=>(s.f[i](e,t),t),[])),s.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";s.l=(i,n,r,a)=>{if(e[i])return void e[i].push(n);let o,c;if(void 0!==r){const e=document.getElementsByTagName("script");for(var l=0;l{o.onerror=o.onload=null,clearTimeout(u);const n=e[i];if(delete e[i],o.parentNode?.removeChild(o),n?.forEach(e=>e(s)),t)return t(s)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=h.bind(null,o.onerror),o.onload=h.bind(null,o.onload),c&&document.head.appendChild(o)}})(),s.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{let e;s.g.importScripts&&(e=s.g.location+"");const t=s.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const s=t.getElementsByTagName("script");if(s.length){let t=s.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=s[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),(()=>{const e={792:0};s.f.j=(t,i)=>{let n=s.o(e,t)?e[t]:void 0;if(0!==n)if(n)i.push(n[2]);else{const r=new Promise((s,i)=>n=e[t]=[s,i]);i.push(n[2]=r);const a=s.p+s.u(t),o=new Error,c=i=>{if(s.o(e,t)&&(n=e[t],0!==n&&(e[t]=void 0),n)){const e=i&&("load"===i.type?"missing":i.type),s=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+e+": "+s+")",o.name="ChunkLoadError",o.type=e,o.request=s,n[1](o)}};s.l(a,c,"chunk-"+t,t)}};const t=(t,i)=>{let[n,r,a]=i;var o,c,l=0;if(n.some(t=>0!==e[t])){for(o in r)s.o(r,o)&&(s.m[o]=r[o]);a&&a(s)}for(t&&t(i);lee,Emoji:()=>ke,FrequentlyUsed:()=>Y,I18n:()=>Q,Picker:()=>ot,SearchIndex:()=>de,Store:()=>$,getEmojiDataFromNative:()=>pe,init:()=>se});var r,s,a,l,c,d,h={},u=[],p=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function f(e,t){for(var n in t)e[n]=t[n];return e}function _(e){var t=e.parentNode;t&&t.removeChild(e)}function g(e,t,n){var o,i,s,a={};for(s in t)"key"==s?o=t[s]:"ref"==s?i=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?r.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return m(e,a,o,i,null)}function m(e,t,n,o,i){var r={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:i??++a};return null==i&&null!=s.vnode&&s.vnode(r),r}function v(){return{current:null}}function b(e){return e.children}function k(e,t){this.props=e,this.context=t}function w(e,t){if(null==t)return e.__?w(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t0?m(_.type,_.props,_.key,null,_.__v):_)){if(_.__=n,_.__b=n.__b+1,null===(f=y[d])||f&&_.key==f.key&&_.type===f.type)y[d]=void 0;else for(p=0;p{let e=null;try{navigator.userAgent.includes("jsdom")||(e=document.createElement("canvas").getContext("2d",{willReadFrequently:!0}))}catch{}if(!e)return()=>!1;const t=20,n=Math.floor(12.5);return e.font=n+"px Arial, Sans-Serif",e.textBaseline="top",e.canvas.width=40,e.canvas.height=25,n=>{e.clearRect(0,0,40,25),e.fillStyle="#FF0000",e.fillText(n,0,22),e.fillStyle="#0000FF",e.fillText(n,t,22);const o=e.getImageData(0,0,t,25).data,i=o.length;let r=0;for(;r=i)return!1;const s=t+r/4%t,a=Math.floor(r/4/t),l=e.getImageData(s,a,1,1).data;return o[r]===l[0]&&o[r+2]===l[2]&&!(e.measureText(n).width>=t)}})();var W=function(){for(const{v:e,emoji:t}of U)if(N(t))return e},K=function(){return!N("🇨🇦")};const G=["+1","grinning","kissing_heart","heart_eyes","laughing","stuck_out_tongue_winking_eye","sweat_smile","joy","scream","disappointed","unamused","weary","sob","sunglasses","heart"];let X=null;var J,Y={add:function(e){X||(X=$.get("frequently")||{});const t=e.id||e;t&&(X[t]||(X[t]=0),X[t]+=1,$.set("last",t),$.set("frequently",X))},get:function({maxFrequentRows:e,perLine:t}){if(!e)return[];X||(X=$.get("frequently"));let n=[];if(!X){X={};for(let e in G.slice(0,t)){const o=G[e];X[o]=t-e,n.push(o)}return n}const o=e*t,i=$.get("last");for(let e in X)n.push(e);if(n.sort((e,t)=>{const n=X[t],o=X[e];return n==o?e.localeCompare(t):n-o}),n.length>o){const e=n.slice(o);n=n.slice(0,o);for(let t of e)t!=i&&delete X[t];i&&-1==n.indexOf(i)&&(delete X[n[n.length-1]],n.splice(-1,1,i)),$.set("frequently",X)}return n},DEFAULTS:G};J=JSON.parse('{"search":"Search","search_no_results_1":"Oh no!","search_no_results_2":"That emoji couldn’t be found","pick":"Pick an emoji…","add_custom":"Add custom emoji","categories":{"activity":"Activity","custom":"Custom","flags":"Flags","foods":"Food & Drink","frequent":"Frequently used","nature":"Animals & Nature","objects":"Objects","people":"Smileys & People","places":"Travel & Places","search":"Search Results","symbols":"Symbols"},"skins":{"1":"Default","2":"Light","3":"Medium-Light","4":"Medium","5":"Medium-Dark","6":"Dark","choose":"Choose default skin tone"}}');var Z={autoFocus:{value:!1},dynamicWidth:{value:!1},emojiButtonColors:{value:null},emojiButtonRadius:{value:"100%"},emojiButtonSize:{value:36},emojiSize:{value:24},emojiVersion:{value:15,choices:[1,2,3,4,5,11,12,12.1,13,13.1,14,15]},exceptEmojis:{value:[]},icons:{value:"auto",choices:["auto","outline","solid"]},locale:{value:"en",choices:["en","ar","be","cs","de","es","fa","fi","fr","hi","it","ja","ko","nl","pl","pt","ru","sa","tr","uk","vi","zh"]},maxFrequentRows:{value:4},navPosition:{value:"top",choices:["top","bottom","none"]},noCountryFlags:{value:!1},noResultsEmoji:{value:null},perLine:{value:9},previewEmoji:{value:null},previewPosition:{value:"bottom",choices:["top","bottom","none"]},searchPosition:{value:"sticky",choices:["sticky","static","none"]},set:{value:"native",choices:["native","apple","facebook","google","twitter"]},skin:{value:1,choices:[1,2,3,4,5,6]},skinTonePosition:{value:"preview",choices:["preview","search","none"]},theme:{value:"auto",choices:["auto","light","dark"]},categories:null,categoryIcons:null,custom:null,data:null,i18n:null,getImageURL:null,getSpritesheetURL:null,onAddCustomEmoji:null,onClickOutside:null,onEmojiSelect:null,stickySearch:{deprecated:!0,value:!0}};let Q=null,ee=null;const te={};async function ne(e){if(te[e])return te[e];const t=await fetch(e),n=await t.json();return te[e]=n,n}let oe=null,ie=null,re=!1;function se(e,{caller:t}={}){return oe||(oe=new Promise(e=>{ie=e})),e?async function(e){re=!0;let{emojiVersion:t,set:n,locale:i}=e;if(t||(t=Z.emojiVersion.value),n||(n=Z.set.value),i||(i=Z.locale.value),ee)ee.categories=ee.categories.filter(e=>!e.name);else{ee=("function"==typeof e.data?await e.data():e.data)||await ne(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/sets/${t}/${n}.json`),ee.emoticons={},ee.natives={},ee.categories.unshift({id:"frequent",emojis:[]});for(const e in ee.aliases){const t=ee.aliases[e],n=ee.emojis[t];n&&(n.aliases||(n.aliases=[]),n.aliases.push(e))}ee.originalCategories=ee.categories}if(Q=("function"==typeof e.i18n?await e.i18n():e.i18n)||("en"==i?o(J):await ne(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/i18n/${i}.json`)),e.custom)for(let t in e.custom){t=parseInt(t);const n=e.custom[t],o=e.custom[t-1];if(n.emojis&&n.emojis.length){n.id||(n.id=`custom_${t+1}`),n.name||(n.name=Q.categories.custom),o&&!n.icon&&(n.target=o.target||o),ee.categories.push(n);for(const e of n.emojis)ee.emojis[e.id]=e}}e.categories&&(ee.categories=ee.originalCategories.filter(t=>-1!=e.categories.indexOf(t.id)).sort((t,n)=>e.categories.indexOf(t.id)-e.categories.indexOf(n.id)));let r=null,s=null;"native"==n&&(r=W(),s=e.noCountryFlags||K());let a=ee.categories.length,l=!1;for(;a--;){const t=ee.categories[a];if("frequent"==t.id){let{maxFrequentRows:n,perLine:o}=e;n=n>=0?n:Z.maxFrequentRows.value,o||(o=Z.perLine.value),t.emojis=Y.get({maxFrequentRows:n,perLine:o})}if(!t.emojis||!t.emojis.length){ee.categories.splice(a,1);continue}const{categoryIcons:n}=e;if(n){const e=n[t.id];e&&!t.icon&&(t.icon=e)}let o=t.emojis.length;for(;o--;){const n=t.emojis[o],i=n.id?n:ee.emojis[n],a=()=>{t.emojis.splice(o,1)};if(!i||e.exceptEmojis&&e.exceptEmojis.includes(i.id))a();else if(r&&i.version>r)a();else if(!s||"flags"!=t.id||he.includes(i.id)){if(!i.search){if(l=!0,i.search=","+[[i.id,!1],[i.name,!0],[i.keywords,!1],[i.emoticons,!1]].map(([e,t])=>{if(e)return(Array.isArray(e)?e:[e]).map(e=>(t?e.split(/[-|_|\s]+/):[e]).map(e=>e.toLowerCase())).flat()}).flat().filter(e=>e&&e.trim()).join(","),i.emoticons)for(const e of i.emoticons)ee.emoticons[e]||(ee.emoticons[e]=i.id);let e=0;for(const t of i.skins){if(!t)continue;e++;const{native:n}=t;n&&(ee.natives[n]=i.id,i.search+=`,${n}`);const o=1==e?"":`:skin-tone-${e}:`;t.shortcodes=`:${i.id}:${o}`}}}else a()}}l&&de.reset(),ie()}(e):t&&!re&&console.warn(`\`${t}\` requires data to be initialized first. Promise will be pending until \`init\` is called.`),oe}function ae(e,t,n){e||(e={});const o={};for(let i in t)o[i]=le(i,e,t,n);return o}function le(e,t,n,o){const i=n[e];let r=o&&o.getAttribute(e)||(null!=t[e]&&null!=t[e]?t[e]:null);return i?(null!=r&&i.value&&typeof i.value!=typeof r&&(r="boolean"==typeof i.value?"false"!=r:i.value.constructor(r)),i.transform&&r&&(r=i.transform(r)),(null==r||i.choices&&-1==i.choices.indexOf(r))&&(r=i.value),r):r}let ce=null;var de={search:async function(e,{maxResults:t,caller:n}={}){if(!e||!e.trim().length)return null;t||(t=90),await se(null,{caller:n||"SearchIndex.search"});const o=e.toLowerCase().replace(/(\w)-/,"$1 ").split(/[\s|,]+/).filter((e,t,n)=>e.trim()&&n.indexOf(e)==t);if(!o.length)return;let i,r,s=ce||(ce=Object.values(ee.emojis));for(const e of o){if(!s.length)break;i=[],r={};for(const t of s){if(!t.search)continue;const n=t.search.indexOf(`,${e}`);-1!=n&&(i.push(t),r[t.id]||(r[t.id]=0),r[t.id]+=t.id==e?0:n+1)}s=i}return i.length<2||(i.sort((e,t)=>{const n=r[e.id],o=r[t.id];return n==o?e.id.localeCompare(t.id):n-o}),i.length>t&&(i=i.slice(0,t))),i},get:function(e){return e.id?e:ee.emojis[e]||ee.emojis[ee.aliases[e]]||ee.emojis[ee.natives[e]]},reset:function(){ce=null},SHORTCODES_REGEX:/^(?:\:([^\:]+)\:)(?:\:skin-tone-(\d)\:)?$/};const he=["checkered_flag","crossed_flags","pirate_flag","rainbow-flag","transgender_flag","triangular_flag_on_post","waving_black_flag","waving_white_flag"];function ue(e,{skinIndex:t=0}={}){const n=e.skins[t]||(t=0,e.skins[t]),o={id:e.id,name:e.name,native:n.native,unified:n.unified,keywords:e.keywords,shortcodes:n.shortcodes||e.shortcodes};return e.skins.length>1&&(o.skin=t+1),n.src&&(o.src=n.src),e.aliases&&e.aliases.length&&(o.aliases=e.aliases),e.emoticons&&e.emoticons.length&&(o.emoticons=e.emoticons),o}async function pe(e){const t=await de.search(e,{maxResults:1,caller:"getEmojiDataFromNative"});if(!t||!t.length)return null;const n=t[0];let o=0;for(let t of n.skins){if(t.native==e)break;o++}return ue(n,{skinIndex:o})}var fe={categories:{activity:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M12 0C5.373 0 0 5.372 0 12c0 6.627 5.373 12 12 12 6.628 0 12-5.373 12-12 0-6.628-5.372-12-12-12m9.949 11H17.05c.224-2.527 1.232-4.773 1.968-6.113A9.966 9.966 0 0 1 21.949 11M13 11V2.051a9.945 9.945 0 0 1 4.432 1.564c-.858 1.491-2.156 4.22-2.392 7.385H13zm-2 0H8.961c-.238-3.165-1.536-5.894-2.393-7.385A9.95 9.95 0 0 1 11 2.051V11zm0 2v8.949a9.937 9.937 0 0 1-4.432-1.564c.857-1.492 2.155-4.221 2.393-7.385H11zm4.04 0c.236 3.164 1.534 5.893 2.392 7.385A9.92 9.92 0 0 1 13 21.949V13h2.04zM4.982 4.887C5.718 6.227 6.726 8.473 6.951 11h-4.9a9.977 9.977 0 0 1 2.931-6.113M2.051 13h4.9c-.226 2.527-1.233 4.771-1.969 6.113A9.972 9.972 0 0 1 2.051 13m16.967 6.113c-.735-1.342-1.744-3.586-1.968-6.113h4.899a9.961 9.961 0 0 1-2.931 6.113"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M16.17 337.5c0 44.98 7.565 83.54 13.98 107.9C35.22 464.3 50.46 496 174.9 496c9.566 0 19.59-.4707 29.84-1.271L17.33 307.3C16.53 317.6 16.17 327.7 16.17 337.5zM495.8 174.5c0-44.98-7.565-83.53-13.98-107.9c-4.688-17.54-18.34-31.23-36.04-35.95C435.5 27.91 392.9 16 337 16c-9.564 0-19.59 .4707-29.84 1.271l187.5 187.5C495.5 194.4 495.8 184.3 495.8 174.5zM26.77 248.8l236.3 236.3c142-36.1 203.9-150.4 222.2-221.1L248.9 26.87C106.9 62.96 45.07 177.2 26.77 248.8zM256 335.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L164.7 283.3C161.6 280.2 160 276.1 160 271.1c0-8.529 6.865-16 16-16c4.095 0 8.189 1.562 11.31 4.688l64.01 64C254.4 327.8 256 331.9 256 335.1zM304 287.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L212.7 235.3C209.6 232.2 208 228.1 208 223.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01C302.5 279.8 304 283.9 304 287.1zM256 175.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01c3.125 3.125 4.688 7.219 4.688 11.31c0 9.133-7.468 16-16 16c-4.094 0-8.189-1.562-11.31-4.688l-64.01-64.01C257.6 184.2 256 180.1 256 175.1z"})})},custom:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",children:V("path",{d:"M417.1 368c-5.937 10.27-16.69 16-27.75 16c-5.422 0-10.92-1.375-15.97-4.281L256 311.4V448c0 17.67-14.33 32-31.1 32S192 465.7 192 448V311.4l-118.3 68.29C68.67 382.6 63.17 384 57.75 384c-11.06 0-21.81-5.734-27.75-16c-8.828-15.31-3.594-34.88 11.72-43.72L159.1 256L41.72 187.7C26.41 178.9 21.17 159.3 29.1 144C36.63 132.5 49.26 126.7 61.65 128.2C65.78 128.7 69.88 130.1 73.72 132.3L192 200.6V64c0-17.67 14.33-32 32-32S256 46.33 256 64v136.6l118.3-68.29c3.838-2.213 7.939-3.539 12.07-4.051C398.7 126.7 411.4 132.5 417.1 144c8.828 15.31 3.594 34.88-11.72 43.72L288 256l118.3 68.28C421.6 333.1 426.8 352.7 417.1 368z"})}),flags:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M0 0l6.084 24H8L1.916 0zM21 5h-4l-1-4H4l3 12h3l1 4h13L21 5zM6.563 3h7.875l2 8H8.563l-2-8zm8.832 10l-2.856 1.904L12.063 13h3.332zM19 13l-1.5-6h1.938l2 8H16l3-2z"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M64 496C64 504.8 56.75 512 48 512h-32C7.25 512 0 504.8 0 496V32c0-17.75 14.25-32 32-32s32 14.25 32 32V496zM476.3 0c-6.365 0-13.01 1.35-19.34 4.233c-45.69 20.86-79.56 27.94-107.8 27.94c-59.96 0-94.81-31.86-163.9-31.87C160.9 .3055 131.6 4.867 96 15.75v350.5c32-9.984 59.87-14.1 84.85-14.1c73.63 0 124.9 31.78 198.6 31.78c31.91 0 68.02-5.971 111.1-23.09C504.1 355.9 512 344.4 512 332.1V30.73C512 11.1 495.3 0 476.3 0z"})})},foods:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M17 4.978c-1.838 0-2.876.396-3.68.934.513-1.172 1.768-2.934 4.68-2.934a1 1 0 0 0 0-2c-2.921 0-4.629 1.365-5.547 2.512-.064.078-.119.162-.18.244C11.73 1.838 10.798.023 9.207.023 8.579.022 7.85.306 7 .978 5.027 2.54 5.329 3.902 6.492 4.999 3.609 5.222 0 7.352 0 12.969c0 4.582 4.961 11.009 9 11.009 1.975 0 2.371-.486 3-1 .629.514 1.025 1 3 1 4.039 0 9-6.418 9-11 0-5.953-4.055-8-7-8M8.242 2.546c.641-.508.943-.523.965-.523.426.169.975 1.405 1.357 3.055-1.527-.629-2.741-1.352-2.98-1.846.059-.112.241-.356.658-.686M15 21.978c-1.08 0-1.21-.109-1.559-.402l-.176-.146c-.367-.302-.816-.452-1.266-.452s-.898.15-1.266.452l-.176.146c-.347.292-.477.402-1.557.402-2.813 0-7-5.389-7-9.009 0-5.823 4.488-5.991 5-5.991 1.939 0 2.484.471 3.387 1.251l.323.276a1.995 1.995 0 0 0 2.58 0l.323-.276c.902-.78 1.447-1.251 3.387-1.251.512 0 5 .168 5 6 0 3.617-4.187 9-7 9"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M481.9 270.1C490.9 279.1 496 291.3 496 304C496 316.7 490.9 328.9 481.9 337.9C472.9 346.9 460.7 352 448 352H64C51.27 352 39.06 346.9 30.06 337.9C21.06 328.9 16 316.7 16 304C16 291.3 21.06 279.1 30.06 270.1C39.06 261.1 51.27 256 64 256H448C460.7 256 472.9 261.1 481.9 270.1zM475.3 388.7C478.3 391.7 480 395.8 480 400V416C480 432.1 473.3 449.3 461.3 461.3C449.3 473.3 432.1 480 416 480H96C79.03 480 62.75 473.3 50.75 461.3C38.74 449.3 32 432.1 32 416V400C32 395.8 33.69 391.7 36.69 388.7C39.69 385.7 43.76 384 48 384H464C468.2 384 472.3 385.7 475.3 388.7zM50.39 220.8C45.93 218.6 42.03 215.5 38.97 211.6C35.91 207.7 33.79 203.2 32.75 198.4C31.71 193.5 31.8 188.5 32.99 183.7C54.98 97.02 146.5 32 256 32C365.5 32 457 97.02 479 183.7C480.2 188.5 480.3 193.5 479.2 198.4C478.2 203.2 476.1 207.7 473 211.6C469.1 215.5 466.1 218.6 461.6 220.8C457.2 222.9 452.3 224 447.3 224H64.67C59.73 224 54.84 222.9 50.39 220.8zM372.7 116.7C369.7 119.7 368 123.8 368 128C368 131.2 368.9 134.3 370.7 136.9C372.5 139.5 374.1 141.6 377.9 142.8C380.8 143.1 384 144.3 387.1 143.7C390.2 143.1 393.1 141.6 395.3 139.3C397.6 137.1 399.1 134.2 399.7 131.1C400.3 128 399.1 124.8 398.8 121.9C397.6 118.1 395.5 116.5 392.9 114.7C390.3 112.9 387.2 111.1 384 111.1C379.8 111.1 375.7 113.7 372.7 116.7V116.7zM244.7 84.69C241.7 87.69 240 91.76 240 96C240 99.16 240.9 102.3 242.7 104.9C244.5 107.5 246.1 109.6 249.9 110.8C252.8 111.1 256 112.3 259.1 111.7C262.2 111.1 265.1 109.6 267.3 107.3C269.6 105.1 271.1 102.2 271.7 99.12C272.3 96.02 271.1 92.8 270.8 89.88C269.6 86.95 267.5 84.45 264.9 82.7C262.3 80.94 259.2 79.1 256 79.1C251.8 79.1 247.7 81.69 244.7 84.69V84.69zM116.7 116.7C113.7 119.7 112 123.8 112 128C112 131.2 112.9 134.3 114.7 136.9C116.5 139.5 118.1 141.6 121.9 142.8C124.8 143.1 128 144.3 131.1 143.7C134.2 143.1 137.1 141.6 139.3 139.3C141.6 137.1 143.1 134.2 143.7 131.1C144.3 128 143.1 124.8 142.8 121.9C141.6 118.1 139.5 116.5 136.9 114.7C134.3 112.9 131.2 111.1 128 111.1C123.8 111.1 119.7 113.7 116.7 116.7L116.7 116.7z"})})},frequent:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M13 4h-2l-.001 7H9v2h2v2h2v-2h4v-2h-4z"}),V("path",{d:"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512zM232 256C232 264 236 271.5 242.7 275.1L338.7 339.1C349.7 347.3 364.6 344.3 371.1 333.3C379.3 322.3 376.3 307.4 365.3 300L280 243.2V120C280 106.7 269.3 96 255.1 96C242.7 96 231.1 106.7 231.1 120L232 256z"})})},nature:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M15.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 15.5 8M8.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 8.5 8"}),V("path",{d:"M18.933 0h-.027c-.97 0-2.138.787-3.018 1.497-1.274-.374-2.612-.51-3.887-.51-1.285 0-2.616.133-3.874.517C7.245.79 6.069 0 5.093 0h-.027C3.352 0 .07 2.67.002 7.026c-.039 2.479.276 4.238 1.04 5.013.254.258.882.677 1.295.882.191 3.177.922 5.238 2.536 6.38.897.637 2.187.949 3.2 1.102C8.04 20.6 8 20.795 8 21c0 1.773 2.35 3 4 3 1.648 0 4-1.227 4-3 0-.201-.038-.393-.072-.586 2.573-.385 5.435-1.877 5.925-7.587.396-.22.887-.568 1.104-.788.763-.774 1.079-2.534 1.04-5.013C23.929 2.67 20.646 0 18.933 0M3.223 9.135c-.237.281-.837 1.155-.884 1.238-.15-.41-.368-1.349-.337-3.291.051-3.281 2.478-4.972 3.091-5.031.256.015.731.27 1.265.646-1.11 1.171-2.275 2.915-2.352 5.125-.133.546-.398.858-.783 1.313M12 22c-.901 0-1.954-.693-2-1 0-.654.475-1.236 1-1.602V20a1 1 0 1 0 2 0v-.602c.524.365 1 .947 1 1.602-.046.307-1.099 1-2 1m3-3.48v.02a4.752 4.752 0 0 0-1.262-1.02c1.092-.516 2.239-1.334 2.239-2.217 0-1.842-1.781-2.195-3.977-2.195-2.196 0-3.978.354-3.978 2.195 0 .883 1.148 1.701 2.238 2.217A4.8 4.8 0 0 0 9 18.539v-.025c-1-.076-2.182-.281-2.973-.842-1.301-.92-1.838-3.045-1.853-6.478l.023-.041c.496-.826 1.49-1.45 1.804-3.102 0-2.047 1.357-3.631 2.362-4.522C9.37 3.178 10.555 3 11.948 3c1.447 0 2.685.192 3.733.57 1 .9 2.316 2.465 2.316 4.48.313 1.651 1.307 2.275 1.803 3.102.035.058.068.117.102.178-.059 5.967-1.949 7.01-4.902 7.19m6.628-8.202c-.037-.065-.074-.13-.113-.195a7.587 7.587 0 0 0-.739-.987c-.385-.455-.648-.768-.782-1.313-.076-2.209-1.241-3.954-2.353-5.124.531-.376 1.004-.63 1.261-.647.636.071 3.044 1.764 3.096 5.031.027 1.81-.347 3.218-.37 3.235"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 576 512",children:V("path",{d:"M332.7 19.85C334.6 8.395 344.5 0 356.1 0C363.6 0 370.6 3.52 375.1 9.502L392 32H444.1C456.8 32 469.1 37.06 478.1 46.06L496 64H552C565.3 64 576 74.75 576 88V112C576 156.2 540.2 192 496 192H426.7L421.6 222.5L309.6 158.5L332.7 19.85zM448 64C439.2 64 432 71.16 432 80C432 88.84 439.2 96 448 96C456.8 96 464 88.84 464 80C464 71.16 456.8 64 448 64zM416 256.1V480C416 497.7 401.7 512 384 512H352C334.3 512 320 497.7 320 480V364.8C295.1 377.1 268.8 384 240 384C211.2 384 184 377.1 160 364.8V480C160 497.7 145.7 512 128 512H96C78.33 512 64 497.7 64 480V249.8C35.23 238.9 12.64 214.5 4.836 183.3L.9558 167.8C-3.331 150.6 7.094 133.2 24.24 128.1C41.38 124.7 58.76 135.1 63.05 152.2L66.93 167.8C70.49 182 83.29 191.1 97.97 191.1H303.8L416 256.1z"})})},objects:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M12 0a9 9 0 0 0-5 16.482V21s2.035 3 5 3 5-3 5-3v-4.518A9 9 0 0 0 12 0zm0 2c3.86 0 7 3.141 7 7s-3.14 7-7 7-7-3.141-7-7 3.14-7 7-7zM9 17.477c.94.332 1.946.523 3 .523s2.06-.19 3-.523v.834c-.91.436-1.925.689-3 .689a6.924 6.924 0 0 1-3-.69v-.833zm.236 3.07A8.854 8.854 0 0 0 12 21c.965 0 1.888-.167 2.758-.451C14.155 21.173 13.153 22 12 22c-1.102 0-2.117-.789-2.764-1.453z"}),V("path",{d:"M14.745 12.449h-.004c-.852-.024-1.188-.858-1.577-1.824-.421-1.061-.703-1.561-1.182-1.566h-.009c-.481 0-.783.497-1.235 1.537-.436.982-.801 1.811-1.636 1.791l-.276-.043c-.565-.171-.853-.691-1.284-1.794-.125-.313-.202-.632-.27-.913-.051-.213-.127-.53-.195-.634C7.067 9.004 7.039 9 6.99 9A1 1 0 0 1 7 7h.01c1.662.017 2.015 1.373 2.198 2.134.486-.981 1.304-2.058 2.797-2.075 1.531.018 2.28 1.153 2.731 2.141l.002-.008C14.944 8.424 15.327 7 16.979 7h.032A1 1 0 1 1 17 9h-.011c-.149.076-.256.474-.319.709a6.484 6.484 0 0 1-.311.951c-.429.973-.79 1.789-1.614 1.789"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",children:V("path",{d:"M112.1 454.3c0 6.297 1.816 12.44 5.284 17.69l17.14 25.69c5.25 7.875 17.17 14.28 26.64 14.28h61.67c9.438 0 21.36-6.401 26.61-14.28l17.08-25.68c2.938-4.438 5.348-12.37 5.348-17.7L272 415.1h-160L112.1 454.3zM191.4 .0132C89.44 .3257 16 82.97 16 175.1c0 44.38 16.44 84.84 43.56 115.8c16.53 18.84 42.34 58.23 52.22 91.45c.0313 .25 .0938 .5166 .125 .7823h160.2c.0313-.2656 .0938-.5166 .125-.7823c9.875-33.22 35.69-72.61 52.22-91.45C351.6 260.8 368 220.4 368 175.1C368 78.61 288.9-.2837 191.4 .0132zM192 96.01c-44.13 0-80 35.89-80 79.1C112 184.8 104.8 192 96 192S80 184.8 80 176c0-61.76 50.25-111.1 112-111.1c8.844 0 16 7.159 16 16S200.8 96.01 192 96.01z"})})},people:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10"}),V("path",{d:"M8 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 8 7M16 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 16 7M15.232 15c-.693 1.195-1.87 2-3.349 2-1.477 0-2.655-.805-3.347-2H15m3-2H6a6 6 0 1 0 12 0"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256zM256 432C332.1 432 396.2 382 415.2 314.1C419.1 300.4 407.8 288 393.6 288H118.4C104.2 288 92.92 300.4 96.76 314.1C115.8 382 179.9 432 256 432V432zM176.4 160C158.7 160 144.4 174.3 144.4 192C144.4 209.7 158.7 224 176.4 224C194 224 208.4 209.7 208.4 192C208.4 174.3 194 160 176.4 160zM336.4 224C354 224 368.4 209.7 368.4 192C368.4 174.3 354 160 336.4 160C318.7 160 304.4 174.3 304.4 192C304.4 209.7 318.7 224 336.4 224z"})})},places:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M6.5 12C5.122 12 4 13.121 4 14.5S5.122 17 6.5 17 9 15.879 9 14.5 7.878 12 6.5 12m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5M17.5 12c-1.378 0-2.5 1.121-2.5 2.5s1.122 2.5 2.5 2.5 2.5-1.121 2.5-2.5-1.122-2.5-2.5-2.5m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5"}),V("path",{d:"M22.482 9.494l-1.039-.346L21.4 9h.6c.552 0 1-.439 1-.992 0-.006-.003-.008-.003-.008H23c0-1-.889-2-1.984-2h-.642l-.731-1.717C19.262 3.012 18.091 2 16.764 2H7.236C5.909 2 4.738 3.012 4.357 4.283L3.626 6h-.642C1.889 6 1 7 1 8h.003S1 8.002 1 8.008C1 8.561 1.448 9 2 9h.6l-.043.148-1.039.346a2.001 2.001 0 0 0-1.359 2.097l.751 7.508a1 1 0 0 0 .994.901H3v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h6v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h1.096a.999.999 0 0 0 .994-.901l.751-7.508a2.001 2.001 0 0 0-1.359-2.097M6.273 4.857C6.402 4.43 6.788 4 7.236 4h9.527c.448 0 .834.43.963.857L19.313 9H4.688l1.585-4.143zM7 21H5v-1h2v1zm12 0h-2v-1h2v1zm2.189-3H2.811l-.662-6.607L3 11h18l.852.393L21.189 18z"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M39.61 196.8L74.8 96.29C88.27 57.78 124.6 32 165.4 32H346.6C387.4 32 423.7 57.78 437.2 96.29L472.4 196.8C495.6 206.4 512 229.3 512 256V448C512 465.7 497.7 480 480 480H448C430.3 480 416 465.7 416 448V400H96V448C96 465.7 81.67 480 64 480H32C14.33 480 0 465.7 0 448V256C0 229.3 16.36 206.4 39.61 196.8V196.8zM109.1 192H402.9L376.8 117.4C372.3 104.6 360.2 96 346.6 96H165.4C151.8 96 139.7 104.6 135.2 117.4L109.1 192zM96 256C78.33 256 64 270.3 64 288C64 305.7 78.33 320 96 320C113.7 320 128 305.7 128 288C128 270.3 113.7 256 96 256zM416 320C433.7 320 448 305.7 448 288C448 270.3 433.7 256 416 256C398.3 256 384 270.3 384 288C384 305.7 398.3 320 416 320z"})})},symbols:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M0 0h11v2H0zM4 11h3V6h4V4H0v2h4zM15.5 17c1.381 0 2.5-1.116 2.5-2.493s-1.119-2.493-2.5-2.493S13 13.13 13 14.507 14.119 17 15.5 17m0-2.986c.276 0 .5.222.5.493 0 .272-.224.493-.5.493s-.5-.221-.5-.493.224-.493.5-.493M21.5 19.014c-1.381 0-2.5 1.116-2.5 2.493S20.119 24 21.5 24s2.5-1.116 2.5-2.493-1.119-2.493-2.5-2.493m0 2.986a.497.497 0 0 1-.5-.493c0-.271.224-.493.5-.493s.5.222.5.493a.497.497 0 0 1-.5.493M22 13l-9 9 1.513 1.5 8.99-9.009zM17 11c2.209 0 4-1.119 4-2.5V2s.985-.161 1.498.949C23.01 4.055 23 6 23 6s1-1.119 1-3.135C24-.02 21 0 21 0h-2v6.347A5.853 5.853 0 0 0 17 6c-2.209 0-4 1.119-4 2.5s1.791 2.5 4 2.5M10.297 20.482l-1.475-1.585a47.54 47.54 0 0 1-1.442 1.129c-.307-.288-.989-1.016-2.045-2.183.902-.836 1.479-1.466 1.729-1.892s.376-.871.376-1.336c0-.592-.273-1.178-.818-1.759-.546-.581-1.329-.871-2.349-.871-1.008 0-1.79.293-2.344.879-.556.587-.832 1.181-.832 1.784 0 .813.419 1.748 1.256 2.805-.847.614-1.444 1.208-1.794 1.784a3.465 3.465 0 0 0-.523 1.833c0 .857.308 1.56.924 2.107.616.549 1.423.823 2.42.823 1.173 0 2.444-.379 3.813-1.137L8.235 24h2.819l-2.09-2.383 1.333-1.135zm-6.736-6.389a1.02 1.02 0 0 1 .73-.286c.31 0 .559.085.747.254a.849.849 0 0 1 .283.659c0 .518-.419 1.112-1.257 1.784-.536-.651-.805-1.231-.805-1.742a.901.901 0 0 1 .302-.669M3.74 22c-.427 0-.778-.116-1.057-.349-.279-.232-.418-.487-.418-.766 0-.594.509-1.288 1.527-2.083.968 1.134 1.717 1.946 2.248 2.438-.921.507-1.686.76-2.3.76"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M500.3 7.251C507.7 13.33 512 22.41 512 31.1V175.1C512 202.5 483.3 223.1 447.1 223.1C412.7 223.1 383.1 202.5 383.1 175.1C383.1 149.5 412.7 127.1 447.1 127.1V71.03L351.1 90.23V207.1C351.1 234.5 323.3 255.1 287.1 255.1C252.7 255.1 223.1 234.5 223.1 207.1C223.1 181.5 252.7 159.1 287.1 159.1V63.1C287.1 48.74 298.8 35.61 313.7 32.62L473.7 .6198C483.1-1.261 492.9 1.173 500.3 7.251H500.3zM74.66 303.1L86.5 286.2C92.43 277.3 102.4 271.1 113.1 271.1H174.9C185.6 271.1 195.6 277.3 201.5 286.2L213.3 303.1H239.1C266.5 303.1 287.1 325.5 287.1 351.1V463.1C287.1 490.5 266.5 511.1 239.1 511.1H47.1C21.49 511.1-.0019 490.5-.0019 463.1V351.1C-.0019 325.5 21.49 303.1 47.1 303.1H74.66zM143.1 359.1C117.5 359.1 95.1 381.5 95.1 407.1C95.1 434.5 117.5 455.1 143.1 455.1C170.5 455.1 191.1 434.5 191.1 407.1C191.1 381.5 170.5 359.1 143.1 359.1zM440.3 367.1H496C502.7 367.1 508.6 372.1 510.1 378.4C513.3 384.6 511.6 391.7 506.5 396L378.5 508C372.9 512.1 364.6 513.3 358.6 508.9C352.6 504.6 350.3 496.6 353.3 489.7L391.7 399.1H336C329.3 399.1 323.4 395.9 321 389.6C318.7 383.4 320.4 376.3 325.5 371.1L453.5 259.1C459.1 255 467.4 254.7 473.4 259.1C479.4 263.4 481.6 271.4 478.7 278.3L440.3 367.1zM116.7 219.1L19.85 119.2C-8.112 90.26-6.614 42.31 24.85 15.34C51.82-8.137 93.26-3.642 118.2 21.83L128.2 32.32L137.7 21.83C162.7-3.642 203.6-8.137 231.6 15.34C262.6 42.31 264.1 90.26 236.1 119.2L139.7 219.1C133.2 225.6 122.7 225.6 116.7 219.1H116.7z"})})}},search:{loupe:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:V("path",{d:"M12.9 14.32a8 8 0 1 1 1.41-1.41l5.35 5.33-1.42 1.42-5.33-5.34zM8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12z"})}),delete:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:V("path",{d:"M10 8.586L2.929 1.515 1.515 2.929 8.586 10l-7.071 7.071 1.414 1.414L10 11.414l7.071 7.071 1.414-1.414L11.414 10l7.071-7.071-1.414-1.414L10 8.586z"})})}};function _e(e){let{id:t,skin:n,emoji:o}=e;if(e.shortcodes){const o=e.shortcodes.match(de.SHORTCODES_REGEX);o&&(t=o[1],o[2]&&(n=o[2]))}if(o||(o=de.get(t||e.native)),!o)return e.fallback;const i=o.skins[n-1]||o.skins[0],r=i.src||("native"==e.set||e.spritesheet?void 0:"function"==typeof e.getImageURL?e.getImageURL(e.set,i.unified):`https://cdn.jsdelivr.net/npm/emoji-datasource-${e.set}@15.0.1/img/${e.set}/64/${i.unified}.png`),s="function"==typeof e.getSpritesheetURL?e.getSpritesheetURL(e.set):`https://cdn.jsdelivr.net/npm/emoji-datasource-${e.set}@15.0.1/img/${e.set}/sheets-256/64.png`;return V("span",{class:"emoji-mart-emoji","data-emoji-set":e.set,children:r?V("img",{style:{maxWidth:e.size||"1em",maxHeight:e.size||"1em",display:"inline-block"},alt:i.native||i.shortcodes,src:r}):"native"==e.set?V("span",{style:{fontSize:e.size,fontFamily:'"EmojiMart", "Segoe UI Emoji", "Segoe UI Symbol", "Segoe UI", "Apple Color Emoji", "Twemoji Mozilla", "Noto Color Emoji", "Android Emoji"'},children:i.native}):V("span",{style:{display:"block",width:e.size,height:e.size,backgroundImage:`url(${s})`,backgroundSize:`${100*ee.sheet.cols}% ${100*ee.sheet.rows}%`,backgroundPosition:`${100/(ee.sheet.cols-1)*i.x}% ${100/(ee.sheet.rows-1)*i.y}%`}})})}const ge="undefined"!=typeof window&&window.HTMLElement?window.HTMLElement:Object;class me extends ge{static get observedAttributes(){return Object.keys(this.Props)}update(e={}){for(let t in e)this.attributeChangedCallback(t,null,e[t])}attributeChangedCallback(e,t,n){if(!this.component)return;const o=le(e,{[e]:n},this.constructor.Props,this);this.component.componentWillReceiveProps?this.component.componentWillReceiveProps({[e]:o}):(this.component.props[e]=o,this.component.forceUpdate())}disconnectedCallback(){this.disconnected=!0,this.component&&this.component.unregister&&this.component.unregister()}constructor(e={}){if(super(),this.props=e,e.parent||e.ref){let t=null;const n=e.parent||(t=e.ref&&e.ref.current);t&&(t.innerHTML=""),n&&n.appendChild(this)}}}class ve extends me{setShadow(){this.attachShadow({mode:"open"})}injectStyles(e){if(!e)return;const t=document.createElement("style");t.textContent=e,this.shadowRoot.insertBefore(t,this.shadowRoot.firstChild)}constructor(e,{styles:t}={}){super(e),this.setShadow(),this.injectStyles(t)}}var be={fallback:"",id:"",native:"",shortcodes:"",size:{value:"",transform:e=>/\D/.test(e)?e:`${e}px`},set:Z.set,skin:Z.skin};class ke extends me{async connectedCallback(){const e=ae(this.props,be,this);e.element=this,e.ref=e=>{this.component=e},await se(),this.disconnected||O(V(_e,{...e}),this)}constructor(e){super(e)}}i(ke,"Props",be),"undefined"==typeof customElements||customElements.get("em-emoji")||customElements.define("em-emoji",ke);var we,ye,Ce=[],xe=s.__b,Se=s.__r,je=s.diffed,ze=s.__c,Me=s.unmount;function Le(){var e;for(Ce.sort(function(e,t){return e.__v.__b-t.__v.__b});e=Ce.pop();)if(e.__P)try{e.__H.__h.forEach(Pe),e.__H.__h.forEach(Re),e.__H.__h=[]}catch(t){e.__H.__h=[],s.__e(t,e.__v)}}s.__b=function(e){we=null,xe&&xe(e)},s.__r=function(e){Se&&Se(e);var t=(we=e.__c).__H;t&&(t.__h.forEach(Pe),t.__h.forEach(Re),t.__h=[])},s.diffed=function(e){je&&je(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Ce.push(t)&&ye===s.requestAnimationFrame||((ye=s.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(o),Ee&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,100);Ee&&(t=requestAnimationFrame(n))})(Le)),we=null},s.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Pe),e.__h=e.__h.filter(function(e){return!e.__||Re(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],s.__e(n,e.__v)}}),ze&&ze(e,t)},s.unmount=function(e){Me&&Me(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Pe(e)}catch(e){t=e}}),t&&s.__e(t,n.__v))};var Ee="function"==typeof requestAnimationFrame;function Pe(e){var t=we,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),we=t}function Re(e){var t=we;e.__c=e.__(),we=t}function Be(e,t){for(var n in e)if("__source"!==n&&!(n in t))return!0;for(var o in t)if("__source"!==o&&e[o]!==t[o])return!0;return!1}function He(e){this.props=e}(He.prototype=new k).isPureReactComponent=!0,He.prototype.shouldComponentUpdate=function(e,t){return Be(this.props,e)||Be(this.state,t)};var Ae=s.__b;s.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Ae&&Ae(e)},"undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.forward_ref");var Te=s.__e;s.__e=function(e,t,n){if(e.then)for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return null==t.__e&&(t.__e=n.__e,t.__k=n.__k),o.__c(e,t);Te(e,t,n)};var Ie=s.unmount;function Oe(){this.__u=0,this.t=null,this.__b=null}function De(e){var t=e.__.__c;return t&&t.__e&&t.__e(e)}function Ve(){this.u=null,this.o=null}s.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&!0===e.__h&&(e.type=null),Ie&&Ie(e)},(Oe.prototype=new k).__c=function(e,t){var n=t.__c,o=this;null==o.t&&(o.t=[]),o.t.push(n);var i=De(o.__v),r=!1,s=function(){r||(r=!0,n.__R=null,i?i(a):a())};n.__R=s;var a=function(){if(! --o.__u){if(o.state.__e){var e=o.state.__e;o.__v.__k[0]=function e(t,n,o){return t&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(t){return e(t,n,o)}),t.__c&&t.__c.__P===n&&(t.__e&&o.insertBefore(t.__e,t.__d),t.__c.__e=!0,t.__c.__P=o)),t}(e,e.__c.__P,e.__c.__O)}var t;for(o.setState({__e:o.__b=null});t=o.t.pop();)t.forceUpdate()}},l=!0===t.__h;o.__u++||l||o.setState({__e:o.__b=o.__v.__k[0]}),e.then(s,s)},Oe.prototype.componentWillUnmount=function(){this.t=[]},Oe.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=function e(t,n,o){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(e){"function"==typeof e.__c&&e.__c()}),t.__c.__H=null),null!=(t=function(e,t){for(var n in t)e[n]=t[n];return e}({},t)).__c&&(t.__c.__P===o&&(t.__c.__P=n),t.__c=null),t.__k=t.__k&&t.__k.map(function(t){return e(t,n,o)})),t}(this.__b,n,o.__O=o.__P)}this.__b=null}var i=t.__e&&g(b,null,e.fallback);return i&&(i.__h=null),[g(b,null,t.__e?null:e.children),i]};var $e=function(e,t,n){if(++n[1]===n[0]&&e.o.delete(t),e.props.revealOrder&&("t"!==e.props.revealOrder[0]||!e.o.size))for(n=e.u;n;){for(;n.length>3;)n.pop()();if(n[1]{const o=t.name||Q.categories[t.id],i=!this.props.unfocused&&t.id==this.state.categoryId;return i&&(e=n),V("button",{"aria-label":o,"aria-selected":i||void 0,title:o,type:"button",class:"flex flex-grow flex-center",onMouseDown:e=>e.preventDefault(),onClick:()=>{this.props.onClick({category:t,i:n})},children:this.renderIcon(t)})}),V("div",{class:"bar",style:{width:100/this.categories.length+"%",opacity:null==e?0:1,transform:"rtl"===this.props.dir?`scaleX(-1) translateX(${100*e}%)`:`translateX(${100*e}%)`}})]})})}constructor(){super(),this.categories=ee.categories.filter(e=>!e.target),this.state={categoryId:this.categories[0].id}}}class tt extends He{shouldComponentUpdate(e){for(let t in e)if("children"!=t&&e[t]!=this.props[t])return!0;return!1}render(){return this.props.children}}class nt extends k{getInitialState(e=this.props){return{skin:$.get("skin")||e.skin,theme:this.initTheme(e.theme)}}componentWillMount(){this.dir=Q.rtl?"rtl":"ltr",this.refs={menu:{current:null},navigation:{current:null},scroll:{current:null},search:{current:null},searchInput:{current:null},skinToneButton:{current:null},skinToneRadio:{current:null}},this.initGrid(),0==this.props.stickySearch&&"sticky"==this.props.searchPosition&&(console.warn("[EmojiMart] Deprecation warning: `stickySearch` has been renamed `searchPosition`."),this.props.searchPosition="static")}componentDidMount(){if(this.register(),this.shadowRoot=this.base.parentNode,this.props.autoFocus){const{searchInput:e}=this.refs;e.current&&e.current.focus()}}componentWillReceiveProps(e){this.nextState||(this.nextState={});for(const t in e)this.nextState[t]=e[t];clearTimeout(this.nextStateTimer),this.nextStateTimer=setTimeout(()=>{let e=!1;for(const t in this.nextState)this.props[t]=this.nextState[t],"custom"!==t&&"categories"!==t||(e=!0);delete this.nextState;const t=this.getInitialState();if(e)return this.reset(t);this.setState(t)})}componentWillUnmount(){this.unregister()}async reset(e={}){await se(this.props),this.initGrid(),this.unobserve(),this.setState(e,()=>{this.observeCategories(),this.observeRows()})}register(){document.addEventListener("click",this.handleClickOutside),this.observe()}unregister(){document.removeEventListener("click",this.handleClickOutside),this.darkMedia?.removeEventListener("change",this.darkMediaCallback),this.unobserve()}observe(){this.observeCategories(),this.observeRows()}unobserve({except:e=[]}={}){Array.isArray(e)||(e=[e]);for(const t of this.observers)e.includes(t)||t.disconnect();this.observers=[].concat(e)}initGrid(){const{categories:e}=ee;this.refs.categories=new Map;const t=ee.categories.map(e=>e.id).join(",");this.navKey&&this.navKey!=t&&this.refs.scroll.current&&(this.refs.scroll.current.scrollTop=0),this.navKey=t,this.grid=[],this.grid.setsize=0;const n=(e,t)=>{const n=[];n.__categoryId=t.id,n.__index=e.length,this.grid.push(n);const o=this.grid.length-1,i=o%10?{}:{current:null};return i.index=o,i.posinset=this.grid.setsize+1,e.push(i),n};for(let t of e){const e=[];let o=n(e,t);for(let i of t.emojis)o.length==this.getPerLine()&&(o=n(e,t)),this.grid.setsize+=1,o.push(i);this.refs.categories.set(t.id,{root:v(),rows:e})}}initTheme(e){if("auto"!=e)return e;if(!this.darkMedia){if(this.darkMedia=matchMedia("(prefers-color-scheme: dark)"),this.darkMedia.media.match(/^not/))return"light";this.darkMedia.addEventListener("change",this.darkMediaCallback)}return this.darkMedia.matches?"dark":"light"}initDynamicPerLine(e=this.props){if(!e.dynamicWidth)return;const{element:t,emojiButtonSize:n}=e,o=()=>{const{width:e}=t.getBoundingClientRect();return Math.floor(e/n)},i=new ResizeObserver(()=>{this.unobserve({except:i}),this.setState({perLine:o()},()=>{this.initGrid(),this.forceUpdate(()=>{this.observeCategories(),this.observeRows()})})});return i.observe(t),this.observers.push(i),o()}getPerLine(){return this.state.perLine||this.props.perLine}getEmojiByPos([e,t]){const n=this.state.searchResults||this.grid,o=n[e]&&n[e][t];if(o)return de.get(o)}observeCategories(){const e=this.refs.navigation.current;if(!e)return;const t=new Map,n=t=>{t!=e.state.categoryId&&e.setState({categoryId:t})},o={root:this.refs.scroll.current,threshold:[0,1]},i=new IntersectionObserver(e=>{for(const n of e){const e=n.target.dataset.id;t.set(e,n.intersectionRatio)}const o=[...t];for(const[e,t]of o)if(t){n(e);break}},o);for(const{root:e}of this.refs.categories.values())i.observe(e.current);this.observers.push(i)}observeRows(){const e={...this.state.visibleRows},t=new IntersectionObserver(t=>{for(const n of t){const t=parseInt(n.target.dataset.index);n.isIntersecting?e[t]=!0:delete e[t]}this.setState({visibleRows:e})},{root:this.refs.scroll.current,rootMargin:`${15*this.props.emojiButtonSize}px 0px ${10*this.props.emojiButtonSize}px`});for(const{rows:e}of this.refs.categories.values())for(const n of e)n.current&&t.observe(n.current);this.observers.push(t)}preventDefault(e){e.preventDefault()}unfocusSearch(){const e=this.refs.searchInput.current;e&&e.blur()}navigate({e,input:t,left:n,right:o,up:i,down:r}){const s=this.state.searchResults||this.grid;if(!s.length)return;let[a,l]=this.state.pos;const c=(()=>{if(0==a&&0==l&&!e.repeat&&(n||i))return null;if(-1==a)return e.repeat||!o&&!r||t.selectionStart!=t.value.length?null:[0,0];if(n||o){let e=s[a];const t=n?-1:1;if(l+=t,!e[l]){if(a+=t,e=s[a],!e)return a=n?0:s.length-1,l=n?0:s[a].length-1,[a,l];l=n?e.length-1:0}return[a,l]}if(i||r){a+=i?-1:1;const e=s[a];return e?(e[l]||(l=e.length-1),[a,l]):(a=i?0:s.length-1,l=i?0:s[a].length-1,[a,l])}})();c?(e.preventDefault(),this.setState({pos:c,keyboard:!0},()=>{this.scrollTo({row:c[0]})})):this.state.pos[0]>-1&&this.setState({pos:[-1,-1]})}scrollTo({categoryId:e,row:t}){const n=this.state.searchResults||this.grid;if(!n.length)return;const o=this.refs.scroll.current,i=o.getBoundingClientRect();let r=0;if(t>=0&&(e=n[t].__categoryId),e&&(r=(this.refs[e]||this.refs.categories.get(e).root).current.getBoundingClientRect().top-(i.top-o.scrollTop)+1),t>=0)if(t){const e=r+n[t].__index*this.props.emojiButtonSize,s=e+this.props.emojiButtonSize+.88*this.props.emojiButtonSize;if(eo.scrollTop+i.height))return;r=s-i.height}}else r=0;this.ignoreMouse(),o.scrollTop=r}ignoreMouse(){this.mouseIsIgnored=!0,clearTimeout(this.ignoreMouseTimer),this.ignoreMouseTimer=setTimeout(()=>{delete this.mouseIsIgnored},100)}handleEmojiOver(e){this.mouseIsIgnored||this.state.showSkins||this.setState({pos:e||[-1,-1],keyboard:!1})}handleEmojiClick({e,emoji:t,pos:n}){if(this.props.onEmojiSelect&&(!t&&n&&(t=this.getEmojiByPos(n)),t)){const n=ue(t,{skinIndex:this.state.skin-1});this.props.maxFrequentRows&&Y.add(n,this.props),this.props.onEmojiSelect(n,e)}}closeSkins(){this.state.showSkins&&(this.setState({showSkins:null,tempSkin:null}),this.base.removeEventListener("click",this.handleBaseClick),this.base.removeEventListener("keydown",this.handleBaseKeydown))}handleSkinMouseOver(e){this.setState({tempSkin:e})}handleSkinClick(e){this.ignoreMouse(),this.closeSkins(),this.setState({skin:e,tempSkin:null}),$.set("skin",e)}renderNav(){return V(et,{ref:this.refs.navigation,icons:this.props.icons,theme:this.state.theme,dir:this.dir,unfocused:!!this.state.searchResults,position:this.props.navPosition,onClick:this.handleCategoryClick},this.navKey)}renderPreview(){const e=this.getEmojiByPos(this.state.pos),t=this.state.searchResults&&!this.state.searchResults.length;return V("div",{id:"preview",class:"flex flex-middle",dir:this.dir,"data-position":this.props.previewPosition,children:[V("div",{class:"flex flex-middle flex-grow",children:[V("div",{class:"flex flex-auto flex-middle flex-center",style:{height:this.props.emojiButtonSize,fontSize:this.props.emojiButtonSize},children:V(_e,{emoji:e,id:t?this.props.noResultsEmoji||"cry":this.props.previewEmoji||("top"==this.props.previewPosition?"point_down":"point_up"),set:this.props.set,size:this.props.emojiButtonSize,skin:this.state.tempSkin||this.state.skin,spritesheet:!0,getSpritesheetURL:this.props.getSpritesheetURL})}),V("div",{class:`margin-${this.dir[0]}`,children:V("div",e||t?{class:`padding-${this.dir[2]} align-${this.dir[0]}`,children:[V("div",{class:"preview-title ellipsis",children:e?e.name:Q.search_no_results_1}),V("div",{class:"preview-subtitle ellipsis color-c",children:e?e.skins[0].shortcodes:Q.search_no_results_2})]}:{class:"preview-placeholder color-c",children:Q.pick})})]}),!e&&"preview"==this.props.skinTonePosition&&this.renderSkinToneButton()]})}renderEmojiButton(e,{pos:t,posinset:n,grid:o}){const i=this.props.emojiButtonSize,r=this.state.tempSkin||this.state.skin,s=(e.skins[r-1]||e.skins[0]).native,a=(l=this.state.pos,c=t,Array.isArray(l)&&Array.isArray(c)&&l.length===c.length&&l.every((e,t)=>e==c[t]));var l,c;const d=t.concat(e.id).join("");return V(tt,{selected:a,skin:r,size:i,children:V("button",{"aria-label":s,"aria-selected":a||void 0,"aria-posinset":n,"aria-setsize":o.setsize,"data-keyboard":this.state.keyboard,title:"none"==this.props.previewPosition?e.name:void 0,type:"button",class:"flex flex-center flex-middle",tabindex:"-1",onClick:t=>this.handleEmojiClick({e:t,emoji:e}),onMouseEnter:()=>this.handleEmojiOver(t),onMouseLeave:()=>this.handleEmojiOver(),style:{width:this.props.emojiButtonSize,height:this.props.emojiButtonSize,fontSize:this.props.emojiSize,lineHeight:0},children:[V("div",{"aria-hidden":"true",class:"background",style:{borderRadius:this.props.emojiButtonRadius,backgroundColor:this.props.emojiButtonColors?this.props.emojiButtonColors[(n-1)%this.props.emojiButtonColors.length]:void 0}}),V(_e,{emoji:e,set:this.props.set,size:this.props.emojiSize,skin:r,spritesheet:!0,getSpritesheetURL:this.props.getSpritesheetURL})]})},d)}renderSearch(){const e="none"==this.props.previewPosition||"search"==this.props.skinTonePosition;return V("div",{children:[V("div",{class:"spacer"}),V("div",{class:"flex flex-middle",children:[V("div",{class:"search relative flex-grow",children:[V("input",{type:"search",ref:this.refs.searchInput,placeholder:Q.search,onClick:this.handleSearchClick,onInput:this.handleSearchInput,onKeyDown:this.handleSearchKeyDown,autoComplete:"off"}),V("span",{class:"icon loupe flex",children:fe.search.loupe}),this.state.searchResults&&V("button",{title:"Clear","aria-label":"Clear",type:"button",class:"icon delete flex",onClick:this.clearSearch,onMouseDown:this.preventDefault,children:fe.search.delete})]}),e&&this.renderSkinToneButton()]})]})}renderSearchResults(){const{searchResults:e}=this.state;return e?V("div",{class:"category",ref:this.refs.search,children:[V("div",{class:`sticky padding-small align-${this.dir[0]}`,children:Q.categories.search}),V("div",{children:e.length?e.map((t,n)=>V("div",{class:"flex",children:t.map((t,o)=>this.renderEmojiButton(t,{pos:[n,o],posinset:n*this.props.perLine+o+1,grid:e}))})):V("div",{class:`padding-small align-${this.dir[0]}`,children:this.props.onAddCustomEmoji&&V("a",{onClick:this.props.onAddCustomEmoji,children:Q.add_custom})})})]}):null}renderCategories(){const{categories:e}=ee,t=!!this.state.searchResults,n=this.getPerLine();return V("div",{style:{visibility:t?"hidden":void 0,display:t?"none":void 0,height:"100%"},children:e.map(e=>{const{root:t,rows:o}=this.refs.categories.get(e.id);return V("div",{"data-id":e.target?e.target.id:e.id,class:"category",ref:t,children:[V("div",{class:`sticky padding-small align-${this.dir[0]}`,children:e.name||Q.categories[e.id]}),V("div",{class:"relative",style:{height:o.length*this.props.emojiButtonSize},children:o.map((t,o)=>{const i=t.index-t.index%10,r=this.state.visibleRows[i],s="current"in t?t:void 0;if(!r&&!s)return null;const a=o*n,l=a+n,c=e.emojis.slice(a,l);return c.length{if(!e)return V("div",{style:{width:this.props.emojiButtonSize,height:this.props.emojiButtonSize}});const o=de.get(e);return this.renderEmojiButton(o,{pos:[t.index,n],posinset:t.posinset+n,grid:this.grid})})},t.index)})})]})})})}renderSkinToneButton(){return"none"==this.props.skinTonePosition?null:V("div",{class:"flex flex-auto flex-center flex-middle",style:{position:"relative",width:this.props.emojiButtonSize,height:this.props.emojiButtonSize},children:V("button",{type:"button",ref:this.refs.skinToneButton,class:"skin-tone-button flex flex-auto flex-center flex-middle","aria-selected":this.state.showSkins?"":void 0,"aria-label":Q.skins.choose,title:Q.skins.choose,onClick:this.openSkins,style:{width:this.props.emojiSize,height:this.props.emojiSize},children:V("span",{class:`skin-tone skin-tone-${this.state.skin}`})})})}renderLiveRegion(){const e=this.getEmojiByPos(this.state.pos);return V("div",{"aria-live":"polite",class:"sr-only",children:e?e.name:""})}renderSkins(){const e=this.refs.skinToneButton.current.getBoundingClientRect(),t=this.base.getBoundingClientRect(),n={};return"ltr"==this.dir?n.right=t.right-e.right-3:n.left=e.left-t.left-3,"bottom"==this.props.previewPosition&&"preview"==this.props.skinTonePosition?n.bottom=t.bottom-e.top+6:(n.top=e.bottom-t.top+3,n.bottom="auto"),V("div",{ref:this.refs.menu,role:"radiogroup",dir:this.dir,"aria-label":Q.skins.choose,class:"menu hidden","data-position":n.top?"top":"bottom",style:n,children:[...Array(6).keys()].map(e=>{const t=e+1,n=this.state.skin==t;return V("div",{children:[V("input",{type:"radio",name:"skin-tone",value:t,"aria-label":Q.skins[t],ref:n?this.refs.skinToneRadio:null,defaultChecked:n,onChange:()=>this.handleSkinMouseOver(t),onKeyDown:e=>{"Enter"!=e.code&&"Space"!=e.code&&"Tab"!=e.code||(e.preventDefault(),this.handleSkinClick(t))}}),V("button",{"aria-hidden":"true",tabindex:"-1",onClick:()=>this.handleSkinClick(t),onMouseEnter:()=>this.handleSkinMouseOver(t),onMouseLeave:()=>this.handleSkinMouseOver(),class:"option flex flex-grow flex-middle",children:[V("span",{class:`skin-tone skin-tone-${t}`}),V("span",{class:"margin-small-lr",children:Q.skins[t]})]})]})})})}render(){const e=this.props.perLine*this.props.emojiButtonSize;return V("section",{id:"root",class:"flex flex-column",dir:this.dir,style:{width:this.props.dynamicWidth?"100%":`calc(${e}px + (var(--padding) + var(--sidebar-width)))`},"data-emoji-set":this.props.set,"data-theme":this.state.theme,"data-menu":this.state.showSkins?"":void 0,children:["top"==this.props.previewPosition&&this.renderPreview(),"top"==this.props.navPosition&&this.renderNav(),"sticky"==this.props.searchPosition&&V("div",{class:"padding-lr",children:this.renderSearch()}),V("div",{ref:this.refs.scroll,class:"scroll flex-grow padding-lr",children:V("div",{style:{width:this.props.dynamicWidth?"100%":e,height:"100%"},children:["static"==this.props.searchPosition&&this.renderSearch(),this.renderSearchResults(),this.renderCategories()]})}),"bottom"==this.props.navPosition&&this.renderNav(),"bottom"==this.props.previewPosition&&this.renderPreview(),this.state.showSkins&&this.renderSkins(),this.renderLiveRegion()]})}constructor(e){super(),i(this,"darkMediaCallback",()=>{"auto"==this.props.theme&&this.setState({theme:this.darkMedia.matches?"dark":"light"})}),i(this,"handleClickOutside",e=>{const{element:t}=this.props;e.target!=t&&(this.state.showSkins&&this.closeSkins(),this.props.onClickOutside&&this.props.onClickOutside(e))}),i(this,"handleBaseClick",e=>{this.state.showSkins&&(e.target.closest(".menu")||(e.preventDefault(),e.stopImmediatePropagation(),this.closeSkins()))}),i(this,"handleBaseKeydown",e=>{this.state.showSkins&&"Escape"==e.key&&(e.preventDefault(),e.stopImmediatePropagation(),this.closeSkins())}),i(this,"handleSearchClick",()=>{this.getEmojiByPos(this.state.pos)&&this.setState({pos:[-1,-1]})}),i(this,"handleSearchInput",async()=>{const e=this.refs.searchInput.current;if(!e)return;const{value:t}=e,n=await de.search(t),o=()=>{this.refs.scroll.current&&(this.refs.scroll.current.scrollTop=0)};if(!n)return this.setState({searchResults:n,pos:[-1,-1]},o);const i=e.selectionStart==e.value.length?[0,0]:[-1,-1],r=[];r.setsize=n.length;let s=null;for(let e of n)r.length&&s.length!=this.getPerLine()||(s=[],s.__categoryId="search",s.__index=r.length,r.push(s)),s.push(e);this.ignoreMouse(),this.setState({searchResults:r,pos:i},o)}),i(this,"handleSearchKeyDown",e=>{const t=e.currentTarget;switch(e.stopImmediatePropagation(),e.key){case"ArrowLeft":this.navigate({e,input:t,left:!0});break;case"ArrowRight":this.navigate({e,input:t,right:!0});break;case"ArrowUp":this.navigate({e,input:t,up:!0});break;case"ArrowDown":this.navigate({e,input:t,down:!0});break;case"Enter":e.preventDefault(),this.handleEmojiClick({e,pos:this.state.pos});break;case"Escape":e.preventDefault(),this.state.searchResults?this.clearSearch():this.unfocusSearch()}}),i(this,"clearSearch",()=>{const e=this.refs.searchInput.current;e&&(e.value="",e.focus(),this.handleSearchInput())}),i(this,"handleCategoryClick",({category:e,i:t})=>{this.scrollTo(0==t?{row:-1}:{categoryId:e.id})}),i(this,"openSkins",e=>{const{currentTarget:t}=e,n=t.getBoundingClientRect();this.setState({showSkins:n},async()=>{await async function(e=1){for(let t in[...Array(e).keys()])await new Promise(requestAnimationFrame)}(2);const e=this.refs.menu.current;e&&(e.classList.remove("hidden"),this.refs.skinToneRadio.current.focus(),this.base.addEventListener("click",this.handleBaseClick,!0),this.base.addEventListener("keydown",this.handleBaseKeydown,!0))})}),this.observers=[],this.state={pos:[-1,-1],perLine:this.initDynamicPerLine(e),visibleRows:{0:!0},...this.getInitialState(e)}}}class ot extends ve{async connectedCallback(){const e=ae(this.props,Z,this);e.element=this,e.ref=e=>{this.component=e},await se(e),this.disconnected||O(V(nt,{...e}),this.shadowRoot)}constructor(e){super(e,{styles:o(it)})}}i(ot,"Props",Z),"undefined"==typeof customElements||customElements.get("em-emoji-picker")||customElements.define("em-emoji-picker",ot);var it={};it=':host {\n width: min-content;\n height: 435px;\n min-height: 230px;\n border-radius: var(--border-radius);\n box-shadow: var(--shadow);\n --border-radius: 10px;\n --category-icon-size: 18px;\n --font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;\n --font-size: 15px;\n --preview-placeholder-size: 21px;\n --preview-title-size: 1.1em;\n --preview-subtitle-size: .9em;\n --shadow-color: 0deg 0% 0%;\n --shadow: .3px .5px 2.7px hsl(var(--shadow-color) / .14), .4px .8px 1px -3.2px hsl(var(--shadow-color) / .14), 1px 2px 2.5px -4.5px hsl(var(--shadow-color) / .14);\n display: flex;\n}\n\n[data-theme="light"] {\n --em-rgb-color: var(--rgb-color, 34, 36, 39);\n --em-rgb-accent: var(--rgb-accent, 34, 102, 237);\n --em-rgb-background: var(--rgb-background, 255, 255, 255);\n --em-rgb-input: var(--rgb-input, 255, 255, 255);\n --em-color-border: var(--color-border, rgba(0, 0, 0, .05));\n --em-color-border-over: var(--color-border-over, rgba(0, 0, 0, .1));\n}\n\n[data-theme="dark"] {\n --em-rgb-color: var(--rgb-color, 222, 222, 221);\n --em-rgb-accent: var(--rgb-accent, 58, 130, 247);\n --em-rgb-background: var(--rgb-background, 21, 22, 23);\n --em-rgb-input: var(--rgb-input, 0, 0, 0);\n --em-color-border: var(--color-border, rgba(255, 255, 255, .1));\n --em-color-border-over: var(--color-border-over, rgba(255, 255, 255, .2));\n}\n\n#root {\n --color-a: rgb(var(--em-rgb-color));\n --color-b: rgba(var(--em-rgb-color), .65);\n --color-c: rgba(var(--em-rgb-color), .45);\n --padding: 12px;\n --padding-small: calc(var(--padding) / 2);\n --sidebar-width: 16px;\n --duration: 225ms;\n --duration-fast: 125ms;\n --duration-instant: 50ms;\n --easing: cubic-bezier(.4, 0, .2, 1);\n width: 100%;\n text-align: left;\n border-radius: var(--border-radius);\n background-color: rgb(var(--em-rgb-background));\n position: relative;\n}\n\n@media (prefers-reduced-motion) {\n #root {\n --duration: 0;\n --duration-fast: 0;\n --duration-instant: 0;\n }\n}\n\n#root[data-menu] button {\n cursor: auto;\n}\n\n#root[data-menu] .menu button {\n cursor: pointer;\n}\n\n:host, #root, input, button {\n color: rgb(var(--em-rgb-color));\n font-family: var(--font-family);\n font-size: var(--font-size);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n line-height: normal;\n}\n\n*, :before, :after {\n box-sizing: border-box;\n min-width: 0;\n margin: 0;\n padding: 0;\n}\n\n.relative {\n position: relative;\n}\n\n.flex {\n display: flex;\n}\n\n.flex-auto {\n flex: none;\n}\n\n.flex-center {\n justify-content: center;\n}\n\n.flex-column {\n flex-direction: column;\n}\n\n.flex-grow {\n flex: auto;\n}\n\n.flex-middle {\n align-items: center;\n}\n\n.flex-wrap {\n flex-wrap: wrap;\n}\n\n.padding {\n padding: var(--padding);\n}\n\n.padding-t {\n padding-top: var(--padding);\n}\n\n.padding-lr {\n padding-left: var(--padding);\n padding-right: var(--padding);\n}\n\n.padding-r {\n padding-right: var(--padding);\n}\n\n.padding-small {\n padding: var(--padding-small);\n}\n\n.padding-small-b {\n padding-bottom: var(--padding-small);\n}\n\n.padding-small-lr {\n padding-left: var(--padding-small);\n padding-right: var(--padding-small);\n}\n\n.margin {\n margin: var(--padding);\n}\n\n.margin-r {\n margin-right: var(--padding);\n}\n\n.margin-l {\n margin-left: var(--padding);\n}\n\n.margin-small-l {\n margin-left: var(--padding-small);\n}\n\n.margin-small-lr {\n margin-left: var(--padding-small);\n margin-right: var(--padding-small);\n}\n\n.align-l {\n text-align: left;\n}\n\n.align-r {\n text-align: right;\n}\n\n.color-a {\n color: var(--color-a);\n}\n\n.color-b {\n color: var(--color-b);\n}\n\n.color-c {\n color: var(--color-c);\n}\n\n.ellipsis {\n white-space: nowrap;\n max-width: 100%;\n width: auto;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.sr-only {\n width: 1px;\n height: 1px;\n position: absolute;\n top: auto;\n left: -10000px;\n overflow: hidden;\n}\n\na {\n cursor: pointer;\n color: rgb(var(--em-rgb-accent));\n}\n\na:hover {\n text-decoration: underline;\n}\n\n.spacer {\n height: 10px;\n}\n\n[dir="rtl"] .scroll {\n padding-left: 0;\n padding-right: var(--padding);\n}\n\n.scroll {\n padding-right: 0;\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.scroll::-webkit-scrollbar {\n width: var(--sidebar-width);\n height: var(--sidebar-width);\n}\n\n.scroll::-webkit-scrollbar-track {\n border: 0;\n}\n\n.scroll::-webkit-scrollbar-button {\n width: 0;\n height: 0;\n display: none;\n}\n\n.scroll::-webkit-scrollbar-corner {\n background-color: rgba(0, 0, 0, 0);\n}\n\n.scroll::-webkit-scrollbar-thumb {\n min-height: 20%;\n min-height: 65px;\n border: 4px solid rgb(var(--em-rgb-background));\n border-radius: 8px;\n}\n\n.scroll::-webkit-scrollbar-thumb:hover {\n background-color: var(--em-color-border-over) !important;\n}\n\n.scroll:hover::-webkit-scrollbar-thumb {\n background-color: var(--em-color-border);\n}\n\n.sticky {\n z-index: 1;\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n font-weight: 500;\n position: sticky;\n top: -1px;\n}\n\n[dir="rtl"] .search input[type="search"] {\n padding: 10px 2.2em 10px 2em;\n}\n\n[dir="rtl"] .search .loupe {\n left: auto;\n right: .7em;\n}\n\n[dir="rtl"] .search .delete {\n left: .7em;\n right: auto;\n}\n\n.search {\n z-index: 2;\n position: relative;\n}\n\n.search input, .search button {\n font-size: calc(var(--font-size) - 1px);\n}\n\n.search input[type="search"] {\n width: 100%;\n background-color: var(--em-color-border);\n transition-duration: var(--duration);\n transition-property: background-color, box-shadow;\n transition-timing-function: var(--easing);\n border: 0;\n border-radius: 10px;\n outline: 0;\n padding: 10px 2em 10px 2.2em;\n display: block;\n}\n\n.search input[type="search"]::-ms-input-placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"]::placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"], .search input[type="search"]::-webkit-search-decoration, .search input[type="search"]::-webkit-search-cancel-button, .search input[type="search"]::-webkit-search-results-button, .search input[type="search"]::-webkit-search-results-decoration {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n}\n\n.search input[type="search"]:focus {\n background-color: rgb(var(--em-rgb-input));\n box-shadow: inset 0 0 0 1px rgb(var(--em-rgb-accent)), 0 1px 3px rgba(65, 69, 73, .2);\n}\n\n.search .icon {\n z-index: 1;\n color: rgba(var(--em-rgb-color), .7);\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n\n.search .loupe {\n pointer-events: none;\n left: .7em;\n}\n\n.search .delete {\n right: .7em;\n}\n\nsvg {\n fill: currentColor;\n width: 1em;\n height: 1em;\n}\n\nbutton {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n cursor: pointer;\n color: currentColor;\n background-color: rgba(0, 0, 0, 0);\n border: 0;\n}\n\n#nav {\n z-index: 2;\n padding-top: 12px;\n padding-bottom: 12px;\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#nav button {\n color: var(--color-b);\n transition: color var(--duration) var(--easing);\n}\n\n#nav button:hover {\n color: var(--color-a);\n}\n\n#nav svg, #nav img {\n width: var(--category-icon-size);\n height: var(--category-icon-size);\n}\n\n#nav[dir="rtl"] .bar {\n left: auto;\n right: 0;\n}\n\n#nav .bar {\n width: 100%;\n height: 3px;\n background-color: rgb(var(--em-rgb-accent));\n transition: transform var(--duration) var(--easing);\n border-radius: 3px 3px 0 0;\n position: absolute;\n bottom: -12px;\n left: 0;\n}\n\n#nav button[aria-selected] {\n color: rgb(var(--em-rgb-accent));\n}\n\n#preview {\n z-index: 2;\n padding: calc(var(--padding) + 4px) var(--padding);\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#preview .preview-placeholder {\n font-size: var(--preview-placeholder-size);\n}\n\n#preview .preview-title {\n font-size: var(--preview-title-size);\n}\n\n#preview .preview-subtitle {\n font-size: var(--preview-subtitle-size);\n}\n\n#nav:before, #preview:before {\n content: "";\n height: 2px;\n position: absolute;\n left: 0;\n right: 0;\n}\n\n#nav[data-position="top"]:before, #preview[data-position="top"]:before {\n background: linear-gradient(to bottom, var(--em-color-border), transparent);\n top: 100%;\n}\n\n#nav[data-position="bottom"]:before, #preview[data-position="bottom"]:before {\n background: linear-gradient(to top, var(--em-color-border), transparent);\n bottom: 100%;\n}\n\n.category:last-child {\n min-height: calc(100% + 1px);\n}\n\n.category button {\n font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, sans-serif;\n position: relative;\n}\n\n.category button > * {\n position: relative;\n}\n\n.category button .background {\n opacity: 0;\n background-color: var(--em-color-border);\n transition: opacity var(--duration-fast) var(--easing) var(--duration-instant);\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n}\n\n.category button:hover .background {\n transition-duration: var(--duration-instant);\n transition-delay: 0s;\n}\n\n.category button[aria-selected] .background {\n opacity: 1;\n}\n\n.category button[data-keyboard] .background {\n transition: none;\n}\n\n.row {\n width: 100%;\n position: absolute;\n top: 0;\n left: 0;\n}\n\n.skin-tone-button {\n border: 1px solid rgba(0, 0, 0, 0);\n border-radius: 100%;\n}\n\n.skin-tone-button:hover {\n border-color: var(--em-color-border);\n}\n\n.skin-tone-button:active .skin-tone {\n transform: scale(.85) !important;\n}\n\n.skin-tone-button .skin-tone {\n transition: transform var(--duration) var(--easing);\n}\n\n.skin-tone-button[aria-selected] {\n background-color: var(--em-color-border);\n border-top-color: rgba(0, 0, 0, .05);\n border-bottom-color: rgba(0, 0, 0, 0);\n border-left-width: 0;\n border-right-width: 0;\n}\n\n.skin-tone-button[aria-selected] .skin-tone {\n transform: scale(.9);\n}\n\n.menu {\n z-index: 2;\n white-space: nowrap;\n border: 1px solid var(--em-color-border);\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n transition-property: opacity, transform;\n transition-duration: var(--duration);\n transition-timing-function: var(--easing);\n border-radius: 10px;\n padding: 4px;\n position: absolute;\n box-shadow: 1px 1px 5px rgba(0, 0, 0, .05);\n}\n\n.menu.hidden {\n opacity: 0;\n}\n\n.menu[data-position="bottom"] {\n transform-origin: 100% 100%;\n}\n\n.menu[data-position="bottom"].hidden {\n transform: scale(.9)rotate(-3deg)translateY(5%);\n}\n\n.menu[data-position="top"] {\n transform-origin: 100% 0;\n}\n\n.menu[data-position="top"].hidden {\n transform: scale(.9)rotate(3deg)translateY(-5%);\n}\n\n.menu input[type="radio"] {\n clip: rect(0 0 0 0);\n width: 1px;\n height: 1px;\n border: 0;\n margin: 0;\n padding: 0;\n position: absolute;\n overflow: hidden;\n}\n\n.menu input[type="radio"]:checked + .option {\n box-shadow: 0 0 0 2px rgb(var(--em-rgb-accent));\n}\n\n.option {\n width: 100%;\n border-radius: 6px;\n padding: 4px 6px;\n}\n\n.option:hover {\n color: #fff;\n background-color: rgb(var(--em-rgb-accent));\n}\n\n.skin-tone {\n width: 16px;\n height: 16px;\n border-radius: 100%;\n display: inline-block;\n position: relative;\n overflow: hidden;\n}\n\n.skin-tone:after {\n content: "";\n mix-blend-mode: overlay;\n background: linear-gradient(rgba(255, 255, 255, .2), rgba(0, 0, 0, 0));\n border: 1px solid rgba(0, 0, 0, .8);\n border-radius: 100%;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 2px #fff;\n}\n\n.skin-tone-1 {\n background-color: #ffc93a;\n}\n\n.skin-tone-2 {\n background-color: #ffdab7;\n}\n\n.skin-tone-3 {\n background-color: #e7b98f;\n}\n\n.skin-tone-4 {\n background-color: #c88c61;\n}\n\n.skin-tone-5 {\n background-color: #a46134;\n}\n\n.skin-tone-6 {\n background-color: #5d4437;\n}\n\n[data-index] {\n justify-content: space-between;\n}\n\n[data-emoji-set="twitter"] .skin-tone:after {\n box-shadow: none;\n border-color: rgba(0, 0, 0, .5);\n}\n\n[data-emoji-set="twitter"] .skin-tone-1 {\n background-color: #fade72;\n}\n\n[data-emoji-set="twitter"] .skin-tone-2 {\n background-color: #f3dfd0;\n}\n\n[data-emoji-set="twitter"] .skin-tone-3 {\n background-color: #eed3a8;\n}\n\n[data-emoji-set="twitter"] .skin-tone-4 {\n background-color: #cfad8d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-5 {\n background-color: #a8805d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-6 {\n background-color: #765542;\n}\n\n[data-emoji-set="google"] .skin-tone:after {\n box-shadow: inset 0 0 2px 2px rgba(0, 0, 0, .4);\n}\n\n[data-emoji-set="google"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="google"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="google"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="google"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="google"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="google"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n[data-emoji-set="facebook"] .skin-tone:after {\n border-color: rgba(0, 0, 0, .4);\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 4px #fff;\n}\n\n[data-emoji-set="facebook"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="facebook"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="facebook"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="facebook"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="facebook"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="facebook"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n',n.d(t,["SafeFlags",0,he])}}]); \ No newline at end of file +"use strict";(Object("undefined"!=typeof self?self:this).webpackChunkHellotext=Object("undefined"!=typeof self?self:this).webpackChunkHellotext||[]).push([[160],{6(e,t,n){function o(e){return e&&e.__esModule?e.default:e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}n.r(t),n.d(t,{Data:()=>ee,Emoji:()=>ke,FrequentlyUsed:()=>Y,I18n:()=>Q,Picker:()=>ot,SearchIndex:()=>de,Store:()=>$,getEmojiDataFromNative:()=>pe,init:()=>se});var r,s,a,l,c,d,h={},u=[],p=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function f(e,t){for(var n in t)e[n]=t[n];return e}function _(e){var t=e.parentNode;t&&t.removeChild(e)}function g(e,t,n){var o,i,s,a={};for(s in t)"key"==s?o=t[s]:"ref"==s?i=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?r.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return m(e,a,o,i,null)}function m(e,t,n,o,i){var r={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:i??++a};return null==i&&null!=s.vnode&&s.vnode(r),r}function v(){return{current:null}}function b(e){return e.children}function k(e,t){this.props=e,this.context=t}function w(e,t){if(null==t)return e.__?w(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t0?m(_.type,_.props,_.key,null,_.__v):_)){if(_.__=n,_.__b=n.__b+1,null===(f=y[d])||f&&_.key==f.key&&_.type===f.type)y[d]=void 0;else for(p=0;p{let e=null;try{navigator.userAgent.includes("jsdom")||(e=document.createElement("canvas").getContext("2d",{willReadFrequently:!0}))}catch{}if(!e)return()=>!1;const t=20,n=Math.floor(12.5);return e.font=n+"px Arial, Sans-Serif",e.textBaseline="top",e.canvas.width=40,e.canvas.height=25,n=>{e.clearRect(0,0,40,25),e.fillStyle="#FF0000",e.fillText(n,0,22),e.fillStyle="#0000FF",e.fillText(n,t,22);const o=e.getImageData(0,0,t,25).data,i=o.length;let r=0;for(;r=i)return!1;const s=t+r/4%t,a=Math.floor(r/4/t),l=e.getImageData(s,a,1,1).data;return o[r]===l[0]&&o[r+2]===l[2]&&!(e.measureText(n).width>=t)}})();var W=function(){for(const{v:e,emoji:t}of U)if(N(t))return e},K=function(){return!N("🇨🇦")};const G=["+1","grinning","kissing_heart","heart_eyes","laughing","stuck_out_tongue_winking_eye","sweat_smile","joy","scream","disappointed","unamused","weary","sob","sunglasses","heart"];let X=null;var J,Y={add:function(e){X||(X=$.get("frequently")||{});const t=e.id||e;t&&(X[t]||(X[t]=0),X[t]+=1,$.set("last",t),$.set("frequently",X))},get:function({maxFrequentRows:e,perLine:t}){if(!e)return[];X||(X=$.get("frequently"));let n=[];if(!X){X={};for(let e in G.slice(0,t)){const o=G[e];X[o]=t-e,n.push(o)}return n}const o=e*t,i=$.get("last");for(let e in X)n.push(e);if(n.sort((e,t)=>{const n=X[t],o=X[e];return n==o?e.localeCompare(t):n-o}),n.length>o){const e=n.slice(o);n=n.slice(0,o);for(let t of e)t!=i&&delete X[t];i&&-1==n.indexOf(i)&&(delete X[n[n.length-1]],n.splice(-1,1,i)),$.set("frequently",X)}return n},DEFAULTS:G};J=JSON.parse('{"search":"Search","search_no_results_1":"Oh no!","search_no_results_2":"That emoji couldn’t be found","pick":"Pick an emoji…","add_custom":"Add custom emoji","categories":{"activity":"Activity","custom":"Custom","flags":"Flags","foods":"Food & Drink","frequent":"Frequently used","nature":"Animals & Nature","objects":"Objects","people":"Smileys & People","places":"Travel & Places","search":"Search Results","symbols":"Symbols"},"skins":{"1":"Default","2":"Light","3":"Medium-Light","4":"Medium","5":"Medium-Dark","6":"Dark","choose":"Choose default skin tone"}}');var Z={autoFocus:{value:!1},dynamicWidth:{value:!1},emojiButtonColors:{value:null},emojiButtonRadius:{value:"100%"},emojiButtonSize:{value:36},emojiSize:{value:24},emojiVersion:{value:15,choices:[1,2,3,4,5,11,12,12.1,13,13.1,14,15]},exceptEmojis:{value:[]},icons:{value:"auto",choices:["auto","outline","solid"]},locale:{value:"en",choices:["en","ar","be","cs","de","es","fa","fi","fr","hi","it","ja","ko","nl","pl","pt","ru","sa","tr","uk","vi","zh"]},maxFrequentRows:{value:4},navPosition:{value:"top",choices:["top","bottom","none"]},noCountryFlags:{value:!1},noResultsEmoji:{value:null},perLine:{value:9},previewEmoji:{value:null},previewPosition:{value:"bottom",choices:["top","bottom","none"]},searchPosition:{value:"sticky",choices:["sticky","static","none"]},set:{value:"native",choices:["native","apple","facebook","google","twitter"]},skin:{value:1,choices:[1,2,3,4,5,6]},skinTonePosition:{value:"preview",choices:["preview","search","none"]},theme:{value:"auto",choices:["auto","light","dark"]},categories:null,categoryIcons:null,custom:null,data:null,i18n:null,getImageURL:null,getSpritesheetURL:null,onAddCustomEmoji:null,onClickOutside:null,onEmojiSelect:null,stickySearch:{deprecated:!0,value:!0}};let Q=null,ee=null;const te={};async function ne(e){if(te[e])return te[e];const t=await fetch(e),n=await t.json();return te[e]=n,n}let oe=null,ie=null,re=!1;function se(e,{caller:t}={}){return oe||(oe=new Promise(e=>{ie=e})),e?async function(e){re=!0;let{emojiVersion:t,set:n,locale:i}=e;if(t||(t=Z.emojiVersion.value),n||(n=Z.set.value),i||(i=Z.locale.value),ee)ee.categories=ee.categories.filter(e=>!e.name);else{ee=("function"==typeof e.data?await e.data():e.data)||await ne(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/sets/${t}/${n}.json`),ee.emoticons={},ee.natives={},ee.categories.unshift({id:"frequent",emojis:[]});for(const e in ee.aliases){const t=ee.aliases[e],n=ee.emojis[t];n&&(n.aliases||(n.aliases=[]),n.aliases.push(e))}ee.originalCategories=ee.categories}if(Q=("function"==typeof e.i18n?await e.i18n():e.i18n)||("en"==i?o(J):await ne(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/i18n/${i}.json`)),e.custom)for(let t in e.custom){t=parseInt(t);const n=e.custom[t],o=e.custom[t-1];if(n.emojis&&n.emojis.length){n.id||(n.id=`custom_${t+1}`),n.name||(n.name=Q.categories.custom),o&&!n.icon&&(n.target=o.target||o),ee.categories.push(n);for(const e of n.emojis)ee.emojis[e.id]=e}}e.categories&&(ee.categories=ee.originalCategories.filter(t=>-1!=e.categories.indexOf(t.id)).sort((t,n)=>e.categories.indexOf(t.id)-e.categories.indexOf(n.id)));let r=null,s=null;"native"==n&&(r=W(),s=e.noCountryFlags||K());let a=ee.categories.length,l=!1;for(;a--;){const t=ee.categories[a];if("frequent"==t.id){let{maxFrequentRows:n,perLine:o}=e;n=n>=0?n:Z.maxFrequentRows.value,o||(o=Z.perLine.value),t.emojis=Y.get({maxFrequentRows:n,perLine:o})}if(!t.emojis||!t.emojis.length){ee.categories.splice(a,1);continue}const{categoryIcons:n}=e;if(n){const e=n[t.id];e&&!t.icon&&(t.icon=e)}let o=t.emojis.length;for(;o--;){const n=t.emojis[o],i=n.id?n:ee.emojis[n],a=()=>{t.emojis.splice(o,1)};if(!i||e.exceptEmojis&&e.exceptEmojis.includes(i.id))a();else if(r&&i.version>r)a();else if(!s||"flags"!=t.id||he.includes(i.id)){if(!i.search){if(l=!0,i.search=","+[[i.id,!1],[i.name,!0],[i.keywords,!1],[i.emoticons,!1]].map(([e,t])=>{if(e)return(Array.isArray(e)?e:[e]).map(e=>(t?e.split(/[-|_|\s]+/):[e]).map(e=>e.toLowerCase())).flat()}).flat().filter(e=>e&&e.trim()).join(","),i.emoticons)for(const e of i.emoticons)ee.emoticons[e]||(ee.emoticons[e]=i.id);let e=0;for(const t of i.skins){if(!t)continue;e++;const{native:n}=t;n&&(ee.natives[n]=i.id,i.search+=`,${n}`);const o=1==e?"":`:skin-tone-${e}:`;t.shortcodes=`:${i.id}:${o}`}}}else a()}}l&&de.reset(),ie()}(e):t&&!re&&console.warn(`\`${t}\` requires data to be initialized first. Promise will be pending until \`init\` is called.`),oe}function ae(e,t,n){e||(e={});const o={};for(let i in t)o[i]=le(i,e,t,n);return o}function le(e,t,n,o){const i=n[e];let r=o&&o.getAttribute(e)||(null!=t[e]&&null!=t[e]?t[e]:null);return i?(null!=r&&i.value&&typeof i.value!=typeof r&&(r="boolean"==typeof i.value?"false"!=r:i.value.constructor(r)),i.transform&&r&&(r=i.transform(r)),(null==r||i.choices&&-1==i.choices.indexOf(r))&&(r=i.value),r):r}let ce=null;var de={search:async function(e,{maxResults:t,caller:n}={}){if(!e||!e.trim().length)return null;t||(t=90),await se(null,{caller:n||"SearchIndex.search"});const o=e.toLowerCase().replace(/(\w)-/,"$1 ").split(/[\s|,]+/).filter((e,t,n)=>e.trim()&&n.indexOf(e)==t);if(!o.length)return;let i,r,s=ce||(ce=Object.values(ee.emojis));for(const e of o){if(!s.length)break;i=[],r={};for(const t of s){if(!t.search)continue;const n=t.search.indexOf(`,${e}`);-1!=n&&(i.push(t),r[t.id]||(r[t.id]=0),r[t.id]+=t.id==e?0:n+1)}s=i}return i.length<2||(i.sort((e,t)=>{const n=r[e.id],o=r[t.id];return n==o?e.id.localeCompare(t.id):n-o}),i.length>t&&(i=i.slice(0,t))),i},get:function(e){return e.id?e:ee.emojis[e]||ee.emojis[ee.aliases[e]]||ee.emojis[ee.natives[e]]},reset:function(){ce=null},SHORTCODES_REGEX:/^(?:\:([^\:]+)\:)(?:\:skin-tone-(\d)\:)?$/};const he=["checkered_flag","crossed_flags","pirate_flag","rainbow-flag","transgender_flag","triangular_flag_on_post","waving_black_flag","waving_white_flag"];function ue(e,{skinIndex:t=0}={}){const n=e.skins[t]||(t=0,e.skins[t]),o={id:e.id,name:e.name,native:n.native,unified:n.unified,keywords:e.keywords,shortcodes:n.shortcodes||e.shortcodes};return e.skins.length>1&&(o.skin=t+1),n.src&&(o.src=n.src),e.aliases&&e.aliases.length&&(o.aliases=e.aliases),e.emoticons&&e.emoticons.length&&(o.emoticons=e.emoticons),o}async function pe(e){const t=await de.search(e,{maxResults:1,caller:"getEmojiDataFromNative"});if(!t||!t.length)return null;const n=t[0];let o=0;for(let t of n.skins){if(t.native==e)break;o++}return ue(n,{skinIndex:o})}var fe={categories:{activity:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M12 0C5.373 0 0 5.372 0 12c0 6.627 5.373 12 12 12 6.628 0 12-5.373 12-12 0-6.628-5.372-12-12-12m9.949 11H17.05c.224-2.527 1.232-4.773 1.968-6.113A9.966 9.966 0 0 1 21.949 11M13 11V2.051a9.945 9.945 0 0 1 4.432 1.564c-.858 1.491-2.156 4.22-2.392 7.385H13zm-2 0H8.961c-.238-3.165-1.536-5.894-2.393-7.385A9.95 9.95 0 0 1 11 2.051V11zm0 2v8.949a9.937 9.937 0 0 1-4.432-1.564c.857-1.492 2.155-4.221 2.393-7.385H11zm4.04 0c.236 3.164 1.534 5.893 2.392 7.385A9.92 9.92 0 0 1 13 21.949V13h2.04zM4.982 4.887C5.718 6.227 6.726 8.473 6.951 11h-4.9a9.977 9.977 0 0 1 2.931-6.113M2.051 13h4.9c-.226 2.527-1.233 4.771-1.969 6.113A9.972 9.972 0 0 1 2.051 13m16.967 6.113c-.735-1.342-1.744-3.586-1.968-6.113h4.899a9.961 9.961 0 0 1-2.931 6.113"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M16.17 337.5c0 44.98 7.565 83.54 13.98 107.9C35.22 464.3 50.46 496 174.9 496c9.566 0 19.59-.4707 29.84-1.271L17.33 307.3C16.53 317.6 16.17 327.7 16.17 337.5zM495.8 174.5c0-44.98-7.565-83.53-13.98-107.9c-4.688-17.54-18.34-31.23-36.04-35.95C435.5 27.91 392.9 16 337 16c-9.564 0-19.59 .4707-29.84 1.271l187.5 187.5C495.5 194.4 495.8 184.3 495.8 174.5zM26.77 248.8l236.3 236.3c142-36.1 203.9-150.4 222.2-221.1L248.9 26.87C106.9 62.96 45.07 177.2 26.77 248.8zM256 335.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L164.7 283.3C161.6 280.2 160 276.1 160 271.1c0-8.529 6.865-16 16-16c4.095 0 8.189 1.562 11.31 4.688l64.01 64C254.4 327.8 256 331.9 256 335.1zM304 287.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L212.7 235.3C209.6 232.2 208 228.1 208 223.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01C302.5 279.8 304 283.9 304 287.1zM256 175.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01c3.125 3.125 4.688 7.219 4.688 11.31c0 9.133-7.468 16-16 16c-4.094 0-8.189-1.562-11.31-4.688l-64.01-64.01C257.6 184.2 256 180.1 256 175.1z"})})},custom:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",children:V("path",{d:"M417.1 368c-5.937 10.27-16.69 16-27.75 16c-5.422 0-10.92-1.375-15.97-4.281L256 311.4V448c0 17.67-14.33 32-31.1 32S192 465.7 192 448V311.4l-118.3 68.29C68.67 382.6 63.17 384 57.75 384c-11.06 0-21.81-5.734-27.75-16c-8.828-15.31-3.594-34.88 11.72-43.72L159.1 256L41.72 187.7C26.41 178.9 21.17 159.3 29.1 144C36.63 132.5 49.26 126.7 61.65 128.2C65.78 128.7 69.88 130.1 73.72 132.3L192 200.6V64c0-17.67 14.33-32 32-32S256 46.33 256 64v136.6l118.3-68.29c3.838-2.213 7.939-3.539 12.07-4.051C398.7 126.7 411.4 132.5 417.1 144c8.828 15.31 3.594 34.88-11.72 43.72L288 256l118.3 68.28C421.6 333.1 426.8 352.7 417.1 368z"})}),flags:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M0 0l6.084 24H8L1.916 0zM21 5h-4l-1-4H4l3 12h3l1 4h13L21 5zM6.563 3h7.875l2 8H8.563l-2-8zm8.832 10l-2.856 1.904L12.063 13h3.332zM19 13l-1.5-6h1.938l2 8H16l3-2z"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M64 496C64 504.8 56.75 512 48 512h-32C7.25 512 0 504.8 0 496V32c0-17.75 14.25-32 32-32s32 14.25 32 32V496zM476.3 0c-6.365 0-13.01 1.35-19.34 4.233c-45.69 20.86-79.56 27.94-107.8 27.94c-59.96 0-94.81-31.86-163.9-31.87C160.9 .3055 131.6 4.867 96 15.75v350.5c32-9.984 59.87-14.1 84.85-14.1c73.63 0 124.9 31.78 198.6 31.78c31.91 0 68.02-5.971 111.1-23.09C504.1 355.9 512 344.4 512 332.1V30.73C512 11.1 495.3 0 476.3 0z"})})},foods:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M17 4.978c-1.838 0-2.876.396-3.68.934.513-1.172 1.768-2.934 4.68-2.934a1 1 0 0 0 0-2c-2.921 0-4.629 1.365-5.547 2.512-.064.078-.119.162-.18.244C11.73 1.838 10.798.023 9.207.023 8.579.022 7.85.306 7 .978 5.027 2.54 5.329 3.902 6.492 4.999 3.609 5.222 0 7.352 0 12.969c0 4.582 4.961 11.009 9 11.009 1.975 0 2.371-.486 3-1 .629.514 1.025 1 3 1 4.039 0 9-6.418 9-11 0-5.953-4.055-8-7-8M8.242 2.546c.641-.508.943-.523.965-.523.426.169.975 1.405 1.357 3.055-1.527-.629-2.741-1.352-2.98-1.846.059-.112.241-.356.658-.686M15 21.978c-1.08 0-1.21-.109-1.559-.402l-.176-.146c-.367-.302-.816-.452-1.266-.452s-.898.15-1.266.452l-.176.146c-.347.292-.477.402-1.557.402-2.813 0-7-5.389-7-9.009 0-5.823 4.488-5.991 5-5.991 1.939 0 2.484.471 3.387 1.251l.323.276a1.995 1.995 0 0 0 2.58 0l.323-.276c.902-.78 1.447-1.251 3.387-1.251.512 0 5 .168 5 6 0 3.617-4.187 9-7 9"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M481.9 270.1C490.9 279.1 496 291.3 496 304C496 316.7 490.9 328.9 481.9 337.9C472.9 346.9 460.7 352 448 352H64C51.27 352 39.06 346.9 30.06 337.9C21.06 328.9 16 316.7 16 304C16 291.3 21.06 279.1 30.06 270.1C39.06 261.1 51.27 256 64 256H448C460.7 256 472.9 261.1 481.9 270.1zM475.3 388.7C478.3 391.7 480 395.8 480 400V416C480 432.1 473.3 449.3 461.3 461.3C449.3 473.3 432.1 480 416 480H96C79.03 480 62.75 473.3 50.75 461.3C38.74 449.3 32 432.1 32 416V400C32 395.8 33.69 391.7 36.69 388.7C39.69 385.7 43.76 384 48 384H464C468.2 384 472.3 385.7 475.3 388.7zM50.39 220.8C45.93 218.6 42.03 215.5 38.97 211.6C35.91 207.7 33.79 203.2 32.75 198.4C31.71 193.5 31.8 188.5 32.99 183.7C54.98 97.02 146.5 32 256 32C365.5 32 457 97.02 479 183.7C480.2 188.5 480.3 193.5 479.2 198.4C478.2 203.2 476.1 207.7 473 211.6C469.1 215.5 466.1 218.6 461.6 220.8C457.2 222.9 452.3 224 447.3 224H64.67C59.73 224 54.84 222.9 50.39 220.8zM372.7 116.7C369.7 119.7 368 123.8 368 128C368 131.2 368.9 134.3 370.7 136.9C372.5 139.5 374.1 141.6 377.9 142.8C380.8 143.1 384 144.3 387.1 143.7C390.2 143.1 393.1 141.6 395.3 139.3C397.6 137.1 399.1 134.2 399.7 131.1C400.3 128 399.1 124.8 398.8 121.9C397.6 118.1 395.5 116.5 392.9 114.7C390.3 112.9 387.2 111.1 384 111.1C379.8 111.1 375.7 113.7 372.7 116.7V116.7zM244.7 84.69C241.7 87.69 240 91.76 240 96C240 99.16 240.9 102.3 242.7 104.9C244.5 107.5 246.1 109.6 249.9 110.8C252.8 111.1 256 112.3 259.1 111.7C262.2 111.1 265.1 109.6 267.3 107.3C269.6 105.1 271.1 102.2 271.7 99.12C272.3 96.02 271.1 92.8 270.8 89.88C269.6 86.95 267.5 84.45 264.9 82.7C262.3 80.94 259.2 79.1 256 79.1C251.8 79.1 247.7 81.69 244.7 84.69V84.69zM116.7 116.7C113.7 119.7 112 123.8 112 128C112 131.2 112.9 134.3 114.7 136.9C116.5 139.5 118.1 141.6 121.9 142.8C124.8 143.1 128 144.3 131.1 143.7C134.2 143.1 137.1 141.6 139.3 139.3C141.6 137.1 143.1 134.2 143.7 131.1C144.3 128 143.1 124.8 142.8 121.9C141.6 118.1 139.5 116.5 136.9 114.7C134.3 112.9 131.2 111.1 128 111.1C123.8 111.1 119.7 113.7 116.7 116.7L116.7 116.7z"})})},frequent:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M13 4h-2l-.001 7H9v2h2v2h2v-2h4v-2h-4z"}),V("path",{d:"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512zM232 256C232 264 236 271.5 242.7 275.1L338.7 339.1C349.7 347.3 364.6 344.3 371.1 333.3C379.3 322.3 376.3 307.4 365.3 300L280 243.2V120C280 106.7 269.3 96 255.1 96C242.7 96 231.1 106.7 231.1 120L232 256z"})})},nature:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M15.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 15.5 8M8.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 8.5 8"}),V("path",{d:"M18.933 0h-.027c-.97 0-2.138.787-3.018 1.497-1.274-.374-2.612-.51-3.887-.51-1.285 0-2.616.133-3.874.517C7.245.79 6.069 0 5.093 0h-.027C3.352 0 .07 2.67.002 7.026c-.039 2.479.276 4.238 1.04 5.013.254.258.882.677 1.295.882.191 3.177.922 5.238 2.536 6.38.897.637 2.187.949 3.2 1.102C8.04 20.6 8 20.795 8 21c0 1.773 2.35 3 4 3 1.648 0 4-1.227 4-3 0-.201-.038-.393-.072-.586 2.573-.385 5.435-1.877 5.925-7.587.396-.22.887-.568 1.104-.788.763-.774 1.079-2.534 1.04-5.013C23.929 2.67 20.646 0 18.933 0M3.223 9.135c-.237.281-.837 1.155-.884 1.238-.15-.41-.368-1.349-.337-3.291.051-3.281 2.478-4.972 3.091-5.031.256.015.731.27 1.265.646-1.11 1.171-2.275 2.915-2.352 5.125-.133.546-.398.858-.783 1.313M12 22c-.901 0-1.954-.693-2-1 0-.654.475-1.236 1-1.602V20a1 1 0 1 0 2 0v-.602c.524.365 1 .947 1 1.602-.046.307-1.099 1-2 1m3-3.48v.02a4.752 4.752 0 0 0-1.262-1.02c1.092-.516 2.239-1.334 2.239-2.217 0-1.842-1.781-2.195-3.977-2.195-2.196 0-3.978.354-3.978 2.195 0 .883 1.148 1.701 2.238 2.217A4.8 4.8 0 0 0 9 18.539v-.025c-1-.076-2.182-.281-2.973-.842-1.301-.92-1.838-3.045-1.853-6.478l.023-.041c.496-.826 1.49-1.45 1.804-3.102 0-2.047 1.357-3.631 2.362-4.522C9.37 3.178 10.555 3 11.948 3c1.447 0 2.685.192 3.733.57 1 .9 2.316 2.465 2.316 4.48.313 1.651 1.307 2.275 1.803 3.102.035.058.068.117.102.178-.059 5.967-1.949 7.01-4.902 7.19m6.628-8.202c-.037-.065-.074-.13-.113-.195a7.587 7.587 0 0 0-.739-.987c-.385-.455-.648-.768-.782-1.313-.076-2.209-1.241-3.954-2.353-5.124.531-.376 1.004-.63 1.261-.647.636.071 3.044 1.764 3.096 5.031.027 1.81-.347 3.218-.37 3.235"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 576 512",children:V("path",{d:"M332.7 19.85C334.6 8.395 344.5 0 356.1 0C363.6 0 370.6 3.52 375.1 9.502L392 32H444.1C456.8 32 469.1 37.06 478.1 46.06L496 64H552C565.3 64 576 74.75 576 88V112C576 156.2 540.2 192 496 192H426.7L421.6 222.5L309.6 158.5L332.7 19.85zM448 64C439.2 64 432 71.16 432 80C432 88.84 439.2 96 448 96C456.8 96 464 88.84 464 80C464 71.16 456.8 64 448 64zM416 256.1V480C416 497.7 401.7 512 384 512H352C334.3 512 320 497.7 320 480V364.8C295.1 377.1 268.8 384 240 384C211.2 384 184 377.1 160 364.8V480C160 497.7 145.7 512 128 512H96C78.33 512 64 497.7 64 480V249.8C35.23 238.9 12.64 214.5 4.836 183.3L.9558 167.8C-3.331 150.6 7.094 133.2 24.24 128.1C41.38 124.7 58.76 135.1 63.05 152.2L66.93 167.8C70.49 182 83.29 191.1 97.97 191.1H303.8L416 256.1z"})})},objects:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M12 0a9 9 0 0 0-5 16.482V21s2.035 3 5 3 5-3 5-3v-4.518A9 9 0 0 0 12 0zm0 2c3.86 0 7 3.141 7 7s-3.14 7-7 7-7-3.141-7-7 3.14-7 7-7zM9 17.477c.94.332 1.946.523 3 .523s2.06-.19 3-.523v.834c-.91.436-1.925.689-3 .689a6.924 6.924 0 0 1-3-.69v-.833zm.236 3.07A8.854 8.854 0 0 0 12 21c.965 0 1.888-.167 2.758-.451C14.155 21.173 13.153 22 12 22c-1.102 0-2.117-.789-2.764-1.453z"}),V("path",{d:"M14.745 12.449h-.004c-.852-.024-1.188-.858-1.577-1.824-.421-1.061-.703-1.561-1.182-1.566h-.009c-.481 0-.783.497-1.235 1.537-.436.982-.801 1.811-1.636 1.791l-.276-.043c-.565-.171-.853-.691-1.284-1.794-.125-.313-.202-.632-.27-.913-.051-.213-.127-.53-.195-.634C7.067 9.004 7.039 9 6.99 9A1 1 0 0 1 7 7h.01c1.662.017 2.015 1.373 2.198 2.134.486-.981 1.304-2.058 2.797-2.075 1.531.018 2.28 1.153 2.731 2.141l.002-.008C14.944 8.424 15.327 7 16.979 7h.032A1 1 0 1 1 17 9h-.011c-.149.076-.256.474-.319.709a6.484 6.484 0 0 1-.311.951c-.429.973-.79 1.789-1.614 1.789"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",children:V("path",{d:"M112.1 454.3c0 6.297 1.816 12.44 5.284 17.69l17.14 25.69c5.25 7.875 17.17 14.28 26.64 14.28h61.67c9.438 0 21.36-6.401 26.61-14.28l17.08-25.68c2.938-4.438 5.348-12.37 5.348-17.7L272 415.1h-160L112.1 454.3zM191.4 .0132C89.44 .3257 16 82.97 16 175.1c0 44.38 16.44 84.84 43.56 115.8c16.53 18.84 42.34 58.23 52.22 91.45c.0313 .25 .0938 .5166 .125 .7823h160.2c.0313-.2656 .0938-.5166 .125-.7823c9.875-33.22 35.69-72.61 52.22-91.45C351.6 260.8 368 220.4 368 175.1C368 78.61 288.9-.2837 191.4 .0132zM192 96.01c-44.13 0-80 35.89-80 79.1C112 184.8 104.8 192 96 192S80 184.8 80 176c0-61.76 50.25-111.1 112-111.1c8.844 0 16 7.159 16 16S200.8 96.01 192 96.01z"})})},people:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10"}),V("path",{d:"M8 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 8 7M16 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 16 7M15.232 15c-.693 1.195-1.87 2-3.349 2-1.477 0-2.655-.805-3.347-2H15m3-2H6a6 6 0 1 0 12 0"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256zM256 432C332.1 432 396.2 382 415.2 314.1C419.1 300.4 407.8 288 393.6 288H118.4C104.2 288 92.92 300.4 96.76 314.1C115.8 382 179.9 432 256 432V432zM176.4 160C158.7 160 144.4 174.3 144.4 192C144.4 209.7 158.7 224 176.4 224C194 224 208.4 209.7 208.4 192C208.4 174.3 194 160 176.4 160zM336.4 224C354 224 368.4 209.7 368.4 192C368.4 174.3 354 160 336.4 160C318.7 160 304.4 174.3 304.4 192C304.4 209.7 318.7 224 336.4 224z"})})},places:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[V("path",{d:"M6.5 12C5.122 12 4 13.121 4 14.5S5.122 17 6.5 17 9 15.879 9 14.5 7.878 12 6.5 12m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5M17.5 12c-1.378 0-2.5 1.121-2.5 2.5s1.122 2.5 2.5 2.5 2.5-1.121 2.5-2.5-1.122-2.5-2.5-2.5m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5"}),V("path",{d:"M22.482 9.494l-1.039-.346L21.4 9h.6c.552 0 1-.439 1-.992 0-.006-.003-.008-.003-.008H23c0-1-.889-2-1.984-2h-.642l-.731-1.717C19.262 3.012 18.091 2 16.764 2H7.236C5.909 2 4.738 3.012 4.357 4.283L3.626 6h-.642C1.889 6 1 7 1 8h.003S1 8.002 1 8.008C1 8.561 1.448 9 2 9h.6l-.043.148-1.039.346a2.001 2.001 0 0 0-1.359 2.097l.751 7.508a1 1 0 0 0 .994.901H3v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h6v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h1.096a.999.999 0 0 0 .994-.901l.751-7.508a2.001 2.001 0 0 0-1.359-2.097M6.273 4.857C6.402 4.43 6.788 4 7.236 4h9.527c.448 0 .834.43.963.857L19.313 9H4.688l1.585-4.143zM7 21H5v-1h2v1zm12 0h-2v-1h2v1zm2.189-3H2.811l-.662-6.607L3 11h18l.852.393L21.189 18z"})]}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M39.61 196.8L74.8 96.29C88.27 57.78 124.6 32 165.4 32H346.6C387.4 32 423.7 57.78 437.2 96.29L472.4 196.8C495.6 206.4 512 229.3 512 256V448C512 465.7 497.7 480 480 480H448C430.3 480 416 465.7 416 448V400H96V448C96 465.7 81.67 480 64 480H32C14.33 480 0 465.7 0 448V256C0 229.3 16.36 206.4 39.61 196.8V196.8zM109.1 192H402.9L376.8 117.4C372.3 104.6 360.2 96 346.6 96H165.4C151.8 96 139.7 104.6 135.2 117.4L109.1 192zM96 256C78.33 256 64 270.3 64 288C64 305.7 78.33 320 96 320C113.7 320 128 305.7 128 288C128 270.3 113.7 256 96 256zM416 320C433.7 320 448 305.7 448 288C448 270.3 433.7 256 416 256C398.3 256 384 270.3 384 288C384 305.7 398.3 320 416 320z"})})},symbols:{outline:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:V("path",{d:"M0 0h11v2H0zM4 11h3V6h4V4H0v2h4zM15.5 17c1.381 0 2.5-1.116 2.5-2.493s-1.119-2.493-2.5-2.493S13 13.13 13 14.507 14.119 17 15.5 17m0-2.986c.276 0 .5.222.5.493 0 .272-.224.493-.5.493s-.5-.221-.5-.493.224-.493.5-.493M21.5 19.014c-1.381 0-2.5 1.116-2.5 2.493S20.119 24 21.5 24s2.5-1.116 2.5-2.493-1.119-2.493-2.5-2.493m0 2.986a.497.497 0 0 1-.5-.493c0-.271.224-.493.5-.493s.5.222.5.493a.497.497 0 0 1-.5.493M22 13l-9 9 1.513 1.5 8.99-9.009zM17 11c2.209 0 4-1.119 4-2.5V2s.985-.161 1.498.949C23.01 4.055 23 6 23 6s1-1.119 1-3.135C24-.02 21 0 21 0h-2v6.347A5.853 5.853 0 0 0 17 6c-2.209 0-4 1.119-4 2.5s1.791 2.5 4 2.5M10.297 20.482l-1.475-1.585a47.54 47.54 0 0 1-1.442 1.129c-.307-.288-.989-1.016-2.045-2.183.902-.836 1.479-1.466 1.729-1.892s.376-.871.376-1.336c0-.592-.273-1.178-.818-1.759-.546-.581-1.329-.871-2.349-.871-1.008 0-1.79.293-2.344.879-.556.587-.832 1.181-.832 1.784 0 .813.419 1.748 1.256 2.805-.847.614-1.444 1.208-1.794 1.784a3.465 3.465 0 0 0-.523 1.833c0 .857.308 1.56.924 2.107.616.549 1.423.823 2.42.823 1.173 0 2.444-.379 3.813-1.137L8.235 24h2.819l-2.09-2.383 1.333-1.135zm-6.736-6.389a1.02 1.02 0 0 1 .73-.286c.31 0 .559.085.747.254a.849.849 0 0 1 .283.659c0 .518-.419 1.112-1.257 1.784-.536-.651-.805-1.231-.805-1.742a.901.901 0 0 1 .302-.669M3.74 22c-.427 0-.778-.116-1.057-.349-.279-.232-.418-.487-.418-.766 0-.594.509-1.288 1.527-2.083.968 1.134 1.717 1.946 2.248 2.438-.921.507-1.686.76-2.3.76"})}),solid:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:V("path",{d:"M500.3 7.251C507.7 13.33 512 22.41 512 31.1V175.1C512 202.5 483.3 223.1 447.1 223.1C412.7 223.1 383.1 202.5 383.1 175.1C383.1 149.5 412.7 127.1 447.1 127.1V71.03L351.1 90.23V207.1C351.1 234.5 323.3 255.1 287.1 255.1C252.7 255.1 223.1 234.5 223.1 207.1C223.1 181.5 252.7 159.1 287.1 159.1V63.1C287.1 48.74 298.8 35.61 313.7 32.62L473.7 .6198C483.1-1.261 492.9 1.173 500.3 7.251H500.3zM74.66 303.1L86.5 286.2C92.43 277.3 102.4 271.1 113.1 271.1H174.9C185.6 271.1 195.6 277.3 201.5 286.2L213.3 303.1H239.1C266.5 303.1 287.1 325.5 287.1 351.1V463.1C287.1 490.5 266.5 511.1 239.1 511.1H47.1C21.49 511.1-.0019 490.5-.0019 463.1V351.1C-.0019 325.5 21.49 303.1 47.1 303.1H74.66zM143.1 359.1C117.5 359.1 95.1 381.5 95.1 407.1C95.1 434.5 117.5 455.1 143.1 455.1C170.5 455.1 191.1 434.5 191.1 407.1C191.1 381.5 170.5 359.1 143.1 359.1zM440.3 367.1H496C502.7 367.1 508.6 372.1 510.1 378.4C513.3 384.6 511.6 391.7 506.5 396L378.5 508C372.9 512.1 364.6 513.3 358.6 508.9C352.6 504.6 350.3 496.6 353.3 489.7L391.7 399.1H336C329.3 399.1 323.4 395.9 321 389.6C318.7 383.4 320.4 376.3 325.5 371.1L453.5 259.1C459.1 255 467.4 254.7 473.4 259.1C479.4 263.4 481.6 271.4 478.7 278.3L440.3 367.1zM116.7 219.1L19.85 119.2C-8.112 90.26-6.614 42.31 24.85 15.34C51.82-8.137 93.26-3.642 118.2 21.83L128.2 32.32L137.7 21.83C162.7-3.642 203.6-8.137 231.6 15.34C262.6 42.31 264.1 90.26 236.1 119.2L139.7 219.1C133.2 225.6 122.7 225.6 116.7 219.1H116.7z"})})}},search:{loupe:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:V("path",{d:"M12.9 14.32a8 8 0 1 1 1.41-1.41l5.35 5.33-1.42 1.42-5.33-5.34zM8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12z"})}),delete:V("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:V("path",{d:"M10 8.586L2.929 1.515 1.515 2.929 8.586 10l-7.071 7.071 1.414 1.414L10 11.414l7.071 7.071 1.414-1.414L11.414 10l7.071-7.071-1.414-1.414L10 8.586z"})})}};function _e(e){let{id:t,skin:n,emoji:o}=e;if(e.shortcodes){const o=e.shortcodes.match(de.SHORTCODES_REGEX);o&&(t=o[1],o[2]&&(n=o[2]))}if(o||(o=de.get(t||e.native)),!o)return e.fallback;const i=o.skins[n-1]||o.skins[0],r=i.src||("native"==e.set||e.spritesheet?void 0:"function"==typeof e.getImageURL?e.getImageURL(e.set,i.unified):`https://cdn.jsdelivr.net/npm/emoji-datasource-${e.set}@15.0.1/img/${e.set}/64/${i.unified}.png`),s="function"==typeof e.getSpritesheetURL?e.getSpritesheetURL(e.set):`https://cdn.jsdelivr.net/npm/emoji-datasource-${e.set}@15.0.1/img/${e.set}/sheets-256/64.png`;return V("span",{class:"emoji-mart-emoji","data-emoji-set":e.set,children:r?V("img",{style:{maxWidth:e.size||"1em",maxHeight:e.size||"1em",display:"inline-block"},alt:i.native||i.shortcodes,src:r}):"native"==e.set?V("span",{style:{fontSize:e.size,fontFamily:'"EmojiMart", "Segoe UI Emoji", "Segoe UI Symbol", "Segoe UI", "Apple Color Emoji", "Twemoji Mozilla", "Noto Color Emoji", "Android Emoji"'},children:i.native}):V("span",{style:{display:"block",width:e.size,height:e.size,backgroundImage:`url(${s})`,backgroundSize:`${100*ee.sheet.cols}% ${100*ee.sheet.rows}%`,backgroundPosition:`${100/(ee.sheet.cols-1)*i.x}% ${100/(ee.sheet.rows-1)*i.y}%`}})})}const ge="undefined"!=typeof window&&window.HTMLElement?window.HTMLElement:Object;class me extends ge{static get observedAttributes(){return Object.keys(this.Props)}update(e={}){for(let t in e)this.attributeChangedCallback(t,null,e[t])}attributeChangedCallback(e,t,n){if(!this.component)return;const o=le(e,{[e]:n},this.constructor.Props,this);this.component.componentWillReceiveProps?this.component.componentWillReceiveProps({[e]:o}):(this.component.props[e]=o,this.component.forceUpdate())}disconnectedCallback(){this.disconnected=!0,this.component&&this.component.unregister&&this.component.unregister()}constructor(e={}){if(super(),this.props=e,e.parent||e.ref){let t=null;const n=e.parent||(t=e.ref&&e.ref.current);t&&(t.innerHTML=""),n&&n.appendChild(this)}}}class ve extends me{setShadow(){this.attachShadow({mode:"open"})}injectStyles(e){if(!e)return;const t=document.createElement("style");t.textContent=e,this.shadowRoot.insertBefore(t,this.shadowRoot.firstChild)}constructor(e,{styles:t}={}){super(e),this.setShadow(),this.injectStyles(t)}}var be={fallback:"",id:"",native:"",shortcodes:"",size:{value:"",transform:e=>/\D/.test(e)?e:`${e}px`},set:Z.set,skin:Z.skin};class ke extends me{async connectedCallback(){const e=ae(this.props,be,this);e.element=this,e.ref=e=>{this.component=e},await se(),this.disconnected||O(V(_e,{...e}),this)}constructor(e){super(e)}}i(ke,"Props",be),"undefined"==typeof customElements||customElements.get("em-emoji")||customElements.define("em-emoji",ke);var we,ye,Ce=[],xe=s.__b,Se=s.__r,je=s.diffed,ze=s.__c,Me=s.unmount;function Le(){var e;for(Ce.sort(function(e,t){return e.__v.__b-t.__v.__b});e=Ce.pop();)if(e.__P)try{e.__H.__h.forEach(Pe),e.__H.__h.forEach(Re),e.__H.__h=[]}catch(t){e.__H.__h=[],s.__e(t,e.__v)}}s.__b=function(e){we=null,xe&&xe(e)},s.__r=function(e){Se&&Se(e);var t=(we=e.__c).__H;t&&(t.__h.forEach(Pe),t.__h.forEach(Re),t.__h=[])},s.diffed=function(e){je&&je(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Ce.push(t)&&ye===s.requestAnimationFrame||((ye=s.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(o),Ee&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,100);Ee&&(t=requestAnimationFrame(n))})(Le)),we=null},s.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Pe),e.__h=e.__h.filter(function(e){return!e.__||Re(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],s.__e(n,e.__v)}}),ze&&ze(e,t)},s.unmount=function(e){Me&&Me(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Pe(e)}catch(e){t=e}}),t&&s.__e(t,n.__v))};var Ee="function"==typeof requestAnimationFrame;function Pe(e){var t=we,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),we=t}function Re(e){var t=we;e.__c=e.__(),we=t}function Be(e,t){for(var n in e)if("__source"!==n&&!(n in t))return!0;for(var o in t)if("__source"!==o&&e[o]!==t[o])return!0;return!1}function He(e){this.props=e}(He.prototype=new k).isPureReactComponent=!0,He.prototype.shouldComponentUpdate=function(e,t){return Be(this.props,e)||Be(this.state,t)};var Ae=s.__b;s.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Ae&&Ae(e)},"undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.forward_ref");var Te=s.__e;s.__e=function(e,t,n){if(e.then)for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return null==t.__e&&(t.__e=n.__e,t.__k=n.__k),o.__c(e,t);Te(e,t,n)};var Ie=s.unmount;function Oe(){this.__u=0,this.t=null,this.__b=null}function De(e){var t=e.__.__c;return t&&t.__e&&t.__e(e)}function Ve(){this.u=null,this.o=null}s.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&!0===e.__h&&(e.type=null),Ie&&Ie(e)},(Oe.prototype=new k).__c=function(e,t){var n=t.__c,o=this;null==o.t&&(o.t=[]),o.t.push(n);var i=De(o.__v),r=!1,s=function(){r||(r=!0,n.__R=null,i?i(a):a())};n.__R=s;var a=function(){if(! --o.__u){if(o.state.__e){var e=o.state.__e;o.__v.__k[0]=function e(t,n,o){return t&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(t){return e(t,n,o)}),t.__c&&t.__c.__P===n&&(t.__e&&o.insertBefore(t.__e,t.__d),t.__c.__e=!0,t.__c.__P=o)),t}(e,e.__c.__P,e.__c.__O)}var t;for(o.setState({__e:o.__b=null});t=o.t.pop();)t.forceUpdate()}},l=!0===t.__h;o.__u++||l||o.setState({__e:o.__b=o.__v.__k[0]}),e.then(s,s)},Oe.prototype.componentWillUnmount=function(){this.t=[]},Oe.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=function e(t,n,o){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(e){"function"==typeof e.__c&&e.__c()}),t.__c.__H=null),null!=(t=function(e,t){for(var n in t)e[n]=t[n];return e}({},t)).__c&&(t.__c.__P===o&&(t.__c.__P=n),t.__c=null),t.__k=t.__k&&t.__k.map(function(t){return e(t,n,o)})),t}(this.__b,n,o.__O=o.__P)}this.__b=null}var i=t.__e&&g(b,null,e.fallback);return i&&(i.__h=null),[g(b,null,t.__e?null:e.children),i]};var $e=function(e,t,n){if(++n[1]===n[0]&&e.o.delete(t),e.props.revealOrder&&("t"!==e.props.revealOrder[0]||!e.o.size))for(n=e.u;n;){for(;n.length>3;)n.pop()();if(n[1]{const o=t.name||Q.categories[t.id],i=!this.props.unfocused&&t.id==this.state.categoryId;return i&&(e=n),V("button",{"aria-label":o,"aria-selected":i||void 0,title:o,type:"button",class:"flex flex-grow flex-center",onMouseDown:e=>e.preventDefault(),onClick:()=>{this.props.onClick({category:t,i:n})},children:this.renderIcon(t)})}),V("div",{class:"bar",style:{width:100/this.categories.length+"%",opacity:null==e?0:1,transform:"rtl"===this.props.dir?`scaleX(-1) translateX(${100*e}%)`:`translateX(${100*e}%)`}})]})})}constructor(){super(),this.categories=ee.categories.filter(e=>!e.target),this.state={categoryId:this.categories[0].id}}}class tt extends He{shouldComponentUpdate(e){for(let t in e)if("children"!=t&&e[t]!=this.props[t])return!0;return!1}render(){return this.props.children}}class nt extends k{getInitialState(e=this.props){return{skin:$.get("skin")||e.skin,theme:this.initTheme(e.theme)}}componentWillMount(){this.dir=Q.rtl?"rtl":"ltr",this.refs={menu:{current:null},navigation:{current:null},scroll:{current:null},search:{current:null},searchInput:{current:null},skinToneButton:{current:null},skinToneRadio:{current:null}},this.initGrid(),0==this.props.stickySearch&&"sticky"==this.props.searchPosition&&(console.warn("[EmojiMart] Deprecation warning: `stickySearch` has been renamed `searchPosition`."),this.props.searchPosition="static")}componentDidMount(){if(this.register(),this.shadowRoot=this.base.parentNode,this.props.autoFocus){const{searchInput:e}=this.refs;e.current&&e.current.focus()}}componentWillReceiveProps(e){this.nextState||(this.nextState={});for(const t in e)this.nextState[t]=e[t];clearTimeout(this.nextStateTimer),this.nextStateTimer=setTimeout(()=>{let e=!1;for(const t in this.nextState)this.props[t]=this.nextState[t],"custom"!==t&&"categories"!==t||(e=!0);delete this.nextState;const t=this.getInitialState();if(e)return this.reset(t);this.setState(t)})}componentWillUnmount(){this.unregister()}async reset(e={}){await se(this.props),this.initGrid(),this.unobserve(),this.setState(e,()=>{this.observeCategories(),this.observeRows()})}register(){document.addEventListener("click",this.handleClickOutside),this.observe()}unregister(){document.removeEventListener("click",this.handleClickOutside),this.darkMedia?.removeEventListener("change",this.darkMediaCallback),this.unobserve()}observe(){this.observeCategories(),this.observeRows()}unobserve({except:e=[]}={}){Array.isArray(e)||(e=[e]);for(const t of this.observers)e.includes(t)||t.disconnect();this.observers=[].concat(e)}initGrid(){const{categories:e}=ee;this.refs.categories=new Map;const t=ee.categories.map(e=>e.id).join(",");this.navKey&&this.navKey!=t&&this.refs.scroll.current&&(this.refs.scroll.current.scrollTop=0),this.navKey=t,this.grid=[],this.grid.setsize=0;const n=(e,t)=>{const n=[];n.__categoryId=t.id,n.__index=e.length,this.grid.push(n);const o=this.grid.length-1,i=o%10?{}:{current:null};return i.index=o,i.posinset=this.grid.setsize+1,e.push(i),n};for(let t of e){const e=[];let o=n(e,t);for(let i of t.emojis)o.length==this.getPerLine()&&(o=n(e,t)),this.grid.setsize+=1,o.push(i);this.refs.categories.set(t.id,{root:v(),rows:e})}}initTheme(e){if("auto"!=e)return e;if(!this.darkMedia){if(this.darkMedia=matchMedia("(prefers-color-scheme: dark)"),this.darkMedia.media.match(/^not/))return"light";this.darkMedia.addEventListener("change",this.darkMediaCallback)}return this.darkMedia.matches?"dark":"light"}initDynamicPerLine(e=this.props){if(!e.dynamicWidth)return;const{element:t,emojiButtonSize:n}=e,o=()=>{const{width:e}=t.getBoundingClientRect();return Math.floor(e/n)},i=new ResizeObserver(()=>{this.unobserve({except:i}),this.setState({perLine:o()},()=>{this.initGrid(),this.forceUpdate(()=>{this.observeCategories(),this.observeRows()})})});return i.observe(t),this.observers.push(i),o()}getPerLine(){return this.state.perLine||this.props.perLine}getEmojiByPos([e,t]){const n=this.state.searchResults||this.grid,o=n[e]&&n[e][t];if(o)return de.get(o)}observeCategories(){const e=this.refs.navigation.current;if(!e)return;const t=new Map,n=t=>{t!=e.state.categoryId&&e.setState({categoryId:t})},o={root:this.refs.scroll.current,threshold:[0,1]},i=new IntersectionObserver(e=>{for(const n of e){const e=n.target.dataset.id;t.set(e,n.intersectionRatio)}const o=[...t];for(const[e,t]of o)if(t){n(e);break}},o);for(const{root:e}of this.refs.categories.values())i.observe(e.current);this.observers.push(i)}observeRows(){const e={...this.state.visibleRows},t=new IntersectionObserver(t=>{for(const n of t){const t=parseInt(n.target.dataset.index);n.isIntersecting?e[t]=!0:delete e[t]}this.setState({visibleRows:e})},{root:this.refs.scroll.current,rootMargin:`${15*this.props.emojiButtonSize}px 0px ${10*this.props.emojiButtonSize}px`});for(const{rows:e}of this.refs.categories.values())for(const n of e)n.current&&t.observe(n.current);this.observers.push(t)}preventDefault(e){e.preventDefault()}unfocusSearch(){const e=this.refs.searchInput.current;e&&e.blur()}navigate({e,input:t,left:n,right:o,up:i,down:r}){const s=this.state.searchResults||this.grid;if(!s.length)return;let[a,l]=this.state.pos;const c=(()=>{if(0==a&&0==l&&!e.repeat&&(n||i))return null;if(-1==a)return e.repeat||!o&&!r||t.selectionStart!=t.value.length?null:[0,0];if(n||o){let e=s[a];const t=n?-1:1;if(l+=t,!e[l]){if(a+=t,e=s[a],!e)return a=n?0:s.length-1,l=n?0:s[a].length-1,[a,l];l=n?e.length-1:0}return[a,l]}if(i||r){a+=i?-1:1;const e=s[a];return e?(e[l]||(l=e.length-1),[a,l]):(a=i?0:s.length-1,l=i?0:s[a].length-1,[a,l])}})();c?(e.preventDefault(),this.setState({pos:c,keyboard:!0},()=>{this.scrollTo({row:c[0]})})):this.state.pos[0]>-1&&this.setState({pos:[-1,-1]})}scrollTo({categoryId:e,row:t}){const n=this.state.searchResults||this.grid;if(!n.length)return;const o=this.refs.scroll.current,i=o.getBoundingClientRect();let r=0;if(t>=0&&(e=n[t].__categoryId),e&&(r=(this.refs[e]||this.refs.categories.get(e).root).current.getBoundingClientRect().top-(i.top-o.scrollTop)+1),t>=0)if(t){const e=r+n[t].__index*this.props.emojiButtonSize,s=e+this.props.emojiButtonSize+.88*this.props.emojiButtonSize;if(eo.scrollTop+i.height))return;r=s-i.height}}else r=0;this.ignoreMouse(),o.scrollTop=r}ignoreMouse(){this.mouseIsIgnored=!0,clearTimeout(this.ignoreMouseTimer),this.ignoreMouseTimer=setTimeout(()=>{delete this.mouseIsIgnored},100)}handleEmojiOver(e){this.mouseIsIgnored||this.state.showSkins||this.setState({pos:e||[-1,-1],keyboard:!1})}handleEmojiClick({e,emoji:t,pos:n}){if(this.props.onEmojiSelect&&(!t&&n&&(t=this.getEmojiByPos(n)),t)){const n=ue(t,{skinIndex:this.state.skin-1});this.props.maxFrequentRows&&Y.add(n,this.props),this.props.onEmojiSelect(n,e)}}closeSkins(){this.state.showSkins&&(this.setState({showSkins:null,tempSkin:null}),this.base.removeEventListener("click",this.handleBaseClick),this.base.removeEventListener("keydown",this.handleBaseKeydown))}handleSkinMouseOver(e){this.setState({tempSkin:e})}handleSkinClick(e){this.ignoreMouse(),this.closeSkins(),this.setState({skin:e,tempSkin:null}),$.set("skin",e)}renderNav(){return V(et,{ref:this.refs.navigation,icons:this.props.icons,theme:this.state.theme,dir:this.dir,unfocused:!!this.state.searchResults,position:this.props.navPosition,onClick:this.handleCategoryClick},this.navKey)}renderPreview(){const e=this.getEmojiByPos(this.state.pos),t=this.state.searchResults&&!this.state.searchResults.length;return V("div",{id:"preview",class:"flex flex-middle",dir:this.dir,"data-position":this.props.previewPosition,children:[V("div",{class:"flex flex-middle flex-grow",children:[V("div",{class:"flex flex-auto flex-middle flex-center",style:{height:this.props.emojiButtonSize,fontSize:this.props.emojiButtonSize},children:V(_e,{emoji:e,id:t?this.props.noResultsEmoji||"cry":this.props.previewEmoji||("top"==this.props.previewPosition?"point_down":"point_up"),set:this.props.set,size:this.props.emojiButtonSize,skin:this.state.tempSkin||this.state.skin,spritesheet:!0,getSpritesheetURL:this.props.getSpritesheetURL})}),V("div",{class:`margin-${this.dir[0]}`,children:V("div",e||t?{class:`padding-${this.dir[2]} align-${this.dir[0]}`,children:[V("div",{class:"preview-title ellipsis",children:e?e.name:Q.search_no_results_1}),V("div",{class:"preview-subtitle ellipsis color-c",children:e?e.skins[0].shortcodes:Q.search_no_results_2})]}:{class:"preview-placeholder color-c",children:Q.pick})})]}),!e&&"preview"==this.props.skinTonePosition&&this.renderSkinToneButton()]})}renderEmojiButton(e,{pos:t,posinset:n,grid:o}){const i=this.props.emojiButtonSize,r=this.state.tempSkin||this.state.skin,s=(e.skins[r-1]||e.skins[0]).native,a=(l=this.state.pos,c=t,Array.isArray(l)&&Array.isArray(c)&&l.length===c.length&&l.every((e,t)=>e==c[t]));var l,c;const d=t.concat(e.id).join("");return V(tt,{selected:a,skin:r,size:i,children:V("button",{"aria-label":s,"aria-selected":a||void 0,"aria-posinset":n,"aria-setsize":o.setsize,"data-keyboard":this.state.keyboard,title:"none"==this.props.previewPosition?e.name:void 0,type:"button",class:"flex flex-center flex-middle",tabindex:"-1",onClick:t=>this.handleEmojiClick({e:t,emoji:e}),onMouseEnter:()=>this.handleEmojiOver(t),onMouseLeave:()=>this.handleEmojiOver(),style:{width:this.props.emojiButtonSize,height:this.props.emojiButtonSize,fontSize:this.props.emojiSize,lineHeight:0},children:[V("div",{"aria-hidden":"true",class:"background",style:{borderRadius:this.props.emojiButtonRadius,backgroundColor:this.props.emojiButtonColors?this.props.emojiButtonColors[(n-1)%this.props.emojiButtonColors.length]:void 0}}),V(_e,{emoji:e,set:this.props.set,size:this.props.emojiSize,skin:r,spritesheet:!0,getSpritesheetURL:this.props.getSpritesheetURL})]})},d)}renderSearch(){const e="none"==this.props.previewPosition||"search"==this.props.skinTonePosition;return V("div",{children:[V("div",{class:"spacer"}),V("div",{class:"flex flex-middle",children:[V("div",{class:"search relative flex-grow",children:[V("input",{type:"search",ref:this.refs.searchInput,placeholder:Q.search,onClick:this.handleSearchClick,onInput:this.handleSearchInput,onKeyDown:this.handleSearchKeyDown,autoComplete:"off"}),V("span",{class:"icon loupe flex",children:fe.search.loupe}),this.state.searchResults&&V("button",{title:"Clear","aria-label":"Clear",type:"button",class:"icon delete flex",onClick:this.clearSearch,onMouseDown:this.preventDefault,children:fe.search.delete})]}),e&&this.renderSkinToneButton()]})]})}renderSearchResults(){const{searchResults:e}=this.state;return e?V("div",{class:"category",ref:this.refs.search,children:[V("div",{class:`sticky padding-small align-${this.dir[0]}`,children:Q.categories.search}),V("div",{children:e.length?e.map((t,n)=>V("div",{class:"flex",children:t.map((t,o)=>this.renderEmojiButton(t,{pos:[n,o],posinset:n*this.props.perLine+o+1,grid:e}))})):V("div",{class:`padding-small align-${this.dir[0]}`,children:this.props.onAddCustomEmoji&&V("a",{onClick:this.props.onAddCustomEmoji,children:Q.add_custom})})})]}):null}renderCategories(){const{categories:e}=ee,t=!!this.state.searchResults,n=this.getPerLine();return V("div",{style:{visibility:t?"hidden":void 0,display:t?"none":void 0,height:"100%"},children:e.map(e=>{const{root:t,rows:o}=this.refs.categories.get(e.id);return V("div",{"data-id":e.target?e.target.id:e.id,class:"category",ref:t,children:[V("div",{class:`sticky padding-small align-${this.dir[0]}`,children:e.name||Q.categories[e.id]}),V("div",{class:"relative",style:{height:o.length*this.props.emojiButtonSize},children:o.map((t,o)=>{const i=t.index-t.index%10,r=this.state.visibleRows[i],s="current"in t?t:void 0;if(!r&&!s)return null;const a=o*n,l=a+n,c=e.emojis.slice(a,l);return c.length{if(!e)return V("div",{style:{width:this.props.emojiButtonSize,height:this.props.emojiButtonSize}});const o=de.get(e);return this.renderEmojiButton(o,{pos:[t.index,n],posinset:t.posinset+n,grid:this.grid})})},t.index)})})]})})})}renderSkinToneButton(){return"none"==this.props.skinTonePosition?null:V("div",{class:"flex flex-auto flex-center flex-middle",style:{position:"relative",width:this.props.emojiButtonSize,height:this.props.emojiButtonSize},children:V("button",{type:"button",ref:this.refs.skinToneButton,class:"skin-tone-button flex flex-auto flex-center flex-middle","aria-selected":this.state.showSkins?"":void 0,"aria-label":Q.skins.choose,title:Q.skins.choose,onClick:this.openSkins,style:{width:this.props.emojiSize,height:this.props.emojiSize},children:V("span",{class:`skin-tone skin-tone-${this.state.skin}`})})})}renderLiveRegion(){const e=this.getEmojiByPos(this.state.pos);return V("div",{"aria-live":"polite",class:"sr-only",children:e?e.name:""})}renderSkins(){const e=this.refs.skinToneButton.current.getBoundingClientRect(),t=this.base.getBoundingClientRect(),n={};return"ltr"==this.dir?n.right=t.right-e.right-3:n.left=e.left-t.left-3,"bottom"==this.props.previewPosition&&"preview"==this.props.skinTonePosition?n.bottom=t.bottom-e.top+6:(n.top=e.bottom-t.top+3,n.bottom="auto"),V("div",{ref:this.refs.menu,role:"radiogroup",dir:this.dir,"aria-label":Q.skins.choose,class:"menu hidden","data-position":n.top?"top":"bottom",style:n,children:[...Array(6).keys()].map(e=>{const t=e+1,n=this.state.skin==t;return V("div",{children:[V("input",{type:"radio",name:"skin-tone",value:t,"aria-label":Q.skins[t],ref:n?this.refs.skinToneRadio:null,defaultChecked:n,onChange:()=>this.handleSkinMouseOver(t),onKeyDown:e=>{"Enter"!=e.code&&"Space"!=e.code&&"Tab"!=e.code||(e.preventDefault(),this.handleSkinClick(t))}}),V("button",{"aria-hidden":"true",tabindex:"-1",onClick:()=>this.handleSkinClick(t),onMouseEnter:()=>this.handleSkinMouseOver(t),onMouseLeave:()=>this.handleSkinMouseOver(),class:"option flex flex-grow flex-middle",children:[V("span",{class:`skin-tone skin-tone-${t}`}),V("span",{class:"margin-small-lr",children:Q.skins[t]})]})]})})})}render(){const e=this.props.perLine*this.props.emojiButtonSize;return V("section",{id:"root",class:"flex flex-column",dir:this.dir,style:{width:this.props.dynamicWidth?"100%":`calc(${e}px + (var(--padding) + var(--sidebar-width)))`},"data-emoji-set":this.props.set,"data-theme":this.state.theme,"data-menu":this.state.showSkins?"":void 0,children:["top"==this.props.previewPosition&&this.renderPreview(),"top"==this.props.navPosition&&this.renderNav(),"sticky"==this.props.searchPosition&&V("div",{class:"padding-lr",children:this.renderSearch()}),V("div",{ref:this.refs.scroll,class:"scroll flex-grow padding-lr",children:V("div",{style:{width:this.props.dynamicWidth?"100%":e,height:"100%"},children:["static"==this.props.searchPosition&&this.renderSearch(),this.renderSearchResults(),this.renderCategories()]})}),"bottom"==this.props.navPosition&&this.renderNav(),"bottom"==this.props.previewPosition&&this.renderPreview(),this.state.showSkins&&this.renderSkins(),this.renderLiveRegion()]})}constructor(e){super(),i(this,"darkMediaCallback",()=>{"auto"==this.props.theme&&this.setState({theme:this.darkMedia.matches?"dark":"light"})}),i(this,"handleClickOutside",e=>{const{element:t}=this.props;e.target!=t&&(this.state.showSkins&&this.closeSkins(),this.props.onClickOutside&&this.props.onClickOutside(e))}),i(this,"handleBaseClick",e=>{this.state.showSkins&&(e.target.closest(".menu")||(e.preventDefault(),e.stopImmediatePropagation(),this.closeSkins()))}),i(this,"handleBaseKeydown",e=>{this.state.showSkins&&"Escape"==e.key&&(e.preventDefault(),e.stopImmediatePropagation(),this.closeSkins())}),i(this,"handleSearchClick",()=>{this.getEmojiByPos(this.state.pos)&&this.setState({pos:[-1,-1]})}),i(this,"handleSearchInput",async()=>{const e=this.refs.searchInput.current;if(!e)return;const{value:t}=e,n=await de.search(t),o=()=>{this.refs.scroll.current&&(this.refs.scroll.current.scrollTop=0)};if(!n)return this.setState({searchResults:n,pos:[-1,-1]},o);const i=e.selectionStart==e.value.length?[0,0]:[-1,-1],r=[];r.setsize=n.length;let s=null;for(let e of n)r.length&&s.length!=this.getPerLine()||(s=[],s.__categoryId="search",s.__index=r.length,r.push(s)),s.push(e);this.ignoreMouse(),this.setState({searchResults:r,pos:i},o)}),i(this,"handleSearchKeyDown",e=>{const t=e.currentTarget;switch(e.stopImmediatePropagation(),e.key){case"ArrowLeft":this.navigate({e,input:t,left:!0});break;case"ArrowRight":this.navigate({e,input:t,right:!0});break;case"ArrowUp":this.navigate({e,input:t,up:!0});break;case"ArrowDown":this.navigate({e,input:t,down:!0});break;case"Enter":e.preventDefault(),this.handleEmojiClick({e,pos:this.state.pos});break;case"Escape":e.preventDefault(),this.state.searchResults?this.clearSearch():this.unfocusSearch()}}),i(this,"clearSearch",()=>{const e=this.refs.searchInput.current;e&&(e.value="",e.focus(),this.handleSearchInput())}),i(this,"handleCategoryClick",({category:e,i:t})=>{this.scrollTo(0==t?{row:-1}:{categoryId:e.id})}),i(this,"openSkins",e=>{const{currentTarget:t}=e,n=t.getBoundingClientRect();this.setState({showSkins:n},async()=>{await async function(e=1){for(let t in[...Array(e).keys()])await new Promise(requestAnimationFrame)}(2);const e=this.refs.menu.current;e&&(e.classList.remove("hidden"),this.refs.skinToneRadio.current.focus(),this.base.addEventListener("click",this.handleBaseClick,!0),this.base.addEventListener("keydown",this.handleBaseKeydown,!0))})}),this.observers=[],this.state={pos:[-1,-1],perLine:this.initDynamicPerLine(e),visibleRows:{0:!0},...this.getInitialState(e)}}}class ot extends ve{async connectedCallback(){const e=ae(this.props,Z,this);e.element=this,e.ref=e=>{this.component=e},await se(e),this.disconnected||O(V(nt,{...e}),this.shadowRoot)}constructor(e){super(e,{styles:o(it)})}}i(ot,"Props",Z),"undefined"==typeof customElements||customElements.get("em-emoji-picker")||customElements.define("em-emoji-picker",ot);var it={};it=':host {\n width: min-content;\n height: 435px;\n min-height: 230px;\n border-radius: var(--border-radius);\n box-shadow: var(--shadow);\n --border-radius: 10px;\n --category-icon-size: 18px;\n --font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;\n --font-size: 15px;\n --preview-placeholder-size: 21px;\n --preview-title-size: 1.1em;\n --preview-subtitle-size: .9em;\n --shadow-color: 0deg 0% 0%;\n --shadow: .3px .5px 2.7px hsl(var(--shadow-color) / .14), .4px .8px 1px -3.2px hsl(var(--shadow-color) / .14), 1px 2px 2.5px -4.5px hsl(var(--shadow-color) / .14);\n display: flex;\n}\n\n[data-theme="light"] {\n --em-rgb-color: var(--rgb-color, 34, 36, 39);\n --em-rgb-accent: var(--rgb-accent, 34, 102, 237);\n --em-rgb-background: var(--rgb-background, 255, 255, 255);\n --em-rgb-input: var(--rgb-input, 255, 255, 255);\n --em-color-border: var(--color-border, rgba(0, 0, 0, .05));\n --em-color-border-over: var(--color-border-over, rgba(0, 0, 0, .1));\n}\n\n[data-theme="dark"] {\n --em-rgb-color: var(--rgb-color, 222, 222, 221);\n --em-rgb-accent: var(--rgb-accent, 58, 130, 247);\n --em-rgb-background: var(--rgb-background, 21, 22, 23);\n --em-rgb-input: var(--rgb-input, 0, 0, 0);\n --em-color-border: var(--color-border, rgba(255, 255, 255, .1));\n --em-color-border-over: var(--color-border-over, rgba(255, 255, 255, .2));\n}\n\n#root {\n --color-a: rgb(var(--em-rgb-color));\n --color-b: rgba(var(--em-rgb-color), .65);\n --color-c: rgba(var(--em-rgb-color), .45);\n --padding: 12px;\n --padding-small: calc(var(--padding) / 2);\n --sidebar-width: 16px;\n --duration: 225ms;\n --duration-fast: 125ms;\n --duration-instant: 50ms;\n --easing: cubic-bezier(.4, 0, .2, 1);\n width: 100%;\n text-align: left;\n border-radius: var(--border-radius);\n background-color: rgb(var(--em-rgb-background));\n position: relative;\n}\n\n@media (prefers-reduced-motion) {\n #root {\n --duration: 0;\n --duration-fast: 0;\n --duration-instant: 0;\n }\n}\n\n#root[data-menu] button {\n cursor: auto;\n}\n\n#root[data-menu] .menu button {\n cursor: pointer;\n}\n\n:host, #root, input, button {\n color: rgb(var(--em-rgb-color));\n font-family: var(--font-family);\n font-size: var(--font-size);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n line-height: normal;\n}\n\n*, :before, :after {\n box-sizing: border-box;\n min-width: 0;\n margin: 0;\n padding: 0;\n}\n\n.relative {\n position: relative;\n}\n\n.flex {\n display: flex;\n}\n\n.flex-auto {\n flex: none;\n}\n\n.flex-center {\n justify-content: center;\n}\n\n.flex-column {\n flex-direction: column;\n}\n\n.flex-grow {\n flex: auto;\n}\n\n.flex-middle {\n align-items: center;\n}\n\n.flex-wrap {\n flex-wrap: wrap;\n}\n\n.padding {\n padding: var(--padding);\n}\n\n.padding-t {\n padding-top: var(--padding);\n}\n\n.padding-lr {\n padding-left: var(--padding);\n padding-right: var(--padding);\n}\n\n.padding-r {\n padding-right: var(--padding);\n}\n\n.padding-small {\n padding: var(--padding-small);\n}\n\n.padding-small-b {\n padding-bottom: var(--padding-small);\n}\n\n.padding-small-lr {\n padding-left: var(--padding-small);\n padding-right: var(--padding-small);\n}\n\n.margin {\n margin: var(--padding);\n}\n\n.margin-r {\n margin-right: var(--padding);\n}\n\n.margin-l {\n margin-left: var(--padding);\n}\n\n.margin-small-l {\n margin-left: var(--padding-small);\n}\n\n.margin-small-lr {\n margin-left: var(--padding-small);\n margin-right: var(--padding-small);\n}\n\n.align-l {\n text-align: left;\n}\n\n.align-r {\n text-align: right;\n}\n\n.color-a {\n color: var(--color-a);\n}\n\n.color-b {\n color: var(--color-b);\n}\n\n.color-c {\n color: var(--color-c);\n}\n\n.ellipsis {\n white-space: nowrap;\n max-width: 100%;\n width: auto;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.sr-only {\n width: 1px;\n height: 1px;\n position: absolute;\n top: auto;\n left: -10000px;\n overflow: hidden;\n}\n\na {\n cursor: pointer;\n color: rgb(var(--em-rgb-accent));\n}\n\na:hover {\n text-decoration: underline;\n}\n\n.spacer {\n height: 10px;\n}\n\n[dir="rtl"] .scroll {\n padding-left: 0;\n padding-right: var(--padding);\n}\n\n.scroll {\n padding-right: 0;\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.scroll::-webkit-scrollbar {\n width: var(--sidebar-width);\n height: var(--sidebar-width);\n}\n\n.scroll::-webkit-scrollbar-track {\n border: 0;\n}\n\n.scroll::-webkit-scrollbar-button {\n width: 0;\n height: 0;\n display: none;\n}\n\n.scroll::-webkit-scrollbar-corner {\n background-color: rgba(0, 0, 0, 0);\n}\n\n.scroll::-webkit-scrollbar-thumb {\n min-height: 20%;\n min-height: 65px;\n border: 4px solid rgb(var(--em-rgb-background));\n border-radius: 8px;\n}\n\n.scroll::-webkit-scrollbar-thumb:hover {\n background-color: var(--em-color-border-over) !important;\n}\n\n.scroll:hover::-webkit-scrollbar-thumb {\n background-color: var(--em-color-border);\n}\n\n.sticky {\n z-index: 1;\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n font-weight: 500;\n position: sticky;\n top: -1px;\n}\n\n[dir="rtl"] .search input[type="search"] {\n padding: 10px 2.2em 10px 2em;\n}\n\n[dir="rtl"] .search .loupe {\n left: auto;\n right: .7em;\n}\n\n[dir="rtl"] .search .delete {\n left: .7em;\n right: auto;\n}\n\n.search {\n z-index: 2;\n position: relative;\n}\n\n.search input, .search button {\n font-size: calc(var(--font-size) - 1px);\n}\n\n.search input[type="search"] {\n width: 100%;\n background-color: var(--em-color-border);\n transition-duration: var(--duration);\n transition-property: background-color, box-shadow;\n transition-timing-function: var(--easing);\n border: 0;\n border-radius: 10px;\n outline: 0;\n padding: 10px 2em 10px 2.2em;\n display: block;\n}\n\n.search input[type="search"]::-ms-input-placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"]::placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"], .search input[type="search"]::-webkit-search-decoration, .search input[type="search"]::-webkit-search-cancel-button, .search input[type="search"]::-webkit-search-results-button, .search input[type="search"]::-webkit-search-results-decoration {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n}\n\n.search input[type="search"]:focus {\n background-color: rgb(var(--em-rgb-input));\n box-shadow: inset 0 0 0 1px rgb(var(--em-rgb-accent)), 0 1px 3px rgba(65, 69, 73, .2);\n}\n\n.search .icon {\n z-index: 1;\n color: rgba(var(--em-rgb-color), .7);\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n\n.search .loupe {\n pointer-events: none;\n left: .7em;\n}\n\n.search .delete {\n right: .7em;\n}\n\nsvg {\n fill: currentColor;\n width: 1em;\n height: 1em;\n}\n\nbutton {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n cursor: pointer;\n color: currentColor;\n background-color: rgba(0, 0, 0, 0);\n border: 0;\n}\n\n#nav {\n z-index: 2;\n padding-top: 12px;\n padding-bottom: 12px;\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#nav button {\n color: var(--color-b);\n transition: color var(--duration) var(--easing);\n}\n\n#nav button:hover {\n color: var(--color-a);\n}\n\n#nav svg, #nav img {\n width: var(--category-icon-size);\n height: var(--category-icon-size);\n}\n\n#nav[dir="rtl"] .bar {\n left: auto;\n right: 0;\n}\n\n#nav .bar {\n width: 100%;\n height: 3px;\n background-color: rgb(var(--em-rgb-accent));\n transition: transform var(--duration) var(--easing);\n border-radius: 3px 3px 0 0;\n position: absolute;\n bottom: -12px;\n left: 0;\n}\n\n#nav button[aria-selected] {\n color: rgb(var(--em-rgb-accent));\n}\n\n#preview {\n z-index: 2;\n padding: calc(var(--padding) + 4px) var(--padding);\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#preview .preview-placeholder {\n font-size: var(--preview-placeholder-size);\n}\n\n#preview .preview-title {\n font-size: var(--preview-title-size);\n}\n\n#preview .preview-subtitle {\n font-size: var(--preview-subtitle-size);\n}\n\n#nav:before, #preview:before {\n content: "";\n height: 2px;\n position: absolute;\n left: 0;\n right: 0;\n}\n\n#nav[data-position="top"]:before, #preview[data-position="top"]:before {\n background: linear-gradient(to bottom, var(--em-color-border), transparent);\n top: 100%;\n}\n\n#nav[data-position="bottom"]:before, #preview[data-position="bottom"]:before {\n background: linear-gradient(to top, var(--em-color-border), transparent);\n bottom: 100%;\n}\n\n.category:last-child {\n min-height: calc(100% + 1px);\n}\n\n.category button {\n font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, sans-serif;\n position: relative;\n}\n\n.category button > * {\n position: relative;\n}\n\n.category button .background {\n opacity: 0;\n background-color: var(--em-color-border);\n transition: opacity var(--duration-fast) var(--easing) var(--duration-instant);\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n}\n\n.category button:hover .background {\n transition-duration: var(--duration-instant);\n transition-delay: 0s;\n}\n\n.category button[aria-selected] .background {\n opacity: 1;\n}\n\n.category button[data-keyboard] .background {\n transition: none;\n}\n\n.row {\n width: 100%;\n position: absolute;\n top: 0;\n left: 0;\n}\n\n.skin-tone-button {\n border: 1px solid rgba(0, 0, 0, 0);\n border-radius: 100%;\n}\n\n.skin-tone-button:hover {\n border-color: var(--em-color-border);\n}\n\n.skin-tone-button:active .skin-tone {\n transform: scale(.85) !important;\n}\n\n.skin-tone-button .skin-tone {\n transition: transform var(--duration) var(--easing);\n}\n\n.skin-tone-button[aria-selected] {\n background-color: var(--em-color-border);\n border-top-color: rgba(0, 0, 0, .05);\n border-bottom-color: rgba(0, 0, 0, 0);\n border-left-width: 0;\n border-right-width: 0;\n}\n\n.skin-tone-button[aria-selected] .skin-tone {\n transform: scale(.9);\n}\n\n.menu {\n z-index: 2;\n white-space: nowrap;\n border: 1px solid var(--em-color-border);\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n transition-property: opacity, transform;\n transition-duration: var(--duration);\n transition-timing-function: var(--easing);\n border-radius: 10px;\n padding: 4px;\n position: absolute;\n box-shadow: 1px 1px 5px rgba(0, 0, 0, .05);\n}\n\n.menu.hidden {\n opacity: 0;\n}\n\n.menu[data-position="bottom"] {\n transform-origin: 100% 100%;\n}\n\n.menu[data-position="bottom"].hidden {\n transform: scale(.9)rotate(-3deg)translateY(5%);\n}\n\n.menu[data-position="top"] {\n transform-origin: 100% 0;\n}\n\n.menu[data-position="top"].hidden {\n transform: scale(.9)rotate(3deg)translateY(-5%);\n}\n\n.menu input[type="radio"] {\n clip: rect(0 0 0 0);\n width: 1px;\n height: 1px;\n border: 0;\n margin: 0;\n padding: 0;\n position: absolute;\n overflow: hidden;\n}\n\n.menu input[type="radio"]:checked + .option {\n box-shadow: 0 0 0 2px rgb(var(--em-rgb-accent));\n}\n\n.option {\n width: 100%;\n border-radius: 6px;\n padding: 4px 6px;\n}\n\n.option:hover {\n color: #fff;\n background-color: rgb(var(--em-rgb-accent));\n}\n\n.skin-tone {\n width: 16px;\n height: 16px;\n border-radius: 100%;\n display: inline-block;\n position: relative;\n overflow: hidden;\n}\n\n.skin-tone:after {\n content: "";\n mix-blend-mode: overlay;\n background: linear-gradient(rgba(255, 255, 255, .2), rgba(0, 0, 0, 0));\n border: 1px solid rgba(0, 0, 0, .8);\n border-radius: 100%;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 2px #fff;\n}\n\n.skin-tone-1 {\n background-color: #ffc93a;\n}\n\n.skin-tone-2 {\n background-color: #ffdab7;\n}\n\n.skin-tone-3 {\n background-color: #e7b98f;\n}\n\n.skin-tone-4 {\n background-color: #c88c61;\n}\n\n.skin-tone-5 {\n background-color: #a46134;\n}\n\n.skin-tone-6 {\n background-color: #5d4437;\n}\n\n[data-index] {\n justify-content: space-between;\n}\n\n[data-emoji-set="twitter"] .skin-tone:after {\n box-shadow: none;\n border-color: rgba(0, 0, 0, .5);\n}\n\n[data-emoji-set="twitter"] .skin-tone-1 {\n background-color: #fade72;\n}\n\n[data-emoji-set="twitter"] .skin-tone-2 {\n background-color: #f3dfd0;\n}\n\n[data-emoji-set="twitter"] .skin-tone-3 {\n background-color: #eed3a8;\n}\n\n[data-emoji-set="twitter"] .skin-tone-4 {\n background-color: #cfad8d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-5 {\n background-color: #a8805d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-6 {\n background-color: #765542;\n}\n\n[data-emoji-set="google"] .skin-tone:after {\n box-shadow: inset 0 0 2px 2px rgba(0, 0, 0, .4);\n}\n\n[data-emoji-set="google"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="google"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="google"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="google"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="google"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="google"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n[data-emoji-set="facebook"] .skin-tone:after {\n border-color: rgba(0, 0, 0, .4);\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 4px #fff;\n}\n\n[data-emoji-set="facebook"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="facebook"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="facebook"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="facebook"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="facebook"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="facebook"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n',n.d(t,["SafeFlags",0,he])}}]); \ No newline at end of file diff --git a/index.d.ts b/index.d.ts index 5ab3c287..2b094926 100644 --- a/index.d.ts +++ b/index.d.ts @@ -11,6 +11,7 @@ export interface HellotextConfig { push?: false | HellotextPushConfig session?: string autoGenerateSession?: boolean + tracking?: boolean } export type HellotextWebchatMode = 'modal' | 'popover' diff --git a/lib/core/configuration.cjs b/lib/core/configuration.cjs index 63af9baa..d83c2292 100644 --- a/lib/core/configuration.cjs +++ b/lib/core/configuration.cjs @@ -16,6 +16,7 @@ var _push = require("./configuration/push"); * Configuration for Hellotext * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id + * @property {Boolean} [tracking=true] - whether events are sent, false when the visitor refused tracking * @property {Forms} [forms] - form configuration * @property {Popup} [popup] - popup configuration * @property {Webchat} [webchat] - webchat configuration @@ -28,6 +29,7 @@ class Configuration { static actionCableUrl = 'wss://www.hellotext.com/cable'; static autoGenerateSession = true; static session = null; + static tracking = true; static forms = _forms.Forms; static popup = _popup.Popup; static webchat = _webchat.Webchat; diff --git a/lib/core/configuration.js b/lib/core/configuration.js index 4a4d04f8..10ef63e3 100644 --- a/lib/core/configuration.js +++ b/lib/core/configuration.js @@ -11,6 +11,7 @@ import { Push } from './configuration/push'; * Configuration for Hellotext * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id + * @property {Boolean} [tracking=true] - whether events are sent, false when the visitor refused tracking * @property {Forms} [forms] - form configuration * @property {Popup} [popup] - popup configuration * @property {Webchat} [webchat] - webchat configuration @@ -23,6 +24,7 @@ class Configuration { static actionCableUrl = 'wss://www.hellotext.com/cable'; static autoGenerateSession = true; static session = null; + static tracking = true; static forms = Forms; static popup = Popup; static webchat = Webchat; diff --git a/lib/hellotext.cjs b/lib/hellotext.cjs index 350ca602..1d8ae22d 100644 --- a/lib/hellotext.cjs +++ b/lib/hellotext.cjs @@ -185,6 +185,7 @@ class Hellotext { if (this.notInitialized) { throw new _errors.NotInitializedError(); } + if (_core.Configuration.tracking === false) return; const business = this.business; const session = this.session; const headers = { diff --git a/lib/hellotext.js b/lib/hellotext.js index c8291dac..1a8a8d9e 100644 --- a/lib/hellotext.js +++ b/lib/hellotext.js @@ -178,6 +178,7 @@ class Hellotext { if (this.notInitialized) { throw new NotInitializedError(); } + if (Configuration.tracking === false) return; const business = this.business; const session = this.session; const headers = { diff --git a/src/core/configuration.js b/src/core/configuration.js index 6136ecbd..c1175477 100644 --- a/src/core/configuration.js +++ b/src/core/configuration.js @@ -11,6 +11,7 @@ import { Push } from './configuration/push' * Configuration for Hellotext * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id + * @property {Boolean} [tracking=true] - whether events are sent, false when the visitor refused tracking * @property {Forms} [forms] - form configuration * @property {Popup} [popup] - popup configuration * @property {Webchat} [webchat] - webchat configuration @@ -24,6 +25,7 @@ class Configuration { static autoGenerateSession = true static session = null + static tracking = true static forms = Forms static popup = Popup diff --git a/src/hellotext.js b/src/hellotext.js index b55678df..36168497 100644 --- a/src/hellotext.js +++ b/src/hellotext.js @@ -245,6 +245,8 @@ class Hellotext { throw new NotInitializedError() } + if (Configuration.tracking === false) return + const business = this.business const session = this.session const headers = {