From f06a03c20fa73baf97f69a29a9fe71e526f2845a Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Tue, 11 Aug 2026 19:23:24 -0400 Subject: [PATCH 01/11] Add popup runtime integration --- README.md | 16 + __tests__/api/popups_test.js | 107 +++++ .../controllers/popup_controller_test.js | 201 ++++++++++ __tests__/core/configuration_test.js | 22 ++ __tests__/hellotext_test.js | 52 ++- __tests__/models/popup_test.js | 106 +++++ index.d.ts | 9 + src/api/index.js | 5 + src/api/popups.js | 67 ++++ src/controllers/popup_controller.js | 367 +++++++++++++++++ src/core/configuration.js | 5 + src/core/configuration/popup.js | 57 +++ src/hellotext.js | 18 + src/index.js | 2 + src/models/business.js | 2 + src/models/index.js | 1 + src/models/popup.js | 57 +++ styles/index.css | 368 ++++++++++++++++++ 18 files changed, 1461 insertions(+), 1 deletion(-) create mode 100644 __tests__/api/popups_test.js create mode 100644 __tests__/controllers/popup_controller_test.js create mode 100644 __tests__/models/popup_test.js create mode 100644 src/api/popups.js create mode 100644 src/controllers/popup_controller.js create mode 100644 src/core/configuration/popup.js create mode 100644 src/models/popup.js diff --git a/README.md b/README.md index f82a550d..b8a91adc 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ This library allows you the following, - Track events happening on your site to [Hellotext](https://www.hellotext.com) in real-time. - Use Hellotext Forms to dynamically collect data from your customers based on your specific business requirements. - Use Hellotext Webchat to interact with your customers in real-time. +- Use Hellotext Popups to collect customer information from dashboard-built popups. ## Installation @@ -122,5 +123,20 @@ 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 | | 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 | An object that mounts a dashboard popup by id, or `false` to disable popup mounting. | Object \| false | null | | 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 | | whatsappWidget | An object that overrides the dashboard WhatsApp widget configuration, or `false` to disable automatic WhatsApp widget mounting. | Object \| false | Dashboard WhatsApp widget when configured | + +#### Popup + +```javascript +Hellotext.initialize('HELLOTEXT_BUSINESS_ID', { + popup: { + id: 'POPUP_ID', + }, +}) +``` + +When the popup is installed automatically from the dashboard, `Hellotext.initialize('HELLOTEXT_BUSINESS_ID')` mounts the configured popup without passing `popup.id` manually. + +The popup is rendered from the dashboard configuration, including steps, layout, bubble, colors, rules, coupon, and journey metadata. diff --git a/__tests__/api/popups_test.js b/__tests__/api/popups_test.js new file mode 100644 index 00000000..69ca35f6 --- /dev/null +++ b/__tests__/api/popups_test.js @@ -0,0 +1,107 @@ +/** + * @jest-environment jsdom + */ + +import PopupsAPI from '../../src/api/popups' +import Hellotext from '../../src/hellotext' +import { Configuration } from '../../src/core' +import { Locale } from '../../src/core/configuration/locale' + +describe('PopupsAPI', () => { + beforeEach(() => { + Configuration.apiRoot = 'https://api.hellotext.test/v1' + Configuration.popup.device = 'desktop' + Locale._identifier = 'es' + Hellotext.business = { + id: 'business-id', + data: null, + setData: jest.fn(), + setLocale: jest.fn(), + } + + jest.spyOn(Hellotext, 'session', 'get').mockReturnValue('session-123') + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + json: jest.fn().mockResolvedValue({ + business: { id: 'business-id' }, + html: '', + locale: 'es', + }), + }) + }) + + afterEach(() => { + jest.restoreAllMocks() + Configuration.apiRoot = 'https://api.hellotext.com/v1' + Configuration.popup.id = undefined + Configuration.popup.container = 'body' + Configuration.popup.device = 'auto' + Locale._identifier = undefined + }) + + it('fetches the public popup with session, locale, and device params', async () => { + const element = await PopupsAPI.get('popup-id') + const url = new URL(global.fetch.mock.calls[0][0]) + + expect(url.pathname).toBe('/v1/public/popups/popup-id') + expect(url.searchParams.get('session')).toBe('session-123') + expect(url.searchParams.get('locale')).toBe('es') + expect(url.searchParams.get('device')).toBe('desktop') + expect(global.fetch.mock.calls[0][1].headers.Authorization).toBe('Bearer business-id') + expect(element.id).toBe('popup-widget') + expect(Hellotext.business.setData).toHaveBeenCalledWith({ id: 'business-id' }) + expect(Hellotext.business.setLocale).toHaveBeenCalledWith('es') + }) + + it('returns null when the popup request fails', async () => { + global.fetch.mockResolvedValue({ ok: false }) + + await expect(PopupsAPI.get('popup-id')).resolves.toBeNull() + }) + + it('returns null when the popup request errors', async () => { + global.fetch.mockRejectedValue(new Error('Network error')) + + await expect(PopupsAPI.get('popup-id')).resolves.toBeNull() + }) + + it('returns null when the popup response is invalid JSON', async () => { + global.fetch.mockResolvedValue({ + ok: true, + json: jest.fn().mockRejectedValue(new Error('Invalid JSON')), + }) + + await expect(PopupsAPI.get('popup-id')).resolves.toBeNull() + }) + + it('submits popup data with the current session', async () => { + global.fetch.mockResolvedValue({ + ok: true, + json: jest.fn().mockResolvedValue({ id: 'submission-id' }), + }) + + const response = await PopupsAPI.submit('popup-id', { + email: 'customer@example.com', + metadata: { fields: { email: 'customer@example.com' } }, + }) + + const request = global.fetch.mock.calls[0] + const body = JSON.parse(request[1].body) + + expect(request[0]).toBe('https://api.hellotext.test/v1/public/popups/popup-id/submissions') + expect(request[1].method).toBe('POST') + expect(request[1].headers.Authorization).toBe('Bearer business-id') + expect(body).toEqual({ + session: 'session-123', + popup_submission: { + email: 'customer@example.com', + metadata: { + fields: { + email: 'customer@example.com', + }, + }, + }, + }) + expect(response.succeeded).toBe(true) + }) +}) diff --git a/__tests__/controllers/popup_controller_test.js b/__tests__/controllers/popup_controller_test.js new file mode 100644 index 00000000..3c253cff --- /dev/null +++ b/__tests__/controllers/popup_controller_test.js @@ -0,0 +1,201 @@ +/** + * @jest-environment jsdom + */ + +import PopupController from '../../src/controllers/popup_controller' +import API from '../../src/api' + +describe('PopupController', () => { + let controller + let originalLocalStorage + + const buildController = ({ hasBubble = true, rules = { operator: 'and', conditions: [] } } = {}) => { + const element = document.createElement('article') + const bubble = document.createElement('button') + const dialog = document.createElement('section') + const completed = document.createElement('section') + const stepOne = document.createElement('section') + const stepTwo = document.createElement('section') + const emailInput = document.createElement('input') + const phoneInput = document.createElement('input') + const stepOneButton = document.createElement('button') + const stepTwoButton = document.createElement('button') + + bubble.textContent = '10% OFF' + emailInput.type = 'email' + emailInput.required = true + emailInput.dataset.popupFieldKind = 'email' + emailInput.dataset.popupFieldKey = 'email' + emailInput.dataset.popupStepId = 'step-one' + phoneInput.type = 'tel' + phoneInput.required = true + phoneInput.dataset.popupFieldKind = 'phone' + phoneInput.dataset.popupFieldKey = 'phone' + phoneInput.dataset.popupStepId = 'step-two' + stepOne.dataset.stepId = 'step-one' + stepOne.dataset.stepName = 'Step 1' + stepTwo.dataset.stepId = 'step-two' + stepTwo.dataset.stepName = 'Step 2' + stepTwo.hidden = true + completed.hidden = true + + stepOne.appendChild(emailInput) + stepTwo.appendChild(phoneInput) + dialog.append(stepOne, stepTwo, completed) + element.append(bubble, dialog) + document.body.appendChild(element) + + controller = new PopupController() + Object.defineProperty(controller, 'element', { + value: element, + writable: false, + configurable: true, + }) + + controller.bubbleTarget = bubble + controller.dialogTarget = dialog + controller.completedTarget = completed + controller.stepTargets = [stepOne, stepTwo] + controller.inputTargets = [emailInput, phoneInput] + controller.submitButtonTargets = [stepOneButton, stepTwoButton] + controller.hasBubbleTarget = hasBubble + controller.hasBubbleValue = hasBubble + controller.captureValue = { capture_id: 'capture-id' } + controller.deviceValue = 'all' + controller.idValue = 'popup-id' + controller.rulesValue = rules + + return { element, bubble, dialog, completed, stepOne, stepTwo, emailInput, phoneInput } + } + + beforeEach(() => { + originalLocalStorage = window.localStorage + jest.spyOn(API.popups, 'submit').mockResolvedValue({ failed: false }) + }) + + afterEach(() => { + jest.restoreAllMocks() + Object.defineProperty(window, 'localStorage', { + value: originalLocalStorage, + configurable: true, + }) + document.body.innerHTML = '' + localStorage.clear() + }) + + it('shows the bubble first and opens the dialog when clicked', () => { + const { element, bubble, dialog } = buildController() + + controller.connect() + + expect(element.hidden).toBe(false) + expect(bubble.hidden).toBe(false) + expect(dialog.hidden).toBe(true) + + controller.open() + + expect(bubble.hidden).toBe(true) + expect(dialog.hidden).toBe(false) + expect(localStorage.getItem('hellotext:popup:popup-id:viewed')).toBe('true') + }) + + it('validates the current step before moving to the next one', async () => { + const { stepOne, stepTwo, emailInput } = buildController({ hasBubble: false }) + + controller.connect() + + await controller.next() + + expect(stepOne.hidden).toBe(false) + expect(stepTwo.hidden).toBe(true) + expect(API.popups.submit).not.toHaveBeenCalled() + + emailInput.value = 'customer@example.com' + + await controller.next() + + expect(stepOne.hidden).toBe(true) + expect(stepTwo.hidden).toBe(false) + expect(API.popups.submit).not.toHaveBeenCalled() + }) + + it('advances instead of submitting when the form submits before the last step', async () => { + const { stepOne, stepTwo, emailInput } = buildController({ hasBubble: false }) + const event = { preventDefault: jest.fn() } + + controller.connect() + emailInput.value = 'customer@example.com' + + await controller.submit(event) + + expect(event.preventDefault).toHaveBeenCalled() + expect(stepOne.hidden).toBe(true) + expect(stepTwo.hidden).toBe(false) + expect(API.popups.submit).not.toHaveBeenCalled() + }) + + it('submits collected fields and shows the completed step on the last step', async () => { + const { completed, emailInput, phoneInput, stepOne, stepTwo } = buildController({ hasBubble: false }) + + controller.connect() + emailInput.value = 'customer@example.com' + await controller.next() + phoneInput.value = '+15551234567' + + await controller.next() + + expect(API.popups.submit).toHaveBeenCalledWith('popup-id', { + email: 'customer@example.com', + phone: '+15551234567', + metadata: { + capture: { + capture_id: 'capture-id', + }, + fields: { + email: 'customer@example.com', + phone: '+15551234567', + }, + steps: [ + { + id: 'step-one', + name: 'Step 1', + fields: { + email: 'customer@example.com', + }, + }, + { + id: 'step-two', + name: 'Step 2', + fields: { + phone: '+15551234567', + }, + }, + ], + }, + }) + expect(stepOne.hidden).toBe(true) + expect(stepTwo.hidden).toBe(true) + expect(completed.hidden).toBe(false) + }) + + it('tolerates browsers that block localStorage', () => { + buildController() + const storage = { + getItem: jest.fn(() => { + throw new Error('blocked') + }), + setItem: jest.fn(() => { + throw new Error('blocked') + }), + clear: jest.fn(), + } + + Object.defineProperty(window, 'localStorage', { + value: storage, + configurable: true, + }) + + expect(() => controller.markViewed()).not.toThrow() + expect(controller.viewedPopupRulePasses({ inclusion: false })).toBe(true) + }) +}) diff --git a/__tests__/core/configuration_test.js b/__tests__/core/configuration_test.js index c60acc3d..256e719e 100644 --- a/__tests__/core/configuration_test.js +++ b/__tests__/core/configuration_test.js @@ -65,6 +65,28 @@ describe('Configuration', () => { }) }) + describe('.popup', () => { + afterEach(() => { + Configuration.popup.id = undefined + Configuration.popup.container = 'body' + Configuration.popup.device = 'auto' + }) + + it('can be modified', () => { + Configuration.assign({ popup: { id: 'popup-id', container: '#popup-root', device: 'desktop' } }) + + expect(Configuration.popup.id).toEqual('popup-id') + expect(Configuration.popup.container).toEqual('#popup-root') + expect(Configuration.popup.device).toEqual('desktop') + }) + + it('accepts false as an opt-out value', () => { + expect(() => { + Configuration.assign({ popup: false }) + }).not.toThrow() + }) + }) + describe('.locale', () => { beforeEach(() => { Locale._identifier = undefined diff --git a/__tests__/hellotext_test.js b/__tests__/hellotext_test.js index df255e1a..7a3ce90d 100644 --- a/__tests__/hellotext_test.js +++ b/__tests__/hellotext_test.js @@ -1,7 +1,7 @@ import Hellotext from "../src/hellotext"; import API from "../src/api"; import { Configuration } from "../src/core"; -import { Session, Webchat, WhatsAppWidget } from "../src/models"; +import { Popup, Session, Webchat, WhatsAppWidget } from "../src/models"; const getCookieValue = name => document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() @@ -15,6 +15,7 @@ const defaultBusiness = (overrides = {}) => ({ features: {}, locale: "en", style_url: "https://example.com/hellotext.css", + popup: null, webchat: null, whitelist: "disabled", ...overrides, @@ -47,17 +48,23 @@ describe("when trying to call methods before initializing the class", () => { }) describe("when initializing business metadata", () => { + let loadPopup let loadWebchat let loadWhatsAppWidget beforeEach(() => { + loadPopup = jest.spyOn(Popup, 'load').mockResolvedValue({}) loadWebchat = jest.spyOn(Webchat, 'load').mockResolvedValue({}) loadWhatsAppWidget = jest.spyOn(WhatsAppWidget, 'load').mockResolvedValue({}) }) afterEach(() => { + loadPopup.mockRestore() loadWebchat.mockRestore() loadWhatsAppWidget.mockRestore() + Configuration.popup.id = undefined + Configuration.popup.container = 'body' + Configuration.popup.device = 'auto' Configuration.webchat.behaviour = null Configuration.webchat.behaviourOverride = false Configuration.webchat.appearance = {} @@ -290,6 +297,49 @@ describe("when initializing business metadata", () => { expect(loadWhatsAppWidget).not.toHaveBeenCalled() }) + it("loads the dashboard popup when no explicit popup config is passed", async () => { + mockBusinessFetch(defaultBusiness({ popup: { id: "dashboard-popup" } })) + + await Hellotext.initialize("xy76ks") + + expect(loadPopup).toHaveBeenCalledWith("dashboard-popup") + }) + + it("uses the dashboard popup id with explicit local options", async () => { + mockBusinessFetch(defaultBusiness({ popup: { id: "dashboard-popup" } })) + + await Hellotext.initialize("xy76ks", { + popup: { + container: "#popup-container", + device: "desktop", + }, + }) + + expect(loadPopup).toHaveBeenCalledWith("dashboard-popup") + expect(Configuration.popup.container).toEqual("#popup-container") + expect(Configuration.popup.device).toEqual("desktop") + }) + + it("lets an explicit popup id override the dashboard popup id", async () => { + mockBusinessFetch(defaultBusiness({ popup: { id: "dashboard-popup" } })) + + await Hellotext.initialize("xy76ks", { + popup: { + id: "explicit-popup", + }, + }) + + expect(loadPopup).toHaveBeenCalledWith("explicit-popup") + }) + + it("skips popup loading when popup is false", async () => { + mockBusinessFetch(defaultBusiness({ popup: { id: "dashboard-popup" } })) + + await Hellotext.initialize("xy76ks", { popup: false }) + + expect(loadPopup).not.toHaveBeenCalled() + }) + it("does not break initialization when business fetch rejects", async () => { API.businesses.get = jest.fn().mockRejectedValue(new Error("network error")) diff --git a/__tests__/models/popup_test.js b/__tests__/models/popup_test.js new file mode 100644 index 00000000..59df8c1a --- /dev/null +++ b/__tests__/models/popup_test.js @@ -0,0 +1,106 @@ +/** + * @jest-environment jsdom + */ + +import API from '../../src/api' +import { Configuration } from '../../src/core' +import { Popup } from '../../src/models' + +describe('Popup', () => { + const createStylesheet = ({ loaded = true } = {}) => { + const linkTag = document.createElement('link') + linkTag.rel = 'stylesheet' + linkTag.href = 'https://example.com/hellotext.css' + linkTag.setAttribute('data-hellotext-stylesheet', 'true') + + if (loaded) { + linkTag.dataset.hellotextStylesheetLoaded = 'true' + } + + document.head.appendChild(linkTag) + + return linkTag + } + + const markStylesheetLoaded = linkTag => { + Object.defineProperty(linkTag, 'sheet', { + value: {}, + configurable: true, + }) + linkTag.dispatchEvent(new Event('load')) + } + + beforeEach(() => { + document.body.innerHTML = '
' + Configuration.popup.container = '#popup-container' + jest.spyOn(API.popups, 'get') + }) + + afterEach(() => { + jest.restoreAllMocks() + document.body.innerHTML = '' + document.querySelectorAll('link[rel="stylesheet"]').forEach(link => { + link.dispatchEvent(new Event('error')) + link.remove() + }) + Configuration.popup.container = 'body' + }) + + it('waits for the stylesheet before appending the popup HTML', () => { + const linkTag = createStylesheet({ loaded: false }) + const article = document.createElement('article') + article.className = 'hellotext--popup' + API.popups.get.mockResolvedValue(article) + + return Popup.load('popup-id').then(popup => { + expect(document.querySelector('#popup-container article')).toBeNull() + + markStylesheetLoaded(linkTag) + + return popup.rendered.then(() => { + expect(document.querySelector('#popup-container article')).toBe(article) + expect(popup.mounted).toBe(true) + }) + }) + }) + + it('does not mount when the API returns no popup HTML', () => { + createStylesheet() + API.popups.get.mockResolvedValue(null) + + return Popup.load('popup-id').then(popup => { + return popup.rendered.then(() => { + expect(document.querySelector('#popup-container').children.length).toBe(0) + expect(popup.mounted).toBe(false) + }) + }) + }) + + it('does not mount when the configured container is missing', () => { + createStylesheet() + Configuration.popup.container = '#missing-container' + jest.spyOn(console, 'warn').mockImplementation(() => {}) + API.popups.get.mockResolvedValue(document.createElement('article')) + + return Popup.load('popup-id').then(popup => { + return popup.rendered.then(() => { + expect(popup.mounted).toBe(false) + expect(console.warn).toHaveBeenCalledWith('Hellotext popup was not mounted because the container #missing-container was not found.') + }) + }) + }) + + it('does not mount when the configured container selector is invalid', () => { + createStylesheet() + Configuration.popup.container = '[' + jest.spyOn(console, 'warn').mockImplementation(() => {}) + API.popups.get.mockResolvedValue(document.createElement('article')) + + return Popup.load('popup-id').then(popup => { + return popup.rendered.then(() => { + expect(popup.mounted).toBe(false) + expect(console.warn).toHaveBeenCalledWith('Hellotext popup was not mounted because the container [ was not found.') + }) + }) + }) +}) diff --git a/index.d.ts b/index.d.ts index 86f9c70a..48ade904 100644 --- a/index.d.ts +++ b/index.d.ts @@ -5,6 +5,7 @@ export interface HellotextConfig { autoMount?: boolean successMessage?: boolean | string } + popup?: false | HellotextPopupConfig webchat?: false | HellotextWebchatConfig whatsappWidget?: false | HellotextWhatsAppWidgetConfig session?: string @@ -67,6 +68,12 @@ export interface HellotextWhatsAppWidgetConfig { appearance?: HellotextWhatsAppWidgetAppearance } +export interface HellotextPopupConfig { + id?: string + container?: string + device?: 'auto' | 'mobile' | 'desktop' +} + export interface HellotextBusinessCountry { code?: string prefix?: string @@ -81,6 +88,7 @@ export interface HellotextBusinessData { style_url?: string webchat?: HellotextWebchatConfig | null whatsapp?: HellotextWhatsAppWidgetConfig | null + popup?: HellotextPopupConfig | null whitelist?: string | string[] | null subscription?: string | null [key: string]: any @@ -140,6 +148,7 @@ declare class Hellotext { static get isInitialized(): boolean static forms: any static business: HellotextBusiness + static popup: any static webchat: any static whatsapp: any } diff --git a/src/api/index.js b/src/api/index.js index 7e946e7e..23cbdc5d 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -2,6 +2,7 @@ import BusinessesAPI from './businesses' import EventsAPI from './events' import FormsAPI from './forms' import IdentificationsAPI from './identifications' +import PopupsAPI from './popups' import WebchatsAPI from './webchats' import WhatsAppWidgetsAPI from './whatsapp_widgets' import AcksAPI from './acks' @@ -42,6 +43,10 @@ export default class API { return FormsAPI } + static get popups() { + return PopupsAPI + } + static get webchats() { return WebchatsAPI } diff --git a/src/api/popups.js b/src/api/popups.js new file mode 100644 index 00000000..7be866f4 --- /dev/null +++ b/src/api/popups.js @@ -0,0 +1,67 @@ +import { Configuration, Locale } from '../core' +import Hellotext from '../hellotext' + +import { Response } from './response' + +class PopupsAPI { + static get endpoint() { + return Configuration.endpoint('public/popups') + } + + static async get(id) { + const url = new URL(`${this.endpoint}/${id}`) + + url.searchParams.append('session', Hellotext.session) + url.searchParams.append('locale', Locale.toString()) + url.searchParams.append('device', Configuration.popup.device) + + const response = await this.fetchPopup(url) + + if (!response.ok) return null + + const data = await this.parsePopupResponse(response) + + if (!data) return null + + if (!Hellotext.business.data) { + Hellotext.business.setData(data.business) + Hellotext.business.setLocale(data.locale) + } + + return new DOMParser().parseFromString(data.html, 'text/html').querySelector('article') + } + + static async submit(id, data) { + const response = await fetch(`${this.endpoint}/${id}/submissions`, { + method: 'POST', + headers: Hellotext.headers, + body: JSON.stringify({ + session: Hellotext.session, + popup_submission: data, + }), + }) + + return new Response(response.ok, response) + } + + static async fetchPopup(url) { + try { + return await fetch(url, { + method: 'GET', + headers: Hellotext.headers, + }) + } catch (_) { + return { ok: false } + } + } + + static async parsePopupResponse(response) { + try { + return await response.json() + } catch (_) { + return null + } + } +} + +export default PopupsAPI diff --git a/src/controllers/popup_controller.js b/src/controllers/popup_controller.js new file mode 100644 index 00000000..1b74b45b --- /dev/null +++ b/src/controllers/popup_controller.js @@ -0,0 +1,367 @@ +import { Controller } from '@hotwired/stimulus' + +import API from '../api' + +/** + * Public popup runtime controller. + * + * Renders the persisted dashboard popup on merchant sites, applies client-side + * display rules, controls bubble-to-dialog transitions, validates every step, + * submits the collected data, and shows the completion screen. + * + * Targets: + * - bubble: Launcher shown before the popup when bubble mode is enabled. + * - dialog: Popup dialog/surface wrapper. + * - step: Sequential form steps. + * - completed: Completion state shown after submission. + * - input: User-entered popup fields. + * - submitButton: Step buttons disabled while the submission is in flight. + * + * Values: + * - capture: Persisted capture, coupon, and journey metadata. + * - device: Popup device targeting. + * - hasBubble: Whether the popup starts from a bubble. + * - id: Public popup identifier. + * - rules: Persisted AND display rules. + */ +export default class extends Controller { + static targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton'] + static values = { + capture: Object, + device: String, + hasBubble: Boolean, + id: String, + rules: Object, + } + + connect() { + this.stepIndex = 0 + this.onScroll = this.evaluateDisplay.bind(this) + + this.hideElement(this.element) + this.hideElement(this.dialogTarget) + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget) + + this.evaluateDisplay() + } + + disconnect() { + window.removeEventListener('scroll', this.onScroll) + } + + open(event) { + if (event) event.preventDefault() + + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget) + this.showElement(this.dialogTarget) + this.markViewed() + } + + close(event) { + if (event) event.preventDefault() + + this.hideElement(this.dialogTarget) + + if (this.hasBubbleValue && this.hasBubbleTarget) { + this.showElement(this.element) + this.showElement(this.bubbleTarget) + } else { + this.hideElement(this.element) + } + } + + async next(event) { + if (event) event.preventDefault() + + this.clearCustomValidity() + + if (!this.currentStepValid()) { + this.showErrorMessages(this.currentStepInputs) + return + } + + this.clearErrorMessages(this.currentStepInputs) + + if (this.stepIndex < this.stepTargets.length - 1) { + this.showStep(this.stepIndex + 1) + return + } + + await this.submit() + } + + async submit(event) { + if (event) event.preventDefault() + + if (this.stepIndex < this.stepTargets.length - 1) { + await this.next() + return + } + + this.submitButtonTargets.forEach(button => { + button.disabled = true + }) + + const response = await API.popups.submit(this.idValue, this.submissionPayload()) + + this.submitButtonTargets.forEach(button => { + button.disabled = false + }) + + if (response.failed) { + await this.handleSubmissionError(response) + return + } + + this.showCompleted() + } + + evaluateDisplay() { + if (!this.matchesDevice() || !this.rulesWithoutScrollPass()) return + + if (this.scrollRule && !this.scrollRulePasses()) { + window.addEventListener('scroll', this.onScroll, { passive: true }) + return + } + + window.removeEventListener('scroll', this.onScroll) + this.showInitialState() + } + + showInitialState() { + this.showElement(this.element) + + if (this.hasBubbleValue && this.hasBubbleTarget) { + this.showElement(this.bubbleTarget) + this.hideElement(this.dialogTarget) + return + } + + this.showElement(this.dialogTarget) + this.markViewed() + } + + showStep(index) { + this.stepIndex = index + + this.stepTargets.forEach((step, stepIndex) => { + this.toggleElement(step, stepIndex !== index) + }) + + this.hideElement(this.completedTarget) + } + + showCompleted() { + this.stepTargets.forEach(step => this.hideElement(step)) + this.showElement(this.completedTarget) + } + + currentStepValid() { + return this.currentStepInputs.every(input => input.checkValidity()) + } + + showErrorMessages(inputs) { + inputs.forEach(input => { + const container = input.closest('.hellotext--popup-field')?.querySelector('[data-error-container]') + if (!container) return + + container.textContent = input.validity.valid ? '' : input.validationMessage + }) + } + + clearErrorMessages(inputs = this.inputTargets) { + inputs.forEach(input => { + const container = input.closest('.hellotext--popup-field')?.querySelector('[data-error-container]') + if (container) container.textContent = '' + }) + } + + clearCustomValidity() { + this.inputTargets.forEach(input => input.setCustomValidity('')) + } + + async handleSubmissionError(response) { + let data + + try { + data = await response.json() + } catch (_) { + return + } + + const errors = data.errors || [] + + errors.forEach(error => { + const input = this.inputForError(error) + if (!input) return + + input.setCustomValidity(error.description || input.validationMessage) + input.reportValidity() + }) + + this.showErrorMessages(this.inputTargets) + } + + inputForError(error) { + const parameter = error.parameter + if (!parameter) return null + + return this.inputTargets.find(input => { + return input.dataset.popupFieldKind === parameter || input.dataset.popupFieldKey === parameter + }) + } + + submissionPayload() { + const payload = { + metadata: { + capture: this.captureValue || {}, + fields: {}, + steps: [], + }, + } + + this.stepTargets.forEach(step => { + const stepFields = {} + const inputs = this.inputsForStep(step) + + inputs.forEach(input => { + const value = this.inputValue(input) + const key = input.dataset.popupFieldKey || input.name + + stepFields[key] = value + payload.metadata.fields[key] = value + + if (input.dataset.popupFieldKind === 'email') payload.email = value + if (input.dataset.popupFieldKind === 'phone') payload.phone = value + }) + + payload.metadata.steps.push({ + id: step.dataset.stepId, + name: step.dataset.stepName, + fields: stepFields, + }) + }) + + return payload + } + + inputValue(input) { + if (input.type === 'checkbox') return input.checked + + return input.value + } + + inputsForStep(step) { + return this.inputTargets.filter(input => input.dataset.popupStepId === step.dataset.stepId) + } + + rulesWithoutScrollPass() { + return this.conditions + .filter(condition => condition.type !== 'scroll_depth') + .every(condition => this.conditionPasses(condition)) + } + + conditionPasses(condition) { + if (condition.group === 'properties' && condition.type === 'page_property') { + return this.pagePropertyRulePasses(condition) + } + + if (condition.group === 'actions' && condition.type === 'viewed_popup') { + return this.viewedPopupRulePasses(condition) + } + + return true + } + + pagePropertyRulePasses(condition) { + const expected = String(condition.value || '').trim().toLowerCase() + if (!expected) return true + + const actual = this.pagePropertyValue(condition.field) + const includes = actual.includes(expected) + + return condition.query === 'does_not_contain' ? !includes : includes + } + + pagePropertyValue(field) { + if (field === 'url') return window.location.href.toLowerCase() + if (field === 'title') return document.title.toLowerCase() + + return window.location.pathname.toLowerCase() + } + + viewedPopupRulePasses(condition) { + const viewed = this.popupWasViewed() + + return condition.inclusion === false ? !viewed : viewed + } + + scrollRulePasses() { + return this.scrollPercentage >= Number(this.scrollRule.value || 0) + } + + matchesDevice() { + if (this.deviceValue === 'all') return true + if (this.deviceValue === 'mobile') return window.innerWidth < 768 + if (this.deviceValue === 'desktop') return window.innerWidth >= 768 + + return true + } + + markViewed() { + try { + localStorage.setItem(this.viewedStorageKey, 'true') + } catch (_) { + // Some browsers disable storage in private contexts; showing the popup is safer than crashing the page. + } + } + + popupWasViewed() { + try { + return localStorage.getItem(this.viewedStorageKey) === 'true' + } catch (_) { + return false + } + } + + showElement(element) { + element.hidden = false + } + + hideElement(element) { + element.hidden = true + } + + toggleElement(element, hidden) { + element.hidden = hidden + } + + get currentStep() { + return this.stepTargets[this.stepIndex] + } + + get currentStepInputs() { + return this.inputsForStep(this.currentStep) + } + + get conditions() { + return this.rulesValue?.conditions || [] + } + + get scrollRule() { + return this.conditions.find(condition => condition.group === 'actions' && condition.type === 'scroll_depth') + } + + get scrollPercentage() { + const documentElement = document.documentElement + const scrollableHeight = documentElement.scrollHeight - window.innerHeight + + if (scrollableHeight <= 0) return 100 + + return Math.round((window.scrollY / scrollableHeight) * 100) + } + + get viewedStorageKey() { + return `hellotext:popup:${this.idValue}:viewed` + } +} diff --git a/src/core/configuration.js b/src/core/configuration.js index 7df6532a..faf886f4 100644 --- a/src/core/configuration.js +++ b/src/core/configuration.js @@ -1,5 +1,6 @@ import { Forms } from './configuration/forms' import { Locale } from './configuration/locale' +import { Popup } from './configuration/popup' import { Webchat } from './configuration/webchat' import { WhatsApp } from './configuration/whatsapp' @@ -10,6 +11,7 @@ import { WhatsApp } from './configuration/whatsapp' * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id * @property {Forms} [forms] - form configuration + * @property {Popup} [popup] - popup configuration * @property {Webchat} [webchat] - webchat configuration * @property {WhatsApp} [whatsappWidget] - WhatsApp widget configuration * @property {Locale} [locale] - locale configuration @@ -22,6 +24,7 @@ class Configuration { static session = null static forms = Forms + static popup = Popup static webchat = Webchat static whatsapp = WhatsApp @@ -43,6 +46,8 @@ class Configuration { Object.entries(props).forEach(([key, value]) => { if (key === 'forms') { this.forms = Forms.assign(value) + } else if (key === 'popup') { + this.popup = Popup.assign(value) } else if (key === 'webchat') { this.webchat = Webchat.assign(value) } else if (key === 'whatsappWidget') { diff --git a/src/core/configuration/popup.js b/src/core/configuration/popup.js new file mode 100644 index 00000000..2be2423c --- /dev/null +++ b/src/core/configuration/popup.js @@ -0,0 +1,57 @@ +/** + * @typedef {'auto' | 'mobile' | 'desktop'} PopupDevice + * @description Runtime device override for popup loading. + */ + +/** + * @class Popup + * @classdesc Configuration for dashboard popups. + * @property {String} id - The popup id. + * @property {String} container - The container to append the popup to, defaults to 'body'. + * @property {PopupDevice} device - Runtime device preference, defaults to 'auto'. + */ +class Popup { + static _id + static _container = 'body' + static _device = 'auto' + + static set id(value) { + this._id = value + } + + static get id() { + return this._id + } + + static set container(value) { + this._container = value + } + + static get container() { + return this._container + } + + static set device(value) { + if (!['auto', 'mobile', 'desktop'].includes(value)) { + throw new Error(`Invalid popup device value: ${value}`) + } + + this._device = value + } + + static get device() { + return this._device + } + + static assign(props) { + if (props) { + Object.entries(props).forEach(([key, value]) => { + this[key] = value + }) + } + + return this + } +} + +export { Popup } diff --git a/src/hellotext.js b/src/hellotext.js index dd86224f..89bd6eeb 100644 --- a/src/hellotext.js +++ b/src/hellotext.js @@ -6,6 +6,7 @@ import { Fingerprint, FormCollection, Page, + Popup, Query, Session, User, @@ -19,6 +20,7 @@ class Hellotext { static eventEmitter = new Event() static forms static business + static popup static webchat static whatsapp @@ -39,6 +41,13 @@ class Hellotext { this.query = new Query() const businessData = await this.business.hydrate() + const popupConfig = + config.popup === false + ? false + : this.mergePopupConfig( + (businessData && businessData.popup) || {}, + config.popup || {}, + ) const webchatConfig = config.webchat === false ? false @@ -70,6 +79,11 @@ class Hellotext { this.whatsapp = await WhatsAppWidget.load(whatsappConfig.id) } + if (popupConfig && popupConfig.id) { + Configuration.popup.assign(popupConfig) + this.popup = await Popup.load(popupConfig.id) + } + if (typeof MutationObserver !== 'undefined') { this.forms.collectExistingFormsOnPage() } @@ -83,6 +97,10 @@ class Hellotext { return this.deepMergePlainObjects(dashboardConfig, localConfig) } + static mergePopupConfig(dashboardConfig, localConfig) { + return this.deepMergePlainObjects(dashboardConfig, localConfig) + } + static deepMergePlainObjects(base, override) { const result = { ...base } diff --git a/src/index.js b/src/index.js index fc838ec6..7c359d29 100644 --- a/src/index.js +++ b/src/index.js @@ -3,12 +3,14 @@ import Hellotext from './hellotext' import FormController from './controllers/form_controller' import MessageController from './controllers/message_controller' +import PopupController from './controllers/popup_controller' import WebChatEmojiController from './controllers/webchat/emoji_picker_controller' import WebchatController from './controllers/webchat_controller' const application = Application.start() application.register('hellotext--form', FormController) +application.register('hellotext--popup', PopupController) application.register('hellotext--webchat', WebchatController) application.register('hellotext--webchat--emoji', WebChatEmojiController) application.register('hellotext--message', MessageController) diff --git a/src/models/business.js b/src/models/business.js index e07d549b..9abc3e8d 100644 --- a/src/models/business.js +++ b/src/models/business.js @@ -26,7 +26,9 @@ const stylesheetLoadTimeout = 10000 * @property {Object} [features] - Feature flags enabled for the business. * @property {String} [locale] - Default dashboard locale for the business. * @property {String} [style_url] - Stylesheet URL to inject for dashboard-managed surfaces. + * @property {{id: String}|null} [popup] - Dashboard popup defaults. * @property {BusinessWebchat|null} [webchat] - Dashboard webchat defaults. + * @property {{id: String}|null} [whatsapp] - Dashboard WhatsApp widget defaults. * @property {String|Array} [whitelist] - Domain whitelist configuration. * @property {String} [subscription] - Current business subscription tier. */ diff --git a/src/models/index.js b/src/models/index.js index b4ccea9f..8ee74e50 100644 --- a/src/models/index.js +++ b/src/models/index.js @@ -4,6 +4,7 @@ export { Fingerprint } from './fingerprint' export { Form } from './form' export { FormCollection } from './form_collection' export { Page } from './page' +export { Popup } from './popup' export { Query } from './query' export { Session } from './session' export { User } from './user' diff --git a/src/models/popup.js b/src/models/popup.js new file mode 100644 index 00000000..b737b9b0 --- /dev/null +++ b/src/models/popup.js @@ -0,0 +1,57 @@ +import { Configuration } from '../core' + +import API from '../api' +import { Business } from './business' + +class Popup { + static async load(id) { + const popup = new Popup({ + id, + html: await API.popups.get(id), + }) + + popup.rendered = popup.render() + + return popup + } + + constructor(data) { + this.data = data + this.mounted = false + this.rendered = Promise.resolve(false) + } + + async render() { + if (!this.data.html) return false + + const container = this.containerToAppendTo + if (!container) { + console.warn(`Hellotext popup was not mounted because the container ${Configuration.popup.container} was not found.`) + return false + } + + if (!await this.stylesheetLoaded) { + console.warn('Hellotext popup was not mounted because its stylesheet failed to load.') + return false + } + + container.appendChild(this.data.html) + this.mounted = true + + return true + } + + get containerToAppendTo() { + try { + return document.querySelector(Configuration.popup.container) + } catch (_) { + return null + } + } + + get stylesheetLoaded() { + return Business.waitForStylesheet(Business.latestStylesheet) + } +} + +export { Popup } diff --git a/styles/index.css b/styles/index.css index 9b9e6551..07f4e518 100644 --- a/styles/index.css +++ b/styles/index.css @@ -28,3 +28,371 @@ form[data-hello-form] [data-logo-container] small { form[data-hello-form] [data-logo-container] [data-hello-brand] { width: 4rem; } + +.hellotext--popup, +.hellotext--popup * { + box-sizing: border-box; +} + +.hellotext--popup[hidden], +.hellotext--popup [hidden] { + display: none !important; +} + +.hellotext--popup { + --hellotext-popup-background-color: #ffffff; + --hellotext-popup-color: #140434; + --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif; + --hellotext-popup-font-size: 16px; + --hellotext-popup-button-background-color: #ff4c00; + --hellotext-popup-button-color: #ffffff; + --hellotext-popup-bubble-background-color: #ff4c00; + --hellotext-popup-bubble-color: #ffffff; + --hellotext-popup-header-background-color: #ffddf4; + --hellotext-popup-header-background-size: cover; + --hellotext-popup-header-background-image: none; + + color: var(--hellotext-popup-color); + font-family: var(--hellotext-popup-font-family); + font-size: var(--hellotext-popup-font-size); + line-height: 1.4; + position: fixed; + inset: 0; + z-index: 2147483000; + pointer-events: none; +} + +.hellotext--popup-bubble { + appearance: none; + border: 0; + border-radius: 999px; + background: var(--hellotext-popup-bubble-background-color); + color: var(--hellotext-popup-bubble-color); + cursor: pointer; + font: inherit; + font-weight: 700; + padding: 12px 18px; + position: fixed; + bottom: 24px; + min-height: 44px; + max-width: min(320px, calc(100vw - 32px)); + pointer-events: auto; + box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18); +} + +.hellotext--popup--bubble-left .hellotext--popup-bubble { + left: 24px; +} + +.hellotext--popup--bubble-center .hellotext--popup-bubble { + left: 50%; + transform: translateX(-50%); +} + +.hellotext--popup--bubble-right .hellotext--popup-bubble { + right: 24px; +} + +.hellotext--popup-dialog { + position: fixed; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + padding: 24px; + pointer-events: none; +} + +.hellotext--popup-dialog--footer { + align-items: flex-end; + padding: 0; +} + +.hellotext--popup-surface { + position: relative; + display: flex; + overflow: visible; + max-width: calc(100vw - 32px); + max-height: calc(100vh - 32px); + border: 1px solid rgba(20, 4, 52, 0.1); + border-radius: 28px; + background: var(--hellotext-popup-background-color); + color: var(--hellotext-popup-color); + pointer-events: auto; + box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18); +} + +.hellotext--popup-surface--desktop-default, +.hellotext--popup-surface--desktop-image_to_right { + width: min(768px, calc(100vw - 32px)); + min-height: 420px; + align-items: stretch; +} + +.hellotext--popup-surface--image-to-right { + flex-direction: row-reverse; +} + +.hellotext--popup-surface--desktop-column { + width: min(448px, calc(100vw - 32px)); + flex-direction: column; +} + +.hellotext--popup-surface--desktop-footer { + width: 100vw; + max-width: none; + max-height: none; + min-height: 132px; + border-right: 0; + border-bottom: 0; + border-left: 0; + border-radius: 24px 24px 0 0; +} + +.hellotext--popup-header { + min-height: 320px; + width: 40%; + flex: 0 0 40%; + border-radius: 28px 0 0 28px; + background-color: var(--hellotext-popup-header-background-color); + background-image: var(--hellotext-popup-header-background-image); + background-position: center; + background-repeat: no-repeat; + background-size: var(--hellotext-popup-header-background-size); +} + +.hellotext--popup-header--image-right { + border-radius: 0 28px 28px 0; +} + +.hellotext--popup-surface--desktop-column .hellotext--popup-header { + width: 100%; + min-height: 200px; + flex-basis: auto; + border-radius: 28px 28px 0 0; +} + +.hellotext--popup-content { + display: flex; + flex: 1 1 auto; + flex-direction: column; + align-items: center; + justify-content: center; + width: 100%; + min-width: 0; + margin: 0; + padding: 28px; + background: transparent; + color: inherit; +} + +.hellotext--popup-surface--desktop-default .hellotext--popup-content, +.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content { + width: 60%; +} + +.hellotext--popup-surface--desktop-footer .hellotext--popup-content { + flex-direction: row; + flex-wrap: wrap; + gap: 16px 28px; + align-items: center; + justify-content: center; + padding: 24px 56px; +} + +.hellotext--popup-step { + display: flex; + flex-direction: column; + align-items: center; + width: 100%; +} + +.hellotext--popup-surface--desktop-footer .hellotext--popup-step { + display: grid; + grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto; + align-items: center; + justify-content: center; + gap: 12px 28px; +} + +.hellotext--popup-copy { + width: 100%; + margin: 0; +} + +.hellotext--popup-copy * { + color: inherit; + margin-top: 0; +} + +.hellotext--popup-copy--header { + font-size: 18px; + line-height: 1.25; +} + +.hellotext--popup-copy--header h1, +.hellotext--popup-copy--header h2, +.hellotext--popup-copy--header h3 { + font-size: clamp(32px, 7vw, 48px); + line-height: 0.95; + margin: 0 0 8px; +} + +.hellotext--popup-copy--footer { + margin-top: 16px; + font-size: 12px; + opacity: 0.72; +} + +.hellotext--popup-fields { + display: flex; + flex-direction: column; + gap: 10px; + width: 100%; + margin-top: 20px; +} + +.hellotext--popup-field { + width: 100%; +} + +.hellotext--popup-label { + display: flex; + flex-direction: column; + gap: 6px; + width: 100%; + font-size: 13px; + font-weight: 600; +} + +.hellotext--popup-label input { + width: 100%; + min-height: 48px; + border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent); + border-radius: 12px; + background: #ffffff; + color: #140434; + font: inherit; + font-size: 16px; + outline: none; + padding: 12px 16px; +} + +.hellotext--popup-label input:focus { + border-color: var(--hellotext-popup-button-background-color); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent); +} + +.hellotext--popup-error { + display: block; + min-height: 18px; + margin-top: 4px; + color: #d92d20; + font-size: 12px; +} + +.hellotext--popup-actions { + display: flex; + width: 100%; + margin-top: 20px; +} + +.hellotext--popup-content--button-left .hellotext--popup-actions { + justify-content: flex-start; +} + +.hellotext--popup-content--button-center .hellotext--popup-actions { + justify-content: center; +} + +.hellotext--popup-content--button-right .hellotext--popup-actions { + justify-content: flex-end; +} + +.hellotext--popup-content--button-full_width .hellotext--popup-actions { + justify-content: stretch; +} + +.hellotext--popup-button { + appearance: none; + border: 0; + border-radius: 999px; + background: var(--hellotext-popup-button-background-color); + color: var(--hellotext-popup-button-color); + cursor: pointer; + font: inherit; + font-weight: 700; + min-height: 48px; + padding: 12px 24px; + text-align: center; +} + +.hellotext--popup-button--full-width { + width: 100%; +} + +.hellotext--popup-button:disabled { + cursor: progress; + opacity: 0.65; +} + +.hellotext--popup-close { + appearance: none; + position: absolute; + top: 12px; + right: 12px; + z-index: 2; + display: flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border: 0; + border-radius: 999px; + background: #f0eef4; + color: #81778f; + cursor: pointer; + padding: 0; +} + +.hellotext--popup-close svg { + width: 14px; + height: 14px; +} + +@media (max-width: 767px) { + .hellotext--popup-surface { + width: min(350px, calc(100vw - 32px)); + max-height: calc(100vh - 32px); + flex-direction: column; + overflow-y: auto; + } + + .hellotext--popup-surface--mobile-center .hellotext--popup-header, + .hellotext--popup-surface--desktop-footer .hellotext--popup-header { + display: none; + } + + .hellotext--popup-header { + width: 100%; + min-height: 200px; + flex-basis: auto; + border-radius: 28px 28px 0 0; + } + + .hellotext--popup-content, + .hellotext--popup-surface--desktop-footer .hellotext--popup-content { + width: 100%; + padding: 24px; + } + + .hellotext--popup-surface--desktop-footer .hellotext--popup-step { + display: flex; + } + + .hellotext--popup-surface--desktop-footer { + width: 100vw; + max-width: none; + border-radius: 24px 24px 0 0; + } +} From ff4c14bd52812f4f59e5b7572995eb17f14596e4 Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Tue, 11 Aug 2026 22:09:53 -0400 Subject: [PATCH 02/11] Fix Cursor Bugbot: Last-step submit skips validation --- __tests__/controllers/popup_controller_test.js | 15 +++++++++++++++ src/controllers/popup_controller.js | 9 +++++++++ 2 files changed, 24 insertions(+) diff --git a/__tests__/controllers/popup_controller_test.js b/__tests__/controllers/popup_controller_test.js index 3c253cff..a59af36e 100644 --- a/__tests__/controllers/popup_controller_test.js +++ b/__tests__/controllers/popup_controller_test.js @@ -178,6 +178,21 @@ describe('PopupController', () => { expect(completed.hidden).toBe(false) }) + it('validates the last step before submitting', async () => { + const { completed, emailInput, phoneInput, stepTwo } = buildController({ hasBubble: false }) + + controller.connect() + emailInput.value = 'customer@example.com' + await controller.next() + + await controller.submit() + + expect(API.popups.submit).not.toHaveBeenCalled() + expect(stepTwo.hidden).toBe(false) + expect(completed.hidden).toBe(true) + expect(phoneInput.checkValidity()).toBe(false) + }) + it('tolerates browsers that block localStorage', () => { buildController() const storage = { diff --git a/src/controllers/popup_controller.js b/src/controllers/popup_controller.js index 1b74b45b..82f325b2 100644 --- a/src/controllers/popup_controller.js +++ b/src/controllers/popup_controller.js @@ -93,11 +93,20 @@ export default class extends Controller { async submit(event) { if (event) event.preventDefault() + this.clearCustomValidity() + if (this.stepIndex < this.stepTargets.length - 1) { await this.next() return } + if (!this.currentStepValid()) { + this.showErrorMessages(this.currentStepInputs) + return + } + + this.clearErrorMessages(this.currentStepInputs) + this.submitButtonTargets.forEach(button => { button.disabled = true }) From 82b06111e13032bbddad4d3ff525d41d826d3751 Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Fri, 21 Aug 2026 19:25:59 -0400 Subject: [PATCH 03/11] popups: recover runtime bundle after rebase --- __tests__/api/popups_test.js | 10 + dist/hellotext.js | 2 +- lib/api/acks.cjs | 18 +- lib/api/acks.js | 23 +- lib/api/businesses.cjs | 18 +- lib/api/businesses.js | 17 +- lib/api/events.cjs | 18 +- lib/api/events.js | 26 +- lib/api/forms.cjs | 20 +- lib/api/forms.js | 23 +- lib/api/identifications.cjs | 18 +- lib/api/identifications.js | 23 +- lib/api/index.cjs | 26 +- lib/api/index.js | 19 +- lib/api/popups.cjs | 86 ++++ lib/api/popups.js | 105 +++++ lib/api/response.cjs | 22 +- lib/api/response.js | 24 +- lib/api/submissions.cjs | 18 +- lib/api/submissions.js | 17 +- lib/api/webchat/messages.cjs | 18 +- lib/api/webchat/messages.js | 27 +- lib/api/webchats.cjs | 18 +- lib/api/webchats.js | 34 +- lib/api/whatsapp_widgets.cjs | 18 +- lib/api/whatsapp_widgets.js | 26 +- lib/builders/input_builder.cjs | 20 +- lib/builders/input_builder.js | 13 +- lib/builders/logo_builder.cjs | 22 +- lib/builders/logo_builder.js | 17 +- lib/channels/application_channel.cjs | 16 +- lib/channels/application_channel.js | 27 +- lib/channels/webchat_channel.cjs | 54 ++- lib/channels/webchat_channel.js | 49 ++- lib/controllers/form_controller.cjs | 44 +- lib/controllers/form_controller.js | 49 +-- lib/controllers/message_controller.cjs | 40 +- lib/controllers/message_controller.js | 62 ++- lib/controllers/mixins/usePopover.cjs | 6 +- lib/controllers/mixins/usePopover.js | 22 +- lib/controllers/popup_controller.cjs | 391 +++++++++++++++++ lib/controllers/popup_controller.js | 407 ++++++++++++++++++ .../webchat/emoji_picker_controller.cjs | 55 ++- .../webchat/emoji_picker_controller.js | 69 +-- lib/controllers/webchat_controller.cjs | 80 ++-- lib/controllers/webchat_controller.js | 163 +++---- lib/core/configuration.cjs | 21 +- lib/core/configuration.js | 28 +- lib/core/configuration/forms.cjs | 16 +- lib/core/configuration/forms.js | 23 +- lib/core/configuration/locale.cjs | 32 +- lib/core/configuration/locale.js | 29 +- lib/core/configuration/popup.cjs | 68 +++ lib/core/configuration/popup.js | 72 ++++ lib/core/configuration/webchat.cjs | 19 +- lib/core/configuration/webchat.js | 47 +- lib/core/configuration/whatsapp.cjs | 16 +- lib/core/configuration/whatsapp.js | 35 +- lib/core/event.cjs | 18 +- lib/core/event.js | 21 +- lib/core/index.cjs | 2 +- lib/core/sanitize_html.cjs | 2 +- lib/errors/invalid_event.cjs | 40 +- lib/errors/invalid_event.js | 37 +- lib/errors/not_initialized_error.cjs | 40 +- lib/errors/not_initialized_error.js | 37 +- lib/hellotext.cjs | 30 +- lib/hellotext.js | 56 ++- lib/index.cjs | 7 +- lib/index.js | 2 + lib/locales/en.cjs | 5 +- lib/locales/es.cjs | 5 +- lib/locales/index.cjs | 7 +- lib/models/business.cjs | 22 +- lib/models/business.js | 22 +- lib/models/cookies.cjs | 20 +- lib/models/cookies.js | 13 +- lib/models/fingerprint.cjs | 18 +- lib/models/fingerprint.js | 23 +- lib/models/form.cjs | 24 +- lib/models/form.js | 35 +- lib/models/form_collection.cjs | 22 +- lib/models/form_collection.js | 21 +- lib/models/index.cjs | 7 + lib/models/index.js | 1 + lib/models/page.cjs | 18 +- lib/models/page.js | 13 +- lib/models/popup.cjs | 65 +++ lib/models/popup.js | 73 ++++ lib/models/query.cjs | 18 +- lib/models/query.js | 13 +- lib/models/session.cjs | 22 +- lib/models/session.js | 17 +- lib/models/user.cjs | 18 +- lib/models/user.js | 13 +- lib/models/utm.cjs | 18 +- lib/models/utm.js | 23 +- lib/models/webchat.cjs | 20 +- lib/models/webchat.js | 17 +- lib/models/whatsapp_widget.cjs | 20 +- lib/models/whatsapp_widget.js | 17 +- lib/vanilla.cjs | 2 +- src/api/popups.js | 8 +- styles/index.css | 300 +++++++++++++ 104 files changed, 2739 insertions(+), 1179 deletions(-) create mode 100644 lib/api/popups.cjs create mode 100644 lib/api/popups.js create mode 100644 lib/controllers/popup_controller.cjs create mode 100644 lib/controllers/popup_controller.js create mode 100644 lib/core/configuration/popup.cjs create mode 100644 lib/core/configuration/popup.js create mode 100644 lib/models/popup.cjs create mode 100644 lib/models/popup.js diff --git a/__tests__/api/popups_test.js b/__tests__/api/popups_test.js index 69ca35f6..7870d06f 100644 --- a/__tests__/api/popups_test.js +++ b/__tests__/api/popups_test.js @@ -53,6 +53,16 @@ describe('PopupsAPI', () => { expect(Hellotext.business.setLocale).toHaveBeenCalledWith('es') }) + it('resolves the automatic device from the viewport before requesting markup', async () => { + Configuration.popup.device = 'auto' + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 767 }) + + await PopupsAPI.get('popup-id') + + const url = new URL(global.fetch.mock.calls[0][0]) + expect(url.searchParams.get('device')).toBe('mobile') + }) + it('returns null when the popup request fails', async () => { global.fetch.mockResolvedValue({ ok: false }) diff --git a/dist/hellotext.js b/dist/hellotext.js index b236a311..e4494ffe 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,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function c(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function l(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function f(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class p{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||g("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||g("missing identifier"),this.methodName=n.methodName||g("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(f(this.keyMappings,n)||g(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=y(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function g(e){throw new Error(e)}function y(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class S{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class C{constructor(e,t,n){this.tokenListObserver=new E(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 P{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new C(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 v(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=p.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class A{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${l(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class j{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 x(e,t){const n=M(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function M(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class _{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new S(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{x(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new P(this,this.dispatcher),this.valueObserver=new A(this,this.controller),this.targetObserver=new j(this,this),this.outletObserver=new _(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${c(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${c(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return x(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class D{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class q{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class U{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class z{constructor(e,t,n,r){this.targets=new q(this),this.classes=new D(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new U(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 z(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new C(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new z(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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function Z([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,c=!i&&o,l=X(r.type),u=Q(e.typeObject.default);if(s)return l;if(c)return u;if(l!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${l}". The provided default value of "${r.default}" is of type "${u}".`);return a?l:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=X(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=X(e);if(t)return ee[t];const n=f(e,"default"),r=f(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=X(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return x(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${l(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return x(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${l(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return M(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=Z(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=Z(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${l(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return x(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=c(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${l(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},500(e,t,n){n.d(t,{default:()=>Ia});var r=n(72),i=n.n(r),o=n(825),a=n.n(o),s=n(659),c=n.n(s),l=n(56),u=n.n(l),h=n(540),f=n.n(h),d=n(113),p=n.n(d),m=n(109),g={};g.styleTagTransform=p(),g.setAttributes=u(),g.insert=c().bind(null,"head"),g.domAPI=a(),g.insertStyleElement=f(),i()(m.A,g),m.A&&m.A.locals&&m.A.locals;var y=n(891);function v(e,t){for(var n=0;n{var[t,n]=e;this[t]=n}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&v(t.prototype,null),n&&v(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function O(e,t){for(var n=0;n{var[t,n]=e;if(!["primaryColor","secondaryColor","typography"].includes(t))throw new Error("Invalid style property: ".concat(t));if("typography"!==t&&!this.isHexOrRgba(n))throw new Error("Invalid color value: ".concat(n," for ").concat(t,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var[t,n]=e;if(!["header","launcher"].includes(t))throw new Error("Invalid appearance property: ".concat(t));if(!this.isPlainObject(n))throw new Error("Appearance ".concat(t," must be an object"));Object.entries(n).forEach(e=>{var[n,r]=e;if("header"===t&&"name"!==n)throw new Error("Invalid appearance header property: ".concat(n));if("launcher"===t&&"iconUrl"!==n)throw new Error("Invalid appearance launcher property: ".concat(n));if(null!=r&&"string"!=typeof r)throw new Error("Invalid appearance ".concat(t,".").concat(n," value: ").concat(r))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var[t,n]=e;if(!["number","restrictToChannel"].includes(t))throw new Error("Invalid WhatsApp property: ".concat(t));if(null!=n){if("number"===t&&"string"!=typeof n)throw new Error("Invalid WhatsApp number value: ".concat(n));if("restrictToChannel"===t&&"boolean"!=typeof n)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(n))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(L).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?I.FIXED:I.ABSOLUTE},set:function(e){if(e&&!Object.values(I).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var[t,n]=e;this[t]=n}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&x(t.prototype,null),n&&x(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function R(e,t){for(var n=0;n{var[t,n]=e;if("launcher"!==t)throw new Error("Invalid appearance property: ".concat(t));if(!this.isPlainObject(n))throw new Error("Appearance ".concat(t," must be an object"));Object.entries(n).forEach(e=>{var[n,r]=e;if("iconUrl"!==n)throw new Error("Invalid appearance launcher property: ".concat(n));if(null!=r&&"string"!=typeof r)throw new Error("Invalid appearance ".concat(t,".").concat(n," value: ").concat(r))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var[t,n]=e;this[t]=n}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(t.prototype,null),n&&R(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function V(e,t){for(var n=0;n{var[t,n]=e;"forms"===t?this.forms=w.assign(n):"webchat"===t?this.webchat=N.assign(n):"whatsappWidget"===t?this.whatsapp=B.assign(n):this[t]=n}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&V(t.prototype,null),n&&V(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function z(e){var t="function"==typeof Map?new Map:void 0;return z=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return H(e,arguments,K(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),$(r,e)},z(e)}function H(e,t,n){return H=W()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&$(i,n.prototype),i},H.apply(null,arguments)}function W(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function $(e,t){return $=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},$(e,t)}function K(e){return K=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},K(e)}U.apiRoot="https://api.hellotext.com/v1",U.actionCableUrl="wss://www.hellotext.com/cable",U.autoGenerateSession=!0,U.session=null,U.forms=w,U.webchat=N,U.whatsapp=B;var G=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&$(e,t)}(o,e);var t,n,r,i=(n=o,r=W(),function(){var e,t=K(n);if(r){var i=K(this).constructor;e=Reflect.construct(t,arguments,i)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function o(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,o),(t=i.call(this,"".concat(e," is not valid. Please provide a valid event name"))).name="InvalidEvent",t}return t=o,Object.defineProperty(t,"prototype",{writable:!1}),t}(z(Error));function J(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Y(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new G(t);this.subscribers=Y(Y({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new G(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&X(t.prototype,n),r&&X(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function te(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function ne(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:ii.headers,body:JSON.stringify(je({session:ii.session},e))});return new me(t.ok,t)},i=function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function a(e){Me(o,n,i,a,s,"next",e)}function s(e){Me(o,n,i,a,s,"throw",e)}a(void 0)})},function(){return i.apply(this,arguments)})}],null&&_e(t.prototype,null),n&&_e(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();const Ne=Le;function Re(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function De(e,t){for(var n=0;n{var[n,r]=e;t.searchParams.append("style[".concat(n,"]"),r)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",U.webchat.placement);var n=yield fetch(t,{method:"GET",headers:ii.headers}),r=yield n.json();return ii.business.data||(ii.business.setData(r.business),ii.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Re(o,r,i,a,s,"next",e)}function s(e){Re(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,{appearance:r,whatsapp:i}=U.webchat;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=r.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=r.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",i.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",i.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],n&&De(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();const Ve=Be;function qe(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function Ue(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){qe(o,r,i,a,s,"next",e)}function s(e){qe(o,r,i,a,s,"throw",e)}a(void 0)})}}function ze(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:ii.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:ii.headers,body:JSON.stringify(e),keepalive:!0})},i=function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function a(e){Ye(o,n,i,a,s,"next",e)}function s(e){Ye(o,n,i,a,s,"throw",e)}a(void 0)})},function(){return i.apply(this,arguments)})}],null&&Ze(t.prototype,null),n&&Ze(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();const et=Qe;function tt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(lt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(lt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],n&&st(t.prototype,n),r&&st(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function ht(e,t){for(var n=0;n{var[t,n]=e;return n}));t.observed_at=(new Date).toISOString(),dt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(dt.get("hello_utm"))||{}}catch(e){return{}}}}],n&&pt(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function yt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new gt,this._url=t}var t,n,r;return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&yt(t.prototype,n),r&&yt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function wt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new bt;Tt(this,Pt)[Pt]=e,Tt(this,Ct)[Ct]=new se,this.session=Tt(this,Ct)[Ct].session||U.session||dt.get("hello_session"),!this.session&&U.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&wt(t.prototype,null),n&&wt(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(ii.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const Vt=Object.entries,qt=Object.setPrototypeOf,Ut=Object.isFrozen,zt=Object.getPrototypeOf,Ht=Object.getOwnPropertyDescriptor;let Wt=Object.freeze,$t=Object.seal,Kt=Object.create,Gt="undefined"!=typeof Reflect&&Reflect,Jt=Gt.apply,Yt=Gt.construct;Wt||(Wt=function(e){return e}),$t||($t=function(e){return e}),Jt||(Jt=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:rn;if(qt&&qt(e,null),!nn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(Ut(t)||(t[r]=e),i=e)}e[i]=!0}return e}function On(e){for(let t=0;t/g),Dn=$t(/\${[\w\W]*/g),Fn=$t(/^data-[\-\w.\u00B7-\uFFFF]+$/),Bn=$t(/^aria-[\-\w]+$/),Vn=$t(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),qn=$t(/^(?:\w+script|data):/i),Un=$t(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),zn=$t(/^html$/i),Hn=$t(/^[a-z][.\w]*(-[.\w]+)+$/i),Wn=$t(/<[/\w!]/g),$n=$t(/<[/\w]/g),Kn=$t(/<\/no(script|embed|frames)/i),Gn=$t(/\/>/i),Jn=function(){return"undefined"==typeof window?null:window},Yn=function(e,t,n,r){return pn(e,t)&&nn(e[t])?wn(r.base?Tn(r.base):{},e[t],r.transform):n};var Zn=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Jn();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,c=t.Element,l=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,f=c.prototype,d=Sn(f,"cloneNode"),p=Sn(f,"remove"),m=Sn(f,"nextSibling"),g=Sn(f,"childNodes"),y=Sn(f,"parentNode"),v=Sn(f,"shadowRoot"),b=Sn(f,"attributes"),w=s&&s.prototype?Sn(s.prototype,"nodeType"):null,O=s&&s.prototype?Sn(s.prototype,"nodeName"):null,T=s&&s.prototype?Sn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let S,k,E="",C=!1,P=0;const A=function(){if(P>0)throw yn('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.')},j=function(e){A(),P++;try{return S.createHTML(e)}finally{P--}},x=r,M=x.implementation,_=x.createNodeIterator,I=x.createDocumentFragment,L=x.getElementsByTagName,N=i.importNode;let R={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof Vt&&"function"==typeof y&&M&&void 0!==M.createHTMLDocument;const D=Nn,F=Rn,B=Dn,V=Fn,q=Bn,U=qn,z=Un,H=Hn;let W=Vn,$=null;const K=wn({},[...kn,...En,...Cn,...An,...xn]);let G=null;const J=wn({},[...Mn,..._n,...In,...Ln]);let Y=Object.seal(Kt(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}})),Z=null,X=null;const Q=Object.seal(Kt(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,ce=null,le=null,ue=!1,he=!1,fe=!1,de=!1,pe=!0,me=!1;const ge="user-content-";let ye=!0,ve=!1,be={},we=null;const Oe=wn({},["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 Te=null;const Se=wn({},["audio","video","img","source","image","track"]);let ke=null;const Ee=wn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ce="http://www.w3.org/1998/Math/MathML",Pe="http://www.w3.org/2000/svg",Ae="http://www.w3.org/1999/xhtml";let je=Ae,xe=!1,Me=null;const _e=wn({},[Ce,Pe,Ae],on),Ie=Wt(["mi","mo","mn","ms","mtext"]);let Le=wn({},Ie);const Ne=Wt(["annotation-xml"]);let Re=wn({},Ne);const De=wn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,qe=null;const Ue=r.createElement("form"),ze=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(qe&&qe===e)return;e&&"object"==typeof e||(e={}),e=Tn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?on:rn,$=Yn(e,"ALLOWED_TAGS",K,{transform:Ve}),G=Yn(e,"ALLOWED_ATTR",J,{transform:Ve}),Me=Yn(e,"ALLOWED_NAMESPACES",_e,{transform:on}),ke=Yn(e,"ADD_URI_SAFE_ATTR",Ee,{transform:Ve,base:Ee}),Te=Yn(e,"ADD_DATA_URI_TAGS",Se,{transform:Ve,base:Se}),we=Yn(e,"FORBID_CONTENTS",Oe,{transform:Ve}),Z=Yn(e,"FORBID_TAGS",Tn({}),{transform:Ve}),X=Yn(e,"FORBID_ATTR",Tn({}),{transform:Ve}),be=!!pn(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Tn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,fe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,pe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ye=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return gn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Vn,je="string"==typeof e.NAMESPACE?e.NAMESPACE:Ae,Le=pn(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Tn(e.MATHML_TEXT_INTEGRATION_POINTS):wn({},Ie),Re=pn(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Tn(e.HTML_INTEGRATION_POINTS):wn({},Ne);const t=pn(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Tn(e.CUSTOM_ELEMENT_HANDLING):Kt(null);if(Y=Kt(null),pn(t,"tagNameCheck")&&ze(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),pn(t,"attributeNameCheck")&&ze(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),pn(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),$t(Y),ie&&(te=!1),fe&&(he=!0),be&&($=wn({},xn),G=Kt(null),!0===be.html&&(wn($,kn),wn(G,Mn)),!0===be.svg&&(wn($,En),wn(G,_n),wn(G,Ln)),!0===be.svgFilters&&(wn($,Cn),wn(G,_n),wn(G,Ln)),!0===be.mathMl&&(wn($,An),wn(G,In),wn(G,Ln))),Q.tagCheck=null,Q.attributeCheck=null,pn(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:nn(e.ADD_TAGS)&&($===K&&($=Tn($)),wn($,e.ADD_TAGS,Ve))),pn(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:nn(e.ADD_ATTR)&&(G===J&&(G=Tn(G)),wn(G,e.ADD_ATTR,Ve))),pn(e,"ADD_URI_SAFE_ATTR")&&nn(e.ADD_URI_SAFE_ATTR)&&wn(ke,e.ADD_URI_SAFE_ATTR,Ve),pn(e,"FORBID_CONTENTS")&&nn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Tn(we)),wn(we,e.FORBID_CONTENTS,Ve)),pn(e,"ADD_FORBID_CONTENTS")&&nn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Tn(we)),wn(we,e.ADD_FORBID_CONTENTS,Ve)),ye&&($["#text"]=!0),ae&&wn($,["html","head","body"]),$.table&&(wn($,["tbody"]),delete Z.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw yn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw yn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=S;S=e.TRUSTED_TYPES_POLICY;try{E=j("")}catch(e){throw S=t,e}}else null===e.TRUSTED_TYPES_POLICY?(S=void 0,E=""):(void 0===S&&(C||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),C=!0),S=k),S&&"string"==typeof E&&(E=j("")));Wt&&Wt(e),qe=e},We=wn({},[...En,...Cn,...Pn]),$e=wn({},[...An,...jn]),Ke=function(e){en(n.removed,{element:e});try{y(e).removeChild(e)}catch(t){if(p(e),!y(e))throw yn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Ze(e);const t=g(e);if(t){const e=[];Zt(t,t=>{en(e,t)}),Zt(e,e=>{try{p(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{en(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){en(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||fe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Ze=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=g(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Xe=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=an(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&je===Ae&&(e=''+e+"");const i=S?j(e):e;if(je===Ae)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=M.createDocument(je,"template",null);try{t.documentElement.innerHTML=xe?E:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),je===Ae?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return _.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},et=function(e){return e=sn(e,D," "),e=sn(e,F," "),sn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=_.call(n||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&Zt(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==g(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&Zt(e,e=>{e.call(n,t,r,qe)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Tn(t):t},st=function(e,t){if(ot(R.beforeSanitizeElements,e,null),e!==t&&null===y(e))return ve&&Ze(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(R.uponSanitizeElement,$,K,ce),ot(R.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===y(e))return ve&&Ze(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&gn(Wn,e.textContent)&&gn(Wn,e.innerHTML))||!(!oe||e.namespaceURI!==Ae||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!gn($n,e.data))}(e,r))return Ke(e),!0;if(Z[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!Z[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&gn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ye&&!we[t]){const t=y(e),r=g(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(R.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=y(e);t&&t.tagName||(t={namespaceURI:je,tagName:"template"});const n=rn(e.tagName),r=rn(t.tagName);return!!Me[e.namespaceURI]&&(e.namespaceURI===Pe?function(e,t,n){return t.namespaceURI===Ae?"svg"===e:t.namespaceURI===Ce?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Ae?"math"===e:t.namespaceURI===Pe?"math"===e&&Re[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Ae?function(e,t,n){return!(t.namespaceURI===Pe&&!Re[n])&&!(t.namespaceURI===Ce&&!Le[n])&&!$e[e]&&(De[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!Me[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&gn(Kn,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(en(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(R.afterSanitizeElements,e,null),!1},ct=function(e,t,n){if(X[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(pe&&("id"===t||"name"===t)&&(n in r||n in Ue))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&gn(V,t));else if(ee&&gn(q,t));else if(i){if(ke[t]);else if(gn(W,sn(n,z,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==cn(n,"data:")||!Te[e])if(ne&&!gn(U,sn(n,z,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&gn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&gn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&gn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},lt=wn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!lt[rn(e)]&&gn(H,e)},ht=function(e,t,n,r){if(S&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return j(r);case"TrustedScriptURL":return function(e){A(),P++;try{return S.createScriptURL(e)}finally{P--}}(r)}return r},ft=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):Qt(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(R.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(R.uponSanitizeAttribute,G,J,le);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,c=o.value,l=Ve(a),u=c;let h="value"===a?u:ln(u);n.attrName=l,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(R.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==l&&"name"!==l||0===cn(h,ge)||(Je(a,e),h=ge+h),oe&&gn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===l&&an(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&gn(Gn,h)?Je(a,e):(ie&&(h=et(h)),ct(i,l,h)?(h=ht(i,l,s,h),h!==u&&ft(e,a,s,h)):Je(a,e)))}ot(R.afterSanitizeAttributes,e,null)},pt=function(e){let t=null;const n=Qe(e);for(ot(R.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(R.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&pt(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),pt(e))}ot(R.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){pt(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=g(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(xe=!e,xe&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return un(e);case"boolean":return hn(e);case"bigint":return fn?fn(e):"0";case"symbol":return dn?dn(e):"Symbol()";case"undefined":default:return mn(e);case"function":case"object":{if(null===e)return mn(e);const t=e,n=Sn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:mn(e)}return mn(e)}}}(e)))throw yn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=ce,G=le):He(t),(R.uponSanitizeElement.length>0||R.uponSanitizeAttribute.length>0)&&($=Tn($)),R.uponSanitizeAttribute.length>0&&(G=Tn(G)),n.removed=[];const c=ve&&"string"!=typeof e&&it(e);if(c){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&gn($n,e.data)){try{p(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=g(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||Z[n])throw Ge(e),yn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),yn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Xe("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return S&&de?j(e):e;if(r=Xe(e),!r)return he?null:de?E:""}r&&ue&&Ke(r.firstChild);const l=c?e:r;try{const e=Qe(l);for(;a=e.nextNode();)st(a,l),dt(a),rt(a.content)&&pt(a.content)}catch(t){throw c&&(Ge(e),Zt(n.removed,e=>{e.element&&Ze(e.element)})),t}if(c)return Zt(n.removed,e=>{e.element&&Ze(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),fe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&gn(zn,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),S&&de?j(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,ce=$,le=G},n.clearConfig=function(){qe=null,se=!1,ce=null,le=null,S=k,E=""},n.isValidAttribute=function(e,t,n){qe||He({});const r=Ve(e),i=Ve(t);return ct(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&pn(R,e)&&en(R[e],t)},n.removeHook=function(e,t){if(pn(R,e)){if(void 0!==t){const n=Xt(R[e],t);return-1===n?void 0:tn(R[e],n,1)[0]}return Qt(R[e])}},n.removeHooks=function(e){pn(R,e)&&(R[e]=[])},n.removeAllHooks=function(){R={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),Xn={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},Qn={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function er(e,t){var n=Zn.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function tr(e,t){e.replaceChildren(function(e){return er(e,Xn)}(t))}function nr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rr(e,t,n){return(t=ar(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ir(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function or(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,ur,{value:fr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")}var t,n,r,i;return t=e,n=[{key:"mount",value:(r=function*(){var e,{ifCompleted:t=!0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),ii.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),ii.business.features.white_label||this.element.prepend(Dt.build())},i=function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function a(e){ir(o,n,i,a,s,"next",e)}function s(e){ir(o,n,i,a,s,"throw",e)}a(void 0)})},function(){return i.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=sr(this,ur)[ur]("[data-form-header]","header");tr(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=sr(this,ur)[ur]("[data-form-inputs]","main");e.map(e=>Mt.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)}},{key:"buildButton",value:function(e){var t=sr(this,ur)[ur]("[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)}},{key:"buildFooter",value:function(e){var t=sr(this,ur)[ur]("[data-form-footer]","footer");tr(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),ii.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],n&&or(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function fr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function dr(e){var t="function"==typeof Map?new Map:void 0;return dr=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return pr(e,arguments,yr(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),gr(r,e)},dr(e)}function pr(e,t,n){return pr=mr()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&gr(i,n.prototype),i},pr.apply(null,arguments)}function mr(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function gr(e,t){return gr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},gr(e,t)}function yr(e){return yr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},yr(e)}var vr=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&gr(e,t)}(o,e);var t,n,r,i=(n=o,r=mr(),function(){var e,t=yr(n);if(r){var i=yr(this).constructor;e=Reflect.construct(t,arguments,i)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function o(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,o),(e=i.call(this,"You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id")).name="NotInitializedError",e}return t=o,Object.defineProperty(t,"prototype",{writable:!1}),t}(dr(Error));function br(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function wr(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(r=function*(){if(ii.notInitialized)throw new vr;if(!this.fetching){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.");var e=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,kr)[kr];if(0!==e.length){var t=e.map(e=>Pe.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>ii.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),U.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},i=function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function a(e){br(o,n,i,a,s,"next",e)}function s(e){br(o,n,i,a,s,"throw",e)}a(void 0)})},function(){return i.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(ii.business.data||(ii.business.setData(e.business),ii.business.setLocale(j.toString())),ii.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 hr(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],n&&wr(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function Cr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function Pr(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function Ar(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Pr(o,r,i,a,s,"next",e)}function s(e){Pr(o,r,i,a,s,"throw",e)}a(void 0)})}}function jr(e,t){for(var n=0;n$r(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=$r(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function Kr(e,t){var n=$r(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function Gr(){return(Gr=Ur(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var Jr=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,n,r;return t=e,n=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(r=Ur(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return Gr.apply(this,arguments)}(Kr(e,t,n))}),function(e,t){return r.apply(this,arguments)})}],n&&Vr(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function Yr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Zr(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};this.business=new ut(e),this.page=new bt,U.assign(t),At.initialize(this.page),this.forms=new Er,this.query=new se;var n=yield this.business.hydrate(),r=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),i=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),o=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");U.webchat.behaviourOverride=o,r&&r.id&&(U.webchat.assign(r),this.webchat=yield Mr.load(r.id)),i&&i.id&&(U.whatsapp.assign(i),this.whatsapp=yield Rr.load(i.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return o.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=Zr({},e);return Object.entries(t).forEach(e=>{var[t,r]=e;this.isPlainObject(r)&&this.isPlainObject(n[t])?n[t]=this.deepMergePlainObjects(n[t],r):n[t]=r}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(i=ei(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new vr;var n=Zr(Zr({},t&&t.headers||{}),this.headers),r=Zr(Zr({},Br.identificationData),t.user_parameters||{}),i=t&&t.url?new bt(t.url):this.page,o=Zr(Zr({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield it.events.create({headers:n,body:o,keepalive:rt(o)})}),function(e){return i.apply(this,arguments)})},{key:"identify",value:(r=ei(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield Jr.generate(this.session,e,n);if(Jr.matches(Br.fingerprint,r))return new me(!0,{json:(t=ei(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield it.identifications.create(Zr({user_id:e},n));return i.succeeded&&Br.remember(e,n.source,r),i}),function(e){return r.apply(this,arguments)})},{key:"forget",value:function(){Br.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return At.session}},{key:"isInitialized",get:function(){return void 0!==At.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new vr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],n&&ti(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();ri.eventEmitter=new ee,ri.forms=void 0,ri.business=void 0,ri.webchat=void 0,ri.whatsapp=void 0;const ii=ri;function oi(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function ai(e,t){for(var n=0;n{var{type:t,parameter:n}=e,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(ii.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},i=function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function a(e){oi(o,n,i,a,s,"next",e)}function s(e){oi(o,n,i,a,s,"throw",e)}a(void 0)})},function(e){return i.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!U.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof U.forms.successMessage?this.element.innerHTML=U.forms.successMessage:this.element.innerHTML=ii.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],n&&ai(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),c}(y.xI);function fi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function di(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],n&&mi(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),a}(y.xI);bi.values={fadeDistance:{type:Number,default:64},id:String,kind:String,pageStartOffset:{type:Number,default:0},utm:Object},bi.targets=["carouselContainer","leftFade","rightFade","carouselCard"];const wi=["start","end"],Oi=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+wi[0],t+"-"+wi[1]),[]),Ti=Math.min,Si=Math.max,ki=Math.round,Ei=Math.floor,Ci=e=>({x:e,y:e}),Pi={left:"right",right:"left",bottom:"top",top:"bottom"},Ai={start:"end",end:"start"};function ji(e,t,n){return Si(e,Ti(t,n))}function xi(e,t){return"function"==typeof e?e(t):e}function Mi(e){return e.split("-")[0]}function _i(e){return e.split("-")[1]}function Ii(e){return"x"===e?"y":"x"}function Li(e){return"y"===e?"height":"width"}const Ni=new Set(["top","bottom"]);function Ri(e){return Ni.has(Mi(e))?"y":"x"}function Di(e){return Ii(Ri(e))}function Fi(e,t,n){void 0===n&&(n=!1);const r=_i(e),i=Di(e),o=Li(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Hi(a)),[a,Hi(a)]}function Bi(e){return e.replace(/start|end/g,e=>Ai[e])}const Vi=["left","right"],qi=["right","left"],Ui=["top","bottom"],zi=["bottom","top"];function Hi(e){return e.replace(/left|right|bottom|top/g,e=>Pi[e])}function Wi(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function $i(e,t,n){let{reference:r,floating:i}=e;const o=Ri(t),a=Di(t),s=Li(a),c=Mi(t),l="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2;let d;switch(c){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}switch(_i(t)){case"start":d[a]-=f*(n&&l?-1:1);break;case"end":d[a]+=f*(n&&l?-1:1)}return d}async function Ki(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:f=!1,padding:d=0}=xi(t,e),p=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}}(d),m=s[f?"floating"===h?"reference":"floating":h],g=Wi(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:l,rootBoundary:u,strategy:c})),y="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Wi(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:y,offsetParent:v,strategy:c}):y);return{top:(g.top-w.top+p.top)/b.y,bottom:(w.bottom-g.bottom+p.bottom)/b.y,left:(g.left-w.left+p.left)/b.x,right:(w.right-g.right+p.right)/b.x}}const Gi=new Set(["left","top"]);function Ji(){return"undefined"!=typeof window}function Yi(e){return Qi(e)?(e.nodeName||"").toLowerCase():"#document"}function Zi(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Xi(e){var t;return null==(t=(Qi(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Qi(e){return!!Ji()&&(e instanceof Node||e instanceof Zi(e).Node)}function eo(e){return!!Ji()&&(e instanceof Element||e instanceof Zi(e).Element)}function to(e){return!!Ji()&&(e instanceof HTMLElement||e instanceof Zi(e).HTMLElement)}function no(e){return!(!Ji()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Zi(e).ShadowRoot)}const ro=new Set(["inline","contents"]);function io(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=yo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!ro.has(i)}const oo=new Set(["table","td","th"]);function ao(e){return oo.has(Yi(e))}const so=[":popover-open",":modal"];function co(e){return so.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const lo=["transform","translate","scale","rotate","perspective"],uo=["transform","translate","scale","rotate","perspective","filter"],ho=["paint","layout","strict","content"];function fo(e){const t=po(),n=eo(e)?yo(e):e;return lo.some(e=>!!n[e]&&"none"!==n[e])||!!n.containerType&&"normal"!==n.containerType||!t&&!!n.backdropFilter&&"none"!==n.backdropFilter||!t&&!!n.filter&&"none"!==n.filter||uo.some(e=>(n.willChange||"").includes(e))||ho.some(e=>(n.contain||"").includes(e))}function po(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const mo=new Set(["html","body","#document"]);function go(e){return mo.has(Yi(e))}function yo(e){return Zi(e).getComputedStyle(e)}function vo(e){return eo(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function bo(e){if("html"===Yi(e))return e;const t=e.assignedSlot||e.parentNode||no(e)&&e.host||Xi(e);return no(t)?t.host:t}function wo(e){const t=bo(e);return go(t)?e.ownerDocument?e.ownerDocument.body:e.body:to(t)&&io(t)?t:wo(t)}function Oo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=wo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Zi(i);if(o){const e=To(a);return t.concat(a,a.visualViewport||[],io(i)?i:[],e&&n?Oo(e):[])}return t.concat(i,Oo(i,[],n))}function To(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function So(e){const t=yo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=to(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=ki(n)!==o||ki(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function ko(e){return eo(e)?e:e.contextElement}function Eo(e){const t=ko(e);if(!to(t))return Ci(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=So(t);let a=(o?ki(n.width):n.width)/r,s=(o?ki(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const Co=Ci(0);function Po(e){const t=Zi(e);return po()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:Co}function Ao(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=ko(e);let a=Ci(1);t&&(r?eo(r)&&(a=Eo(r)):a=Eo(e));const s=function(e,t,n){return void 0===t&&(t=!1),!(!n||t&&n!==Zi(e))&&t}(o,n,r)?Po(o):Ci(0);let c=(i.left+s.x)/a.x,l=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o){const e=Zi(o),t=r&&eo(r)?Zi(r):r;let n=e,i=To(n);for(;i&&r&&t!==n;){const e=Eo(i),t=i.getBoundingClientRect(),r=yo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,h*=e.y,c+=o,l+=a,n=Zi(i),i=To(n)}}return Wi({width:u,height:h,x:c,y:l})}function jo(e,t){const n=vo(e).scrollLeft;return t?t.left+n:Ao(Xi(e)).left+n}function xo(e,t,n){void 0===n&&(n=!1);const r=e.getBoundingClientRect();return{x:r.left+t.scrollLeft-(n?0:jo(e,r)),y:r.top+t.scrollTop}}const Mo=new Set(["absolute","fixed"]);function _o(e,t,n){let r;if("viewport"===t)r=function(e,t){const n=Zi(e),r=Xi(e),i=n.visualViewport;let o=r.clientWidth,a=r.clientHeight,s=0,c=0;if(i){o=i.width,a=i.height;const e=po();(!e||e&&"fixed"===t)&&(s=i.offsetLeft,c=i.offsetTop)}return{width:o,height:a,x:s,y:c}}(e,n);else if("document"===t)r=function(e){const t=Xi(e),n=vo(e),r=e.ownerDocument.body,i=Si(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=Si(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+jo(e);const s=-n.scrollTop;return"rtl"===yo(r).direction&&(a+=Si(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:a,y:s}}(Xi(e));else if(eo(t))r=function(e,t){const n=Ao(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=to(e)?Eo(e):Ci(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=Po(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Wi(r)}function Io(e,t){const n=bo(e);return!(n===t||!eo(n)||go(n))&&("fixed"===yo(n).position||Io(n,t))}function Lo(e,t,n){const r=to(t),i=Xi(t),o="fixed"===n,a=Ao(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const c=Ci(0);function l(){c.x=jo(i)}if(r||!r&&!o)if(("body"!==Yi(t)||io(i))&&(s=vo(t)),r){const e=Ao(t,!0,o,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else i&&l();o&&!r&&i&&l();const u=!i||r||o?Ci(0):xo(i,s);return{x:a.left+s.scrollLeft-c.x-u.x,y:a.top+s.scrollTop-c.y-u.y,width:a.width,height:a.height}}function No(e){return"static"===yo(e).position}function Ro(e,t){if(!to(e)||"fixed"===yo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Xi(e)===n&&(n=n.ownerDocument.body),n}function Do(e,t){const n=Zi(e);if(co(e))return n;if(!to(e)){let t=bo(e);for(;t&&!go(t);){if(eo(t)&&!No(t))return t;t=bo(t)}return n}let r=Ro(e,t);for(;r&&ao(r)&&No(r);)r=Ro(r,t);return r&&go(r)&&No(r)&&!fo(r)?n:r||function(e){let t=bo(e);for(;to(t)&&!go(t);){if(fo(t))return t;if(co(t))return null;t=bo(t)}return null}(e)||n}const Fo={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Xi(r),s=!!t&&co(t.floating);if(r===a||s&&o)return n;let c={scrollLeft:0,scrollTop:0},l=Ci(1);const u=Ci(0),h=to(r);if((h||!h&&!o)&&(("body"!==Yi(r)||io(a))&&(c=vo(r)),to(r))){const e=Ao(r);l=Eo(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const f=!a||h||o?Ci(0):xo(a,c,!0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}},getDocumentElement:Xi,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?co(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Oo(e,[],!1).filter(e=>eo(e)&&"body"!==Yi(e)),i=null;const o="fixed"===yo(e).position;let a=o?bo(e):e;for(;eo(a)&&!go(a);){const t=yo(a),n=fo(a);n||"fixed"!==t.position||(i=null),(o?!n&&!i:!n&&"static"===t.position&&i&&Mo.has(i.position)||io(a)&&!n&&Io(e,a))?r=r.filter(e=>e!==a):i=t,a=bo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=o[0],s=o.reduce((e,n)=>{const r=_o(t,n,i);return e.top=Si(r.top,e.top),e.right=Ti(r.right,e.right),e.bottom=Ti(r.bottom,e.bottom),e.left=Si(r.left,e.left),e},_o(t,a,i));return{width:s.right-s.left,height:s.bottom-s.top,x:s.left,y:s.top}},getOffsetParent:Do,getElementRects:async function(e){const t=this.getOffsetParent||Do,n=this.getDimensions,r=await n(e.floating);return{reference:Lo(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:n}=So(e);return{width:t,height:n}},getScale:Eo,isElement:eo,isRTL:function(e){return"rtl"===yo(e).direction}};function Bo(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const Vo=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:o,placement:a,middlewareData:s}=t,c=await async function(e,t){const{placement:n,platform:r,elements:i}=e,o=await(null==r.isRTL?void 0:r.isRTL(i.floating)),a=Mi(n),s=_i(n),c="y"===Ri(n),l=Gi.has(a)?-1:1,u=o&&c?-1:1,h=xi(t,e);let{mainAxis:f,crossAxis:d,alignmentAxis:p}="number"==typeof h?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return s&&"number"==typeof p&&(d="end"===s?-1*p:p),c?{x:d*u,y:f*l}:{x:f*l,y:d*u}}(t,e);return a===(null==(n=s.offset)?void 0:n.placement)&&null!=(r=s.arrow)&&r.alignmentOffset?{}:{x:i+c.x,y:o+c.y,data:{...c,placement:a}}}}},qo=function(e){return void 0===e&&(e={}),{name:"autoPlacement",options:e,async fn(t){var n,r,i;const{rects:o,middlewareData:a,placement:s,platform:c,elements:l}=t,{crossAxis:u=!1,alignment:h,allowedPlacements:f=Oi,autoAlignment:d=!0,...p}=xi(e,t),m=void 0!==h||f===Oi?function(e,t,n){return(e?[...n.filter(t=>_i(t)===e),...n.filter(t=>_i(t)!==e)]:n.filter(e=>Mi(e)===e)).filter(n=>!e||_i(n)===e||!!t&&Bi(n)!==n)}(h||null,d,f):f,g=await Ki(t,p),y=(null==(n=a.autoPlacement)?void 0:n.index)||0,v=m[y];if(null==v)return{};const b=Fi(v,o,await(null==c.isRTL?void 0:c.isRTL(l.floating)));if(s!==v)return{reset:{placement:m[0]}};const w=[g[Mi(v)],g[b[0]],g[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:v,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const S=O.map(e=>{const t=_i(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=S.filter(e=>e[2].slice(0,_i(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||S[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},Uo=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i}=t,{mainAxis:o=!0,crossAxis:a=!1,limiter:s={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=xi(e,t),l={x:n,y:r},u=await Ki(t,c),h=Ri(Mi(i)),f=Ii(h);let d=l[f],p=l[h];if(o){const e="y"===f?"bottom":"right";d=ji(d+u["y"===f?"top":"left"],d,d-u[e])}if(a){const e="y"===h?"bottom":"right";p=ji(p+u["y"===h?"top":"left"],p,p-u[e])}const m=s.fn({...t,[f]:d,[h]:p});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[f]:o,[h]:a}}}}}},zo=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:c,elements:l}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:f,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:p="none",flipAlignment:m=!0,...g}=xi(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const y=Mi(i),v=Ri(s),b=Mi(s)===s,w=await(null==c.isRTL?void 0:c.isRTL(l.floating)),O=f||(b||!m?[Hi(s)]:function(e){const t=Hi(e);return[Bi(e),t,Bi(t)]}(s)),T="none"!==p;!f&&T&&O.push(...function(e,t,n,r){const i=_i(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?qi:Vi:t?Vi:qi;case"left":case"right":return t?Ui:zi;default:return[]}}(Mi(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(Bi)))),o}(s,m,p,w));const S=[s,...O],k=await Ki(t,g),E=[];let C=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&E.push(k[y]),h){const e=Fi(i,a,w);E.push(k[e[0]],k[e[1]])}if(C=[...C,{placement:i,overflows:E}],!E.every(e=>e<=0)){var P,A;const e=((null==(P=o.flip)?void 0:P.index)||0)+1,t=S[e];if(t&&("alignment"!==h||v===Ri(t)||C.every(e=>Ri(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:C},reset:{placement:t}};let n=null==(A=C.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:A.placement;if(!n)switch(d){case"bestFit":{var j;const e=null==(j=C.filter(e=>{if(T){const t=Ri(e.placement);return t===v||"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:j[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var Ho=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var{trigger:t,popover:n,strategy:r}=e;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:c=!1}=r,l=ko(e),u=i||o?[...l?Oo(l):[],...Oo(t)]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n,{passive:!0}),o&&e.addEventListener("resize",n)});const h=l&&s?function(e,t){let n,r=null;const i=Xi(e);function o(){var e;clearTimeout(n),null==(e=r)||e.disconnect(),r=null}return function a(s,c){void 0===s&&(s=!1),void 0===c&&(c=1),o();const l=e.getBoundingClientRect(),{left:u,top:h,width:f,height:d}=l;if(s||t(),!f||!d)return;const p={rootMargin:-Ei(h)+"px "+-Ei(i.clientWidth-(u+f))+"px "+-Ei(i.clientHeight-(h+d))+"px "+-Ei(u)+"px",threshold:Si(0,Ti(1,c))||1};let m=!0;function g(t){const r=t[0].intersectionRatio;if(r!==c){if(!m)return a();r?a(!1,r):n=setTimeout(()=>{a(!1,1e-7)},1e3)}1!==r||Bo(l,e.getBoundingClientRect())||a(),m=!1}try{r=new IntersectionObserver(g,{...p,root:i.ownerDocument})}catch(e){r=new IntersectionObserver(g,p)}r.observe(e)}(!0),o}(l,n):null;let f,d=-1,p=null;a&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&(p.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=p)||e.observe(t)})),n()}),l&&!c&&p.observe(l),p.observe(t));let m=c?Ao(e):null;return c&&function t(){const r=Ao(e);m&&!Bo(m,r)&&n(),m=r,f=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=p)||e.disconnect(),p=null,c&&cancelAnimationFrame(f)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i={platform:Fo,...n},o={...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=o.filter(Boolean),c=await(null==a.isRTL?void 0:a.isRTL(t));let l=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=$i(l,r,c),f=r,d={},p=0;for(let n=0;n{var{x:t,y:r,strategy:i}=e,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Wo(e,t,n,r,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,i)}function $o(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Wo(o,r,i,a,s,"next",e)}function s(e){Wo(o,r,i,a,s,"throw",e)}a(void 0)})}}function Ko(e,t){for(var n=0;n{var[n,r]=e;t.searchParams.append(n,r)}),yield fetch(t,{method:"GET",headers:ii.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:ii.session})}},{key:"create",value:(i=ea(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(ii.business.id)},body:e});return new me(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:ii.headers,body:JSON.stringify({session:ii.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return U.endpoint("public/webchats/:id/messages")}}],n&&ta(t.prototype,n),r&&ta(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();const ia=ra;function oa(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),{type:r,message:i}=n;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(U.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&oa(t.prototype,n),r&&oa(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function ca(e,t){for(var n=0;nr.handleSubscriptionConfirmed(e)),r.subscribe(),r}return t=a,(n=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){ua(fa(a.prototype),"onMessage",this).call(this,t=>{"message"===t.type&&e(t)})}},{key:"onReaction",value:function(e){ua(fa(a.prototype),"onMessage",this).call(this,t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)})}},{key:"onTypingStart",value:function(e){ua(fa(a.prototype),"onMessage",this).call(this,t=>{"started_typing"===t.type&&e(t)})}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&ca(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),a}(sa);const pa=da;var ma=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},ga=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ya=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function va(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function ba(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var{data:t}=e,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(u=Ta(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:ii.session}),{next:t,messages:n}=yield e.json();this.nextPageValue=t,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,n.forEach(e=>{var{body:t,attachments:n}=e,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),tr(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return u.apply(this,arguments)})},{key:"onClickOutside",value:function(e){N.mode===L.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),ii.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),ii.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var{message:t,reaction:n,type:r}=e,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{id:r,body:i,attachments:o,teaser:a}=e,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var c=this.messageTemplateTarget.cloneNode(!0);c.classList.add("hellotext--webchat-message"),c.style.display="flex",tr(c.querySelector("[data-body]"),i),c.setAttribute("data-id",r),c.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(c,s),this.localizeMessageTimestamp(c.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(c))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(c),ii.eventEmitter.dispatch("webchat:message:received",ba(ba({},e),{},{body:c.querySelector("[data-body]").innerText})),!1!==n.scroll&&c.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(l=Ta(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),{messages:n=[]}=yield t.json();n.forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return l.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return er(e,Qn)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),ii.eventEmitter.dispatch("webchat:message:received",ba(ba({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=Ta(function*(e){var t,n,{detail:{id:r,product:i,buttonId:o,body:a,cardElement:s}}=e;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",a),r&&c.append("message[replied_to]",r),i&&c.append("message[product]",i),o&&c.append("message[button]",o),c.append("session",ii.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var l,u=this.buildMessageElement(),h=null==s||null===(n=s.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);u.querySelector("[data-body]").innerText=a,h&&(h.removeAttribute("width"),h.removeAttribute("height"),null===(l=this.messageAttachmentsContainer(u))||void 0===l||l.appendChild(h)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(u,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(u),u.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:u.outerHTML});var f=yield this.messagesAPI.create(c);if(f.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(f,u);var d=yield f.json();this.dispatch("set:id",{target:u,detail:d.id}),this.localizeMessageTimestamp(u.querySelector("[data-message-timestamp]"),d.created_at||d.createdAt),this.clearRevealedOpeningSequenceMessageIds();var p={id:d.id,body:a,attachments:h?[h.src]:[],replied_to:r,product:i,button:o,type:"quick_reply"};ii.eventEmitter.dispatch("webchat:message:sent",p)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(s=Ta(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",ii.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var c=this.buildMessageElement();c.querySelector("[data-body]").innerText=o,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));var l=yield this.messagesAPI.create(s);if(l.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(l,c);var u=yield l.json();c.setAttribute("data-id",u.id),this.localizeMessageTimestamp(c.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),ii.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return s.apply(this,arguments)})},{key:"sendMessage",value:(a=Ta(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",ii.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),ii.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return a.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var{target:t}=e,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){var{target:t}=e;t.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(o=Ta(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return o.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(i=Ta(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,c=null!=t&&t.clone?t.clone():t,l=yield null==c||null===(s=c.text)||void 0===s?void 0:s.call(c);return this.messageFailureReasonFromText(l)||n}catch(e){return n}}),function(e){return i.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i,o,a;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(i=r[0])||void 0===i?void 0:i.message,null===(o=e.errors)||void 0===o||null===(a=o[0])||void 0===a?void 0:a.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var{currentTarget:t}=e,n=t.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==n.dataset.name),this.attachmentInputTarget.value="",n.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var{detail:t}=e,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var{moveCursorToEnd:e=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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){var t=this.inputTarget.value.length;this.inputTarget.setSelectionRange(t,t)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[Vo(this.offsetValue),Uo({padding:this.paddingValue}),zo()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ja.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],r=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,Aa)}catch(e){return new Intl.DateTimeFormat(void 0,Aa)}}}],n&&Sa(t.prototype,n),r&&Sa(t,r),Object.defineProperty(t,"prototype",{writable:!1}),p}(y.xI);Ma.messageTimestampFormatters={},Ma.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},Ma.classes=["fadeOut"],Ma.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"];var _a=y.lg.start();_a.register("hellotext--form",hi),_a.register("hellotext--webchat",Ma),_a.register("hellotext--webchat--emoji",Xo),_a.register("hellotext--message",bi),window.Hellotext=ii;const Ia=ii},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}},72(e){var t=[];function n(e){for(var n=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},113(e){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,c;if(void 0!==o){const e=document.getElementsByTagName("script");for(var l=0;l{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),c&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,c=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,i[1](s)}};n.l(a,c,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,c,l=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);l(()=>{"use strict";var e={891(e,t,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class U{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class q{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new U(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 q(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new q(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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>gs});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function q(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=q(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=q(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=q(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=U.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=U,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(Fe({session:Ei.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=qe;function We(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function $e(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){We(o,r,i,a,s,"next",e)}function s(e){We(o,r,i,a,s,"throw",e)}a(void 0)})}}function Ke(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Xe(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xe(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ei.headers}),r=yield n.json();return Ei.business.data||(Ei.business.setData(r.business),Ei.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ze(o,r,i,a,s,"next",e)}function s(e){Ze(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&Qe(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const nt=tt;function rt(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function it(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){rt(o,r,i,a,s,"next",e)}function s(e){rt(o,r,i,a,s,"throw",e)}a(void 0)})}}function ot(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ei.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){pt(o,r,i,a,s,"next",e)}function s(e){pt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&dt(e.prototype,null),t&&dt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const yt=mt;function gt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(St,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(St,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&xt(e.prototype,t),n&&xt(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function Ct(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return jt(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jt(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));At.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(At.get("hello_utm"))||{}}catch(e){return{}}}}],t&&_t(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new It,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Lt(t.prototype,n),r&&Lt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Dt;Bt(this,Ht)[Ht]=e,Bt(this,qt)[qt]=new ye,this.session=Bt(this,qt)[qt].session||Z.session||At.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Rt(e.prototype,null),t&&Rt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function $t(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ei.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const rn=Object.entries,on=Object.setPrototypeOf,an=Object.isFrozen,sn=Object.getPrototypeOf,ln=Object.getOwnPropertyDescriptor;let cn=Object.freeze,un=Object.seal,hn=Object.create,pn="undefined"!=typeof Reflect&&Reflect,dn=pn.apply,fn=pn.construct;cn||(cn=function(e){return e}),un||(un=function(e){return e}),dn||(dn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:On;if(on&&on(e,null),!wn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(an(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Fn(e){for(let t=0;t/g),er=un(/\${[\w\W]*/g),tr=un(/^data-[\-\w.\u00B7-\uFFFF]+$/),nr=un(/^aria-[\-\w]+$/),rr=un(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ir=un(/^(?:\w+script|data):/i),or=un(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ar=un(/^html$/i),sr=un(/^[a-z][.\w]*(-[.\w]+)+$/i),lr=un(/<[/\w!]/g),cr=un(/<[/\w]/g),ur=un(/<\/no(script|embed|frames)/i),hr=un(/\/>/i),pr=function(){return"undefined"==typeof window?null:window},dr=function(e,t,n,r){return _n(e,t)&&wn(e[t])?Rn(r.base?Bn(r.base):{},e[t],r.transform):n};var fr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:pr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=Vn(p,"cloneNode"),f=Vn(p,"remove"),m=Vn(p,"nextSibling"),y=Vn(p,"childNodes"),g=Vn(p,"parentNode"),v=Vn(p,"shadowRoot"),b=Vn(p,"attributes"),w=s&&s.prototype?Vn(s.prototype,"nodeType"):null,O=s&&s.prototype?Vn(s.prototype,"nodeName"):null,T=s&&s.prototype?Vn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Ln('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof rn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=Zn,F=Qn,B=er,V=tr,z=nr,U=ir,q=or,H=sr;let W=rr,$=null;const K=Rn({},[...zn,...Un,...qn,...Wn,...Kn]);let G=null;const J=Rn({},[...Gn,...Jn,...Yn,...Xn]);let Y=Object.seal(hn(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}})),X=null,Z=null;const Q=Object.seal(hn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Rn({},["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 Te=null;const xe=Rn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Rn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Rn({},[Ee,Ce,Pe],Tn),Ie=cn(["mi","mo","mn","ms","mtext"]);let Le=Rn({},Ie);const Ne=cn(["annotation-xml"]);let De=Rn({},Ne);const Re=Rn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const Ue=r.createElement("form"),qe=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Bn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Tn:On,$=dr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=dr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=dr(e,"ALLOWED_NAMESPACES",Me,{transform:Tn}),ke=dr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=dr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=dr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=dr(e,"FORBID_TAGS",Bn({}),{transform:Ve}),Z=dr(e,"FORBID_ATTR",Bn({}),{transform:Ve}),be=!!_n(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Bn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return In(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:rr,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=_n(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Bn(e.MATHML_TEXT_INTEGRATION_POINTS):Rn({},Ie),De=_n(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Bn(e.HTML_INTEGRATION_POINTS):Rn({},Ne);const t=_n(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Bn(e.CUSTOM_ELEMENT_HANDLING):hn(null);if(Y=hn(null),_n(t,"tagNameCheck")&&qe(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),_n(t,"attributeNameCheck")&&qe(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),_n(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),un(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Rn({},Kn),G=hn(null),!0===be.html&&(Rn($,zn),Rn(G,Gn)),!0===be.svg&&(Rn($,Un),Rn(G,Jn),Rn(G,Xn)),!0===be.svgFilters&&(Rn($,qn),Rn(G,Jn),Rn(G,Xn)),!0===be.mathMl&&(Rn($,Wn),Rn(G,Yn),Rn(G,Xn))),Q.tagCheck=null,Q.attributeCheck=null,_n(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:wn(e.ADD_TAGS)&&($===K&&($=Bn($)),Rn($,e.ADD_TAGS,Ve))),_n(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:wn(e.ADD_ATTR)&&(G===J&&(G=Bn(G)),Rn(G,e.ADD_ATTR,Ve))),_n(e,"ADD_URI_SAFE_ATTR")&&wn(e.ADD_URI_SAFE_ATTR)&&Rn(ke,e.ADD_URI_SAFE_ATTR,Ve),_n(e,"FORBID_CONTENTS")&&wn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.FORBID_CONTENTS,Ve)),_n(e,"ADD_FORBID_CONTENTS")&&wn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Rn($,["html","head","body"]),$.table&&(Rn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));cn&&cn(e),ze=e},We=Rn({},[...Un,...qn,...Hn]),$e=Rn({},[...Wn,...$n]),Ke=function(e){vn(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Ln("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];mn(t,t=>{vn(e,t)}),mn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{vn(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){vn(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=xn(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=kn(e,R," "),e=kn(e,F," "),kn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&mn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&mn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Bn(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&In(lr,e.textContent)&&In(lr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!In(cr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=On(e.tagName),r=On(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&In(ur,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(vn(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in Ue))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&In(V,t));else if(ee&&In(z,t));else if(i){if(ke[t]);else if(In(W,kn(n,q,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Sn(n,"data:")||!Te[e])if(ne&&!In(U,kn(n,q,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&In(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Rn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[On(e)]&&In(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):gn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:En(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Sn(h,ye)||(Je(a,e),h=ye+h),oe&&In(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&xn(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&In(hr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return Cn(e);case"boolean":return Pn(e);case"bigint":return An?An(e):"0";case"symbol":return jn?jn(e):"Symbol()";case"undefined":default:return Mn(e);case"function":case"object":{if(null===e)return Mn(e);const t=e,n=Vn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Mn(e)}return Mn(e)}}}(e)))throw Ln("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Bn($)),D.uponSanitizeAttribute.length>0&&(G=Bn(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&In(cr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Ln("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Ln("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),mn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return mn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&In(ar,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&_n(D,e)&&vn(D[e],t)},n.removeHook=function(e,t){if(_n(D,e)){if(void 0!==t){const n=yn(D[e],t);return-1===n?void 0:bn(D[e],n,1)[0]}return gn(D[e])}},n.removeHooks=function(e){_n(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),mr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},yr={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function gr(e,t){var n=fr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function vr(e,t){e.replaceChildren(function(e){return gr(e,mr)}(t))}function br(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wr(e,t,n){return(t=xr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Or(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Tr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,Cr,{value:Ar}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ei.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ei.business.features.white_label||this.element.prepend(en.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Or(o,r,i,a,s,"next",e)}function s(e){Or(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-header]","header");vr(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-inputs]","main");e.map(e=>Gt.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)}},{key:"buildButton",value:function(e){var t=kr(this,Cr)[Cr]("[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)}},{key:"buildFooter",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-footer]","footer");vr(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ei.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Tr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Ar(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function jr(e){var t="function"==typeof Map?new Map:void 0;return jr=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(_r())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Mr(i,n.prototype),i}(e,arguments,Ir(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Mr(n,e)},jr(e)}function _r(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_r=function(){return!!e})()}function Mr(e,t){return Mr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Mr(e,t)}function Ir(e){return Ir=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ir(e)}var Lr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Ir(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,_r()?Reflect.construct(t,n||[],Ir(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Mr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(jr(Error));function Nr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Dr(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ei.notInitialized)throw new Lr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,Vr)[Vr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ei.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Nr(o,r,i,a,s,"next",e)}function s(e){Nr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ei.business.data||(Ei.business.setData(e.business),Ei.business.setLocale(j.toString())),Ei.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 Pr(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Dr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Ur(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function qr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Hr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){qr(o,r,i,a,s,"next",e)}function s(e){qr(o,r,i,a,s,"throw",e)}a(void 0)})}}function Wr(e,t){for(var n=0;ndi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=di(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function fi(e,t){var n=di(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function mi(){return(mi=ci(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var yi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=ci(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return mi.apply(this,arguments)}(fi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&si(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function gi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new Et(e),this.page=new Dt,Z.assign(t),Wt.initialize(this.page),this.forms=new zr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Kr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield Zr.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ri.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=bi({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return gi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Ti(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Lr;var n=bi(bi({},t&&t.headers||{}),this.headers),r=bi(bi({},ai.identificationData),t.user_parameters||{}),i=t&&t.url?new Dt(t.url):this.page,o=bi(bi({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield wt.events.create({headers:n,body:o,keepalive:bt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Ti(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield yi.generate(this.session,e,n);if(yi.matches(ai.fingerprint,r))return new ke(!0,{json:(t=Ti(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield wt.identifications.create(bi({user_id:e},n));return i.succeeded&&ai.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ai.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Wt.session}},{key:"isInitialized",get:function(){return void 0!==Wt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Lr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&xi(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Si.eventEmitter=new ce,Si.forms=void 0,Si.business=void 0,Si.popup=void 0,Si.webchat=void 0,Si.whatsapp=void 0;const Ei=Si;function Ci(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Pi(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ei.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){Ci(o,n,r,a,s,"next",e)}function s(e){Ci(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ei.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&Pi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Di(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ri(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Bi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function $i(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Ki(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$i(o,r,i,a,s,"next",e)}function s(e){$i(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gi(e,t){for(var n=0;n{e.disabled=!0});var t=yield wt.popups.submit(this.idValue,this.submissionPayload());this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed?yield this.handleSubmissionError(t):this.showCompleted()}else this.showErrorMessages(this.currentStepInputs)}),function(e){return o.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.showElement(this.completedTarget)}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Ki(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Gi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a}(g.xI);eo.targets=["bubble","dialog","step","completed","input","submitButton"],eo.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const to=["start","end"],no=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+to[0],t+"-"+to[1]),[]),ro=Math.min,io=Math.max,oo=Math.round,ao=Math.floor,so=e=>({x:e,y:e}),lo={left:"right",right:"left",bottom:"top",top:"bottom"};function co(e,t){return"function"==typeof e?e(t):e}function uo(e){return e.split("-")[0]}function ho(e){return e.split("-")[1]}function po(e){return"x"===e?"y":"x"}function fo(e){return"y"===e?"height":"width"}function mo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function yo(e){return po(mo(e))}function go(e,t,n){void 0===n&&(n=!1);const r=ho(e),i=yo(e),o=fo(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=xo(a)),[a,xo(a)]}function vo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const bo=["left","right"],wo=["right","left"],Oo=["top","bottom"],To=["bottom","top"];function xo(e){const t=uo(e);return lo[t]+e.slice(t.length)}function ko(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function So(e,t,n){let{reference:r,floating:i}=e;const o=mo(t),a=yo(t),s=fo(a),l=uo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=ho(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Eo(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=co(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=ko(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=ko(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const Co=new Set(["left","top"]);function Po(){return"undefined"!=typeof window}function Ao(e){return Mo(e)?(e.nodeName||"").toLowerCase():"#document"}function jo(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function _o(e){var t;return null==(t=(Mo(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Mo(e){return!!Po()&&(e instanceof Node||e instanceof jo(e).Node)}function Io(e){return!!Po()&&(e instanceof Element||e instanceof jo(e).Element)}function Lo(e){return!!Po()&&(e instanceof HTMLElement||e instanceof jo(e).HTMLElement)}function No(e){return!(!Po()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof jo(e).ShadowRoot)}function Do(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=$o(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Ro(e){return/^(table|td|th)$/.test(Ao(e))}function Fo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Bo=/transform|translate|scale|rotate|perspective|filter/,Vo=/paint|layout|strict|content/,zo=e=>!!e&&"none"!==e;let Uo;function qo(e){const t=Io(e)?$o(e):e;return zo(t.transform)||zo(t.translate)||zo(t.scale)||zo(t.rotate)||zo(t.perspective)||!Ho()&&(zo(t.backdropFilter)||zo(t.filter))||Bo.test(t.willChange||"")||Vo.test(t.contain||"")}function Ho(){return null==Uo&&(Uo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Uo}function Wo(e){return/^(html|body|#document)$/.test(Ao(e))}function $o(e){return jo(e).getComputedStyle(e)}function Ko(e){return Io(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Go(e){if("html"===Ao(e))return e;const t=e.assignedSlot||e.parentNode||No(e)&&e.host||_o(e);return No(t)?t.host:t}function Jo(e){const t=Go(e);return Wo(t)?(e.ownerDocument||e).body:Lo(t)&&Do(t)?t:Jo(t)}function Yo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Jo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=jo(i);if(o){const e=Xo(a);return t.concat(a,a.visualViewport||[],Do(i)?i:[],e&&n?Yo(e):[])}return t.concat(i,Yo(i,[],n))}function Xo(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Zo(e){const t=$o(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Lo(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=oo(n)!==o||oo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function Qo(e){return Io(e)?e:e.contextElement}function ea(e){const t=Qo(e);if(!Lo(t))return so(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Zo(t);let a=(o?oo(n.width):n.width)/r,s=(o?oo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ta=so(0);function na(e){const t=jo(e);return Ho()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ta}function ra(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=Qo(e);let a=so(1);t&&(r?Io(r)&&(a=ea(r)):a=ea(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===jo(e)}(o,n,r)?na(o):so(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=jo(o),t=Io(r)?jo(r):r;let n=e,i=Xo(n);for(;i&&t!==n;){const e=ea(i),t=i.getBoundingClientRect(),r=$o(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=jo(i),i=Xo(n)}}return ko({width:u,height:h,x:l,y:c})}function ia(e,t){const n=Ko(e).scrollLeft;return t?t.left+n:ra(_o(e)).left+n}function oa(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ia(e,n),y:n.top+t.scrollTop}}function aa(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=jo(e),o=_o(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ho()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(ia(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Ko(e),n=e.ownerDocument.body,r=io(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=io(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+ia(e);const a=-t.scrollTop;return"rtl"===$o(n).direction&&(o+=io(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(_o(e));else if(Io(t))r=function(e,t){const n=ra(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ea(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=na(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ko(r)}function sa(e,t,n){const r=Lo(t),i=_o(t),o="fixed"===n,a=ra(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=so(0);if((r||!o)&&(("body"!==Ao(t)||Do(i))&&(s=Ko(t)),r)){const e=ra(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=ia(i));const c=!i||r||o?so(0):oa(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function la(e){return"static"===$o(e).position}function ca(e,t){if(!Lo(e)||"fixed"===$o(e).position)return null;if(t)return t(e);let n=e.offsetParent;return _o(e)===n&&(n=n.ownerDocument.body),n}function ua(e,t){const n=jo(e);if(Fo(e))return n;if(!Lo(e)){let t=Go(e);for(;t&&!Wo(t);){if(Io(t)&&!la(t))return t;t=Go(t)}return n}let r=ca(e,t);for(;r&&Ro(r)&&la(r);)r=ca(r,t);return r&&Wo(r)&&la(r)&&!qo(r)?n:r||function(e){let t=Go(e);for(;Lo(t)&&!Wo(t);){if(qo(t))return t;if(Fo(t))return null;t=Go(t)}return null}(e)||n}const ha={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=_o(r),s=!!t&&Fo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=so(1);const u=so(0),h=Lo(r);if((h||!o)&&(("body"!==Ao(r)||Do(a))&&(l=Ko(r)),h)){const e=ra(r);c=ea(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?so(0):oa(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:_o,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?Fo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Yo(e,[],!1).filter(e=>Io(e)&&"body"!==Ao(e)),i=null;const o="fixed"===$o(e).position;let a=o?Go(e):e;for(;Io(a)&&!Wo(a);){const e=$o(a),t=qo(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Go(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=aa(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;eho(t)===e),...n.filter(t=>ho(t)!==e)]:n.filter(e=>uo(e)===e)).filter(n=>!e||ho(n)===e||!!t&&vo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=go(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[uo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=ho(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,ho(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},ma=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=co(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=mo(i),d=po(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],io(n,ro(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ya=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=co(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=uo(i),v=mo(s),b=uo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[xo(s)]:function(e){const t=xo(e);return[vo(e),t,vo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=ho(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?wo:bo:t?bo:wo;case"left":case"right":return t?Oo:To;default:return[]}}(uo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(vo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=go(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===mo(t)||E.every(e=>mo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=mo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var ga=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=Qo(e),u=i||o?[...c?Yo(c):[],...t?Yo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=_o(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-ao(h)+"px "+-ao(o.clientWidth-(u+p))+"px "+-ao(o.clientHeight-(h+d))+"px "+-ao(u)+"px",threshold:io(0,ro(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!pa(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=jo(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?ra(e):null;return l&&function t(){const r=ra(e);m&&!pa(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...ha,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Eo},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=So(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function va(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ja(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ja(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ei.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ei.session})}},{key:"create",value:(i=Ma(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ei.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ei.headers,body:JSON.stringify({session:Ei.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Ia(t.prototype,n),r&&Ia(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Da=Na;function Ra(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Ra(t.prototype,n),r&&Ra(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Va(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ka(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ha(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ha(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ha(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&Va(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ba);const Ja=Ga;var Ya=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},Xa=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},Za=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function Qa(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function es(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=rs(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ei.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),vr(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){U.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ei.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ei.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",vr(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=rs(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return gr(e,yr)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=rs(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ei.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ei.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=rs(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ei.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=rs(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ei.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=rs(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=rs(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[da(this.offsetValue),ma({padding:this.paddingValue}),ya()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ds.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ps)}catch(e){return new Intl.DateTimeFormat(void 0,ps)}}}],r&&is(n.prototype,r),i&&is(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);ms.messageTimestampFormatters={},ms.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},ms.classes=["fadeOut"],ms.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"];var ys=g.lg.start();ys.register("hellotext--form",Ni),ys.register("hellotext--popup",eo),ys.register("hellotext--webchat",ms),ys.register("hellotext--webchat--emoji",Aa),ys.register("hellotext--message",Wi),window.Hellotext=Ei;const gs=Ei},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Configuration } from '../../core'; import Hellotext from '../../hellotext'; import { Response } from '../response'; @@ -13,13 +19,15 @@ var WebchatMessagesAPI = /*#__PURE__*/function () { _classCallCheck(this, WebchatMessagesAPI); this.webchatId = webchatId; } - _createClass(WebchatMessagesAPI, [{ + return _createClass(WebchatMessagesAPI, [{ key: "index", value: function () { var _index = _asyncToGenerator(function* (params) { var url = new URL(this.url); Object.entries(params).forEach(_ref => { - var [key, value] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; url.searchParams.append(key, value); }); return yield fetch(url, { @@ -82,6 +90,5 @@ var WebchatMessagesAPI = /*#__PURE__*/function () { return Configuration.endpoint("public/webchats/:id/messages"); } }]); - return WebchatMessagesAPI; }(); export default WebchatMessagesAPI; \ No newline at end of file diff --git a/lib/api/webchats.cjs b/lib/api/webchats.cjs index b6789f02..471dd17b 100644 --- a/lib/api/webchats.cjs +++ b/lib/api/webchats.cjs @@ -6,17 +6,17 @@ Object.defineProperty(exports, "__esModule", { exports.default = void 0; var _core = require("../core"); var _hellotext = _interopRequireDefault(require("../hellotext")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } let WebchatsAPI = /*#__PURE__*/function () { function WebchatsAPI() { _classCallCheck(this, WebchatsAPI); } - _createClass(WebchatsAPI, null, [{ + return _createClass(WebchatsAPI, null, [{ key: "endpoint", get: function () { return _core.Configuration.endpoint('public/webchats'); @@ -63,7 +63,5 @@ let WebchatsAPI = /*#__PURE__*/function () { url.searchParams.append(key, String(value)); } }]); - return WebchatsAPI; }(); -var _default = WebchatsAPI; -exports.default = _default; \ No newline at end of file +var _default = exports.default = WebchatsAPI; \ No newline at end of file diff --git a/lib/api/webchats.js b/lib/api/webchats.js index b68c93f2..418938e5 100644 --- a/lib/api/webchats.js +++ b/lib/api/webchats.js @@ -1,17 +1,23 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Configuration, Locale } from '../core'; import Hellotext from '../hellotext'; var WebchatsAPI = /*#__PURE__*/function () { function WebchatsAPI() { _classCallCheck(this, WebchatsAPI); } - _createClass(WebchatsAPI, null, [{ + return _createClass(WebchatsAPI, null, [{ key: "endpoint", get: function get() { return Configuration.endpoint('public/webchats'); @@ -24,7 +30,9 @@ var WebchatsAPI = /*#__PURE__*/function () { url.searchParams.append('session', Hellotext.session); url.searchParams.append('locale', Locale.toString()); Object.entries(Configuration.webchat.style).forEach(_ref => { - var [key, value] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; url.searchParams.append("style[".concat(key, "]"), value); }); this.appendWebchatOverrides(url); @@ -49,10 +57,9 @@ var WebchatsAPI = /*#__PURE__*/function () { key: "appendWebchatOverrides", value: function appendWebchatOverrides(url) { var _appearance$header, _appearance$launcher; - var { - appearance, - whatsapp - } = Configuration.webchat; + var _Configuration$webcha = Configuration.webchat, + appearance = _Configuration$webcha.appearance, + whatsapp = _Configuration$webcha.whatsapp; this.appendIfSupplied(url, 'webchat[appearance][header][name]', (_appearance$header = appearance.header) === null || _appearance$header === void 0 ? void 0 : _appearance$header.name); this.appendIfSupplied(url, 'webchat[appearance][launcher][icon_url]', (_appearance$launcher = appearance.launcher) === null || _appearance$launcher === void 0 ? void 0 : _appearance$launcher.iconUrl); this.appendIfSupplied(url, 'webchat[handoff][identifier]', whatsapp.number); @@ -65,6 +72,5 @@ var WebchatsAPI = /*#__PURE__*/function () { url.searchParams.append(key, String(value)); } }]); - return WebchatsAPI; }(); export default WebchatsAPI; \ No newline at end of file diff --git a/lib/api/whatsapp_widgets.cjs b/lib/api/whatsapp_widgets.cjs index edc4098e..223dc35c 100644 --- a/lib/api/whatsapp_widgets.cjs +++ b/lib/api/whatsapp_widgets.cjs @@ -6,17 +6,17 @@ Object.defineProperty(exports, "__esModule", { exports.default = void 0; var _core = require("../core"); var _hellotext = _interopRequireDefault(require("../hellotext")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } let WhatsAppWidgetsAPI = /*#__PURE__*/function () { function WhatsAppWidgetsAPI() { _classCallCheck(this, WhatsAppWidgetsAPI); } - _createClass(WhatsAppWidgetsAPI, null, [{ + return _createClass(WhatsAppWidgetsAPI, null, [{ key: "endpoint", get: function () { return _core.Configuration.endpoint('public/widgets/whatsapp'); @@ -81,7 +81,5 @@ let WhatsAppWidgetsAPI = /*#__PURE__*/function () { } } }]); - return WhatsAppWidgetsAPI; }(); -var _default = WhatsAppWidgetsAPI; -exports.default = _default; \ No newline at end of file +var _default = exports.default = WhatsAppWidgetsAPI; \ No newline at end of file diff --git a/lib/api/whatsapp_widgets.js b/lib/api/whatsapp_widgets.js index 8099da61..fbdca012 100644 --- a/lib/api/whatsapp_widgets.js +++ b/lib/api/whatsapp_widgets.js @@ -1,17 +1,17 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Configuration, Locale } from '../core'; import Hellotext from '../hellotext'; var WhatsAppWidgetsAPI = /*#__PURE__*/function () { function WhatsAppWidgetsAPI() { _classCallCheck(this, WhatsAppWidgetsAPI); } - _createClass(WhatsAppWidgetsAPI, null, [{ + return _createClass(WhatsAppWidgetsAPI, null, [{ key: "endpoint", get: function get() { return Configuration.endpoint('public/widgets/whatsapp'); @@ -43,11 +43,10 @@ var WhatsAppWidgetsAPI = /*#__PURE__*/function () { key: "appendWhatsAppOverrides", value: function appendWhatsAppOverrides(url) { var _appearance$launcher; - var { - appearance, - body, - number - } = Configuration.whatsapp; + var _Configuration$whatsa = Configuration.whatsapp, + appearance = _Configuration$whatsa.appearance, + body = _Configuration$whatsa.body, + number = _Configuration$whatsa.number; this.appendIfSupplied(url, 'whatsapp[appearance][launcher][icon_url]', (_appearance$launcher = appearance.launcher) === null || _appearance$launcher === void 0 ? void 0 : _appearance$launcher.iconUrl); this.appendIfSupplied(url, 'whatsapp[number]', number); this.appendIfSupplied(url, 'whatsapp[body]', body); @@ -94,6 +93,5 @@ var WhatsAppWidgetsAPI = /*#__PURE__*/function () { return parseWidgetResponse; }() }]); - return WhatsAppWidgetsAPI; }(); export default WhatsAppWidgetsAPI; \ No newline at end of file diff --git a/lib/builders/input_builder.cjs b/lib/builders/input_builder.cjs index 8352f45c..dacd5091 100644 --- a/lib/builders/input_builder.cjs +++ b/lib/builders/input_builder.cjs @@ -5,17 +5,17 @@ Object.defineProperty(exports, "__esModule", { }); exports.InputBuilder = void 0; var _hellotext = _interopRequireDefault(require("../hellotext")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let InputBuilder = /*#__PURE__*/function () { +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let InputBuilder = exports.InputBuilder = /*#__PURE__*/function () { function InputBuilder() { _classCallCheck(this, InputBuilder); } - _createClass(InputBuilder, null, [{ + return _createClass(InputBuilder, null, [{ key: "build", value: function build(data) { const article = document.createElement('article'); @@ -56,6 +56,4 @@ let InputBuilder = /*#__PURE__*/function () { return article; } }]); - return InputBuilder; -}(); -exports.InputBuilder = InputBuilder; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/builders/input_builder.js b/lib/builders/input_builder.js index 4b975dc8..493e6885 100644 --- a/lib/builders/input_builder.js +++ b/lib/builders/input_builder.js @@ -1,14 +1,14 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import Hellotext from '../hellotext'; var InputBuilder = /*#__PURE__*/function () { function InputBuilder() { _classCallCheck(this, InputBuilder); } - _createClass(InputBuilder, null, [{ + return _createClass(InputBuilder, null, [{ key: "build", value: function build(data) { var article = document.createElement('article'); @@ -49,6 +49,5 @@ var InputBuilder = /*#__PURE__*/function () { return article; } }]); - return InputBuilder; }(); export { InputBuilder }; \ No newline at end of file diff --git a/lib/builders/logo_builder.cjs b/lib/builders/logo_builder.cjs index e2806d31..d747d87a 100644 --- a/lib/builders/logo_builder.cjs +++ b/lib/builders/logo_builder.cjs @@ -5,21 +5,21 @@ Object.defineProperty(exports, "__esModule", { }); exports.LogoBuilder = void 0; var _hellotext = _interopRequireDefault(require("../hellotext")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } var _template = /*#__PURE__*/_classPrivateFieldLooseKey("template"); -let LogoBuilder = /*#__PURE__*/function () { +let LogoBuilder = exports.LogoBuilder = /*#__PURE__*/function () { function LogoBuilder() { _classCallCheck(this, LogoBuilder); } - _createClass(LogoBuilder, null, [{ + return _createClass(LogoBuilder, null, [{ key: "build", value: function build() { const container = document.createElement('div'); @@ -27,9 +27,7 @@ let LogoBuilder = /*#__PURE__*/function () { return container.firstElementChild; } }]); - return LogoBuilder; }(); -exports.LogoBuilder = LogoBuilder; function _template2() { const url = `https://www.hellotext.com?hello_session=${_hellotext.default.session}`; return ` diff --git a/lib/builders/logo_builder.js b/lib/builders/logo_builder.js index f00b8fd0..80ef3f37 100644 --- a/lib/builders/logo_builder.js +++ b/lib/builders/logo_builder.js @@ -1,18 +1,18 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } import Hellotext from '../hellotext'; var _template = /*#__PURE__*/_classPrivateFieldLooseKey("template"); var LogoBuilder = /*#__PURE__*/function () { function LogoBuilder() { _classCallCheck(this, LogoBuilder); } - _createClass(LogoBuilder, null, [{ + return _createClass(LogoBuilder, null, [{ key: "build", value: function build() { var container = document.createElement('div'); @@ -20,7 +20,6 @@ var LogoBuilder = /*#__PURE__*/function () { return container.firstElementChild; } }]); - return LogoBuilder; }(); function _template2() { var url = "https://www.hellotext.com?hello_session=".concat(Hellotext.session); diff --git a/lib/channels/application_channel.cjs b/lib/channels/application_channel.cjs index 6345c581..e5ba31cc 100644 --- a/lib/channels/application_channel.cjs +++ b/lib/channels/application_channel.cjs @@ -5,17 +5,17 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; var _core = require("../core"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } let ApplicationChannel = /*#__PURE__*/function () { function ApplicationChannel() { _classCallCheck(this, ApplicationChannel); ApplicationChannel.channels.add(this); } - _createClass(ApplicationChannel, [{ + return _createClass(ApplicationChannel, [{ key: "send", value: function send({ command, @@ -186,7 +186,6 @@ let ApplicationChannel = /*#__PURE__*/function () { return delay + jitter; } }]); - return ApplicationChannel; }(); ApplicationChannel.webSocket = void 0; ApplicationChannel.channels = new Set(); @@ -199,5 +198,4 @@ ApplicationChannel.reconnectBaseDelay = 500; ApplicationChannel.reconnectMaxDelay = 10000; ApplicationChannel.reconnectJitter = 0.3; ApplicationChannel.needsResubscribe = false; -var _default = ApplicationChannel; -exports.default = _default; \ No newline at end of file +var _default = exports.default = ApplicationChannel; \ No newline at end of file diff --git a/lib/channels/application_channel.js b/lib/channels/application_channel.js index cc2c2428..ab0f0bdf 100644 --- a/lib/channels/application_channel.js +++ b/lib/channels/application_channel.js @@ -1,22 +1,20 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Configuration } from '../core'; var ApplicationChannel = /*#__PURE__*/function () { function ApplicationChannel() { _classCallCheck(this, ApplicationChannel); ApplicationChannel.channels.add(this); } - _createClass(ApplicationChannel, [{ + return _createClass(ApplicationChannel, [{ key: "send", value: function send(_ref) { - var { - command, - identifier, - data - } = _ref; + var command = _ref.command, + identifier = _ref.identifier, + data = _ref.data; var payload = { command, identifier: JSON.stringify(identifier), @@ -37,10 +35,8 @@ var ApplicationChannel = /*#__PURE__*/function () { value: function onMessage(callback) { var handler = event => { var data = JSON.parse(event.data); - var { - type, - message - } = data; + var type = data.type, + message = data.message; if (this.ignoredEvents.includes(type)) { return; } @@ -181,7 +177,6 @@ var ApplicationChannel = /*#__PURE__*/function () { return delay + jitter; } }]); - return ApplicationChannel; }(); ApplicationChannel.webSocket = void 0; ApplicationChannel.channels = new Set(); diff --git a/lib/channels/webchat_channel.cjs b/lib/channels/webchat_channel.cjs index 88286aff..090a8810 100644 --- a/lib/channels/webchat_channel.cjs +++ b/lib/channels/webchat_channel.cjs @@ -5,28 +5,27 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; var _application_channel = _interopRequireDefault(require("./application_channel")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } let WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { - _inherits(WebchatChannel, _ApplicationChannel); - var _super = _createSuper(WebchatChannel); function WebchatChannel(id, session, conversation) { var _this; _classCallCheck(this, WebchatChannel); - _this = _super.call(this); + _this = _callSuper(this, WebchatChannel); _this.id = id; _this.session = session; _this.conversation = conversation; @@ -45,7 +44,8 @@ let WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { _this.subscribe(); return _this; } - _createClass(WebchatChannel, [{ + _inherits(WebchatChannel, _ApplicationChannel); + return _createClass(WebchatChannel, [{ key: "subscribe", value: function subscribe() { this.subscribed = true; @@ -155,28 +155,28 @@ let WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { }, { key: "onMessage", value: function onMessage(callback) { - _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + _superPropGet(WebchatChannel, "onMessage", this, 3)([message => { if (message.type !== 'message') return; callback(message); - }); + }]); } }, { key: "onReaction", value: function onReaction(callback) { - _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + _superPropGet(WebchatChannel, "onMessage", this, 3)([message => { if (message.type === 'reaction.create' || message.type === 'reaction.destroy') { callback(message); } - }); + }]); } }, { key: "onTypingStart", value: function onTypingStart(callback) { - _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + _superPropGet(WebchatChannel, "onMessage", this, 3)([message => { if (message.type === 'started_typing') { callback(message); } - }); + }]); } }, { key: "updateSubscriptionWith", @@ -188,7 +188,5 @@ let WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { }, 1000); } }]); - return WebchatChannel; }(_application_channel.default); -var _default = WebchatChannel; -exports.default = _default; \ No newline at end of file +var _default = exports.default = WebchatChannel; \ No newline at end of file diff --git a/lib/channels/webchat_channel.js b/lib/channels/webchat_channel.js index 00746189..1e84cd48 100644 --- a/lib/channels/webchat_channel.js +++ b/lib/channels/webchat_channel.js @@ -1,25 +1,24 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } import ApplicationChannel from './application_channel'; var WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { - _inherits(WebchatChannel, _ApplicationChannel); - var _super = _createSuper(WebchatChannel); function WebchatChannel(id, session, conversation) { var _this; _classCallCheck(this, WebchatChannel); - _this = _super.call(this); + _this = _callSuper(this, WebchatChannel); _this.id = id; _this.session = session; _this.conversation = conversation; @@ -38,7 +37,8 @@ var WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { _this.subscribe(); return _this; } - _createClass(WebchatChannel, [{ + _inherits(WebchatChannel, _ApplicationChannel); + return _createClass(WebchatChannel, [{ key: "subscribe", value: function subscribe() { this.subscribed = true; @@ -148,28 +148,28 @@ var WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { }, { key: "onMessage", value: function onMessage(callback) { - _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + _superPropGet(WebchatChannel, "onMessage", this, 3)([message => { if (message.type !== 'message') return; callback(message); - }); + }]); } }, { key: "onReaction", value: function onReaction(callback) { - _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + _superPropGet(WebchatChannel, "onMessage", this, 3)([message => { if (message.type === 'reaction.create' || message.type === 'reaction.destroy') { callback(message); } - }); + }]); } }, { key: "onTypingStart", value: function onTypingStart(callback) { - _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + _superPropGet(WebchatChannel, "onMessage", this, 3)([message => { if (message.type === 'started_typing') { callback(message); } - }); + }]); } }, { key: "updateSubscriptionWith", @@ -181,6 +181,5 @@ var WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { }, 1000); } }]); - return WebchatChannel; }(ApplicationChannel); export default WebchatChannel; \ No newline at end of file diff --git a/lib/controllers/form_controller.cjs b/lib/controllers/form_controller.cjs index 1b9794be..448c9615 100644 --- a/lib/controllers/form_controller.cjs +++ b/lib/controllers/form_controller.cjs @@ -9,29 +9,29 @@ var _hellotext = _interopRequireDefault(require("../hellotext")); var _models = require("../models"); var _forms = _interopRequireDefault(require("../api/forms")); var _core = require("../core"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -let _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +let _default = exports.default = /*#__PURE__*/function (_Controller) { function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "initialize", value: function initialize() { this.form = new _models.Form(this.dataValue, this.element); @@ -39,7 +39,7 @@ let _default = /*#__PURE__*/function (_Controller) { }, { key: "connect", value: function connect() { - _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + _superPropGet(_default, "connect", this, 3)([]); this.element.addEventListener('submit', this.submit.bind(this)); if (document.activeElement.tagName !== 'INPUT') { this.inputTargets[0].focus(); @@ -131,9 +131,7 @@ let _default = /*#__PURE__*/function (_Controller) { return !this.element.checkValidity(); } }]); - return _default; }(_stimulus.Controller); -exports.default = _default; _default.values = { data: Object, step: { diff --git a/lib/controllers/form_controller.js b/lib/controllers/form_controller.js index 14be7be2..f2b32455 100644 --- a/lib/controllers/form_controller.js +++ b/lib/controllers/form_controller.js @@ -1,32 +1,32 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } import { Controller } from '@hotwired/stimulus'; import Hellotext from '../hellotext'; import { Form } from '../models'; import FormsAPI from '../api/forms'; import { Configuration } from '../core'; var _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "initialize", value: function initialize() { this.form = new Form(this.dataValue, this.element); @@ -34,7 +34,7 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "connect", value: function connect() { - _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + _superPropGet(_default, "connect", this, 3)([]); this.element.addEventListener('submit', this.submit.bind(this)); if (document.activeElement.tagName !== 'INPUT') { this.inputTargets[0].focus(); @@ -56,10 +56,8 @@ var _default = /*#__PURE__*/function (_Controller) { var data = yield response.json(); if (response.failed) { data.errors.forEach(error => { - var { - type, - parameter - } = error; + var type = error.type, + parameter = error.parameter; var input = this.inputTargets.find(input => input.name === parameter); input.setCustomValidity(Hellotext.business.locale.errors[type]); input.reportValidity(); @@ -132,7 +130,6 @@ var _default = /*#__PURE__*/function (_Controller) { return !this.element.checkValidity(); } }]); - return _default; }(Controller); _default.values = { data: Object, diff --git a/lib/controllers/message_controller.cjs b/lib/controllers/message_controller.cjs index 0ccfbcc0..0096023a 100644 --- a/lib/controllers/message_controller.cjs +++ b/lib/controllers/message_controller.cjs @@ -6,27 +6,26 @@ Object.defineProperty(exports, "__esModule", { exports.default = void 0; var _stimulus = require("@hotwired/stimulus"); var _hellotext = _interopRequireDefault(require("../hellotext")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -let _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +let _default = exports.default = /*#__PURE__*/function (_Controller) { function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "connect", value: function connect() { this.updateFades(); @@ -36,7 +35,7 @@ let _default = /*#__PURE__*/function (_Controller) { key: "disconnect", value: function disconnect() { var _this$resizeObserver; - (_this$resizeObserver = this.resizeObserver) === null || _this$resizeObserver === void 0 ? void 0 : _this$resizeObserver.disconnect(); + (_this$resizeObserver = this.resizeObserver) === null || _this$resizeObserver === void 0 || _this$resizeObserver.disconnect(); } }, { key: "setId", @@ -140,7 +139,6 @@ let _default = /*#__PURE__*/function (_Controller) { if (!firstCard) { return 280; // Fallback to default desktop card width } - const cardWidth = firstCard.offsetWidth; return cardWidth + this.getGap(); } @@ -277,9 +275,7 @@ let _default = /*#__PURE__*/function (_Controller) { fadeTarget.classList.add('hidden'); } }]); - return _default; }(_stimulus.Controller); -exports.default = _default; _default.values = { fadeDistance: { type: Number, diff --git a/lib/controllers/message_controller.js b/lib/controllers/message_controller.js index 4e2ad890..a6f7876b 100644 --- a/lib/controllers/message_controller.js +++ b/lib/controllers/message_controller.js @@ -1,28 +1,27 @@ -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } import { Controller } from '@hotwired/stimulus'; import Hellotext from '../hellotext'; var _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "connect", value: function connect() { this.updateFades(); @@ -32,14 +31,12 @@ var _default = /*#__PURE__*/function (_Controller) { key: "disconnect", value: function disconnect() { var _this$resizeObserver; - (_this$resizeObserver = this.resizeObserver) === null || _this$resizeObserver === void 0 ? void 0 : _this$resizeObserver.disconnect(); + (_this$resizeObserver = this.resizeObserver) === null || _this$resizeObserver === void 0 || _this$resizeObserver.disconnect(); } }, { key: "setId", value: function setId(_ref) { - var { - detail: id - } = _ref; + var id = _ref.detail; this.idValue = id; this.element.id = id; } @@ -51,9 +48,7 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "quickReply", value: function quickReply(_ref2) { - var { - currentTarget - } = _ref2; + var currentTarget = _ref2.currentTarget; var card = currentTarget.closest('[data-hellotext--message-target="carouselCard"]'); var messageElement = currentTarget.closest('[data-controller~="hellotext--message"]'); var body = currentTarget.dataset.text || currentTarget.textContent.trim(); @@ -70,15 +65,12 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "addToCart", value: function addToCart(_ref3) { - var { - currentTarget - } = _ref3; + var currentTarget = _ref3.currentTarget; var card = currentTarget.closest('[data-hellotext--message-target="carouselCard"]'); - var { - id, - reference, - source - } = card.dataset; + var _card$dataset = card.dataset, + id = _card$dataset.id, + reference = _card$dataset.reference, + source = _card$dataset.source; var item = { product: id, quantity: 1 @@ -135,7 +127,6 @@ var _default = /*#__PURE__*/function (_Controller) { if (!firstCard) { return 280; // Fallback to default desktop card width } - var cardWidth = firstCard.offsetWidth; return cardWidth + this.getGap(); } @@ -273,7 +264,6 @@ var _default = /*#__PURE__*/function (_Controller) { fadeTarget.classList.add('hidden'); } }]); - return _default; }(Controller); _default.values = { fadeDistance: { diff --git a/lib/controllers/mixins/usePopover.cjs b/lib/controllers/mixins/usePopover.cjs index b1d5c956..8abc3218 100644 --- a/lib/controllers/mixins/usePopover.cjs +++ b/lib/controllers/mixins/usePopover.cjs @@ -10,7 +10,7 @@ const usePopover = controller => { Object.assign(controller, { show() { var _this$cancelBehaviour; - (_this$cancelBehaviour = this.cancelBehaviourOpen) === null || _this$cancelBehaviour === void 0 ? void 0 : _this$cancelBehaviour.call(this); + (_this$cancelBehaviour = this.cancelBehaviourOpen) === null || _this$cancelBehaviour === void 0 || _this$cancelBehaviour.call(this); this.openValue = true; }, hide() { @@ -18,7 +18,7 @@ const usePopover = controller => { }, toggle() { var _this$cancelBehaviour2; - (_this$cancelBehaviour2 = this.cancelBehaviourOpen) === null || _this$cancelBehaviour2 === void 0 ? void 0 : _this$cancelBehaviour2.call(this); + (_this$cancelBehaviour2 = this.cancelBehaviourOpen) === null || _this$cancelBehaviour2 === void 0 || _this$cancelBehaviour2.call(this); this.openValue = !this.openValue; }, setupFloatingUI({ @@ -49,7 +49,7 @@ const usePopover = controller => { if (this.disabledValue) return; if (this.openValue) { var _this$preparePopoverO; - (_this$preparePopoverO = this.preparePopoverOpenAnimation) === null || _this$preparePopoverO === void 0 ? void 0 : _this$preparePopoverO.call(this); + (_this$preparePopoverO = this.preparePopoverOpenAnimation) === null || _this$preparePopoverO === void 0 || _this$preparePopoverO.call(this); this.popoverTarget.showPopover(); this.popoverTarget.setAttribute('aria-expanded', 'true'); if (this['onPopoverOpened']) { diff --git a/lib/controllers/mixins/usePopover.js b/lib/controllers/mixins/usePopover.js index 14281b92..a3e25548 100644 --- a/lib/controllers/mixins/usePopover.js +++ b/lib/controllers/mixins/usePopover.js @@ -4,7 +4,7 @@ export var usePopover = controller => { Object.assign(controller, { show() { var _this$cancelBehaviour; - (_this$cancelBehaviour = this.cancelBehaviourOpen) === null || _this$cancelBehaviour === void 0 ? void 0 : _this$cancelBehaviour.call(this); + (_this$cancelBehaviour = this.cancelBehaviourOpen) === null || _this$cancelBehaviour === void 0 || _this$cancelBehaviour.call(this); this.openValue = true; }, hide() { @@ -12,26 +12,22 @@ export var usePopover = controller => { }, toggle() { var _this$cancelBehaviour2; - (_this$cancelBehaviour2 = this.cancelBehaviourOpen) === null || _this$cancelBehaviour2 === void 0 ? void 0 : _this$cancelBehaviour2.call(this); + (_this$cancelBehaviour2 = this.cancelBehaviourOpen) === null || _this$cancelBehaviour2 === void 0 || _this$cancelBehaviour2.call(this); this.openValue = !this.openValue; }, setupFloatingUI(_ref) { - var { - trigger, - popover, - strategy - } = _ref; + var trigger = _ref.trigger, + popover = _ref.popover, + strategy = _ref.strategy; this.floatingUICleanup = autoUpdate(trigger, popover, () => { computePosition(trigger, popover, { placement: this.placementValue, middleware: this.middlewares, strategy: strategy || Configuration.webchat.strategy }).then(_ref2 => { - var { - x, - y, - strategy - } = _ref2; + var x = _ref2.x, + y = _ref2.y, + strategy = _ref2.strategy; var newStyle = { left: "".concat(x, "px"), top: "".concat(y, "px"), @@ -45,7 +41,7 @@ export var usePopover = controller => { if (this.disabledValue) return; if (this.openValue) { var _this$preparePopoverO; - (_this$preparePopoverO = this.preparePopoverOpenAnimation) === null || _this$preparePopoverO === void 0 ? void 0 : _this$preparePopoverO.call(this); + (_this$preparePopoverO = this.preparePopoverOpenAnimation) === null || _this$preparePopoverO === void 0 || _this$preparePopoverO.call(this); this.popoverTarget.showPopover(); this.popoverTarget.setAttribute('aria-expanded', 'true'); if (this['onPopoverOpened']) { diff --git a/lib/controllers/popup_controller.cjs b/lib/controllers/popup_controller.cjs new file mode 100644 index 00000000..ccb98bf5 --- /dev/null +++ b/lib/controllers/popup_controller.cjs @@ -0,0 +1,391 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _stimulus = require("@hotwired/stimulus"); +var _api = _interopRequireDefault(require("../api")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Public popup runtime controller. + * + * Renders the persisted dashboard popup on merchant sites, applies client-side + * display rules, controls bubble-to-dialog transitions, validates every step, + * submits the collected data, and shows the completion screen. + * + * Targets: + * - bubble: Launcher shown before the popup when bubble mode is enabled. + * - dialog: Popup dialog/surface wrapper. + * - step: Sequential form steps. + * - completed: Completion state shown after submission. + * - input: User-entered popup fields. + * - submitButton: Step buttons disabled while the submission is in flight. + * + * Values: + * - capture: Persisted capture, coupon, and journey metadata. + * - device: Popup device targeting. + * - hasBubble: Whether the popup starts from a bubble. + * - id: Public popup identifier. + * - rules: Persisted AND display rules. + */ +let _default = exports.default = /*#__PURE__*/function (_Controller) { + function _default() { + _classCallCheck(this, _default); + return _callSuper(this, _default, arguments); + } + _inherits(_default, _Controller); + return _createClass(_default, [{ + key: "connect", + value: function connect() { + this.stepIndex = 0; + this.onScroll = this.evaluateDisplay.bind(this); + this.hideElement(this.element); + this.hideElement(this.dialogTarget); + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget); + this.evaluateDisplay(); + } + }, { + key: "disconnect", + value: function disconnect() { + window.removeEventListener('scroll', this.onScroll); + } + }, { + key: "open", + value: function open(event) { + if (event) event.preventDefault(); + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget); + this.showElement(this.dialogTarget); + this.markViewed(); + } + }, { + key: "close", + value: function close(event) { + if (event) event.preventDefault(); + this.hideElement(this.dialogTarget); + if (this.hasBubbleValue && this.hasBubbleTarget) { + this.showElement(this.element); + this.showElement(this.bubbleTarget); + } else { + this.hideElement(this.element); + } + } + }, { + key: "next", + value: async function next(event) { + if (event) event.preventDefault(); + this.clearCustomValidity(); + if (!this.currentStepValid()) { + this.showErrorMessages(this.currentStepInputs); + return; + } + this.clearErrorMessages(this.currentStepInputs); + if (this.stepIndex < this.stepTargets.length - 1) { + this.showStep(this.stepIndex + 1); + return; + } + await this.submit(); + } + }, { + key: "submit", + value: async function submit(event) { + if (event) event.preventDefault(); + this.clearCustomValidity(); + if (this.stepIndex < this.stepTargets.length - 1) { + await this.next(); + return; + } + if (!this.currentStepValid()) { + this.showErrorMessages(this.currentStepInputs); + return; + } + this.clearErrorMessages(this.currentStepInputs); + this.submitButtonTargets.forEach(button => { + button.disabled = true; + }); + const response = await _api.default.popups.submit(this.idValue, this.submissionPayload()); + this.submitButtonTargets.forEach(button => { + button.disabled = false; + }); + if (response.failed) { + await this.handleSubmissionError(response); + return; + } + this.showCompleted(); + } + }, { + key: "evaluateDisplay", + value: function evaluateDisplay() { + if (!this.matchesDevice() || !this.rulesWithoutScrollPass()) return; + if (this.scrollRule && !this.scrollRulePasses()) { + window.addEventListener('scroll', this.onScroll, { + passive: true + }); + return; + } + window.removeEventListener('scroll', this.onScroll); + this.showInitialState(); + } + }, { + key: "showInitialState", + value: function showInitialState() { + this.showElement(this.element); + if (this.hasBubbleValue && this.hasBubbleTarget) { + this.showElement(this.bubbleTarget); + this.hideElement(this.dialogTarget); + return; + } + this.showElement(this.dialogTarget); + this.markViewed(); + } + }, { + key: "showStep", + value: function showStep(index) { + this.stepIndex = index; + this.stepTargets.forEach((step, stepIndex) => { + this.toggleElement(step, stepIndex !== index); + }); + this.hideElement(this.completedTarget); + } + }, { + key: "showCompleted", + value: function showCompleted() { + this.stepTargets.forEach(step => this.hideElement(step)); + this.showElement(this.completedTarget); + } + }, { + key: "currentStepValid", + value: function currentStepValid() { + return this.currentStepInputs.every(input => input.checkValidity()); + } + }, { + key: "showErrorMessages", + value: function showErrorMessages(inputs) { + inputs.forEach(input => { + var _input$closest; + const container = (_input$closest = input.closest('.hellotext--popup-field')) === null || _input$closest === void 0 ? void 0 : _input$closest.querySelector('[data-error-container]'); + if (!container) return; + container.textContent = input.validity.valid ? '' : input.validationMessage; + }); + } + }, { + key: "clearErrorMessages", + value: function clearErrorMessages(inputs = this.inputTargets) { + inputs.forEach(input => { + var _input$closest2; + const container = (_input$closest2 = input.closest('.hellotext--popup-field')) === null || _input$closest2 === void 0 ? void 0 : _input$closest2.querySelector('[data-error-container]'); + if (container) container.textContent = ''; + }); + } + }, { + key: "clearCustomValidity", + value: function clearCustomValidity() { + this.inputTargets.forEach(input => input.setCustomValidity('')); + } + }, { + key: "handleSubmissionError", + value: async function handleSubmissionError(response) { + let data; + try { + data = await response.json(); + } catch (_) { + return; + } + const errors = data.errors || []; + errors.forEach(error => { + const input = this.inputForError(error); + if (!input) return; + input.setCustomValidity(error.description || input.validationMessage); + input.reportValidity(); + }); + this.showErrorMessages(this.inputTargets); + } + }, { + key: "inputForError", + value: function inputForError(error) { + const parameter = error.parameter; + if (!parameter) return null; + return this.inputTargets.find(input => { + return input.dataset.popupFieldKind === parameter || input.dataset.popupFieldKey === parameter; + }); + } + }, { + key: "submissionPayload", + value: function submissionPayload() { + const payload = { + metadata: { + capture: this.captureValue || {}, + fields: {}, + steps: [] + } + }; + this.stepTargets.forEach(step => { + const stepFields = {}; + const inputs = this.inputsForStep(step); + inputs.forEach(input => { + const value = this.inputValue(input); + const key = input.dataset.popupFieldKey || input.name; + stepFields[key] = value; + payload.metadata.fields[key] = value; + if (input.dataset.popupFieldKind === 'email') payload.email = value; + if (input.dataset.popupFieldKind === 'phone') payload.phone = value; + }); + payload.metadata.steps.push({ + id: step.dataset.stepId, + name: step.dataset.stepName, + fields: stepFields + }); + }); + return payload; + } + }, { + key: "inputValue", + value: function inputValue(input) { + if (input.type === 'checkbox') return input.checked; + return input.value; + } + }, { + key: "inputsForStep", + value: function inputsForStep(step) { + return this.inputTargets.filter(input => input.dataset.popupStepId === step.dataset.stepId); + } + }, { + key: "rulesWithoutScrollPass", + value: function rulesWithoutScrollPass() { + return this.conditions.filter(condition => condition.type !== 'scroll_depth').every(condition => this.conditionPasses(condition)); + } + }, { + key: "conditionPasses", + value: function conditionPasses(condition) { + if (condition.group === 'properties' && condition.type === 'page_property') { + return this.pagePropertyRulePasses(condition); + } + if (condition.group === 'actions' && condition.type === 'viewed_popup') { + return this.viewedPopupRulePasses(condition); + } + return true; + } + }, { + key: "pagePropertyRulePasses", + value: function pagePropertyRulePasses(condition) { + const expected = String(condition.value || '').trim().toLowerCase(); + if (!expected) return true; + const actual = this.pagePropertyValue(condition.field); + const includes = actual.includes(expected); + return condition.query === 'does_not_contain' ? !includes : includes; + } + }, { + key: "pagePropertyValue", + value: function pagePropertyValue(field) { + if (field === 'url') return window.location.href.toLowerCase(); + if (field === 'title') return document.title.toLowerCase(); + return window.location.pathname.toLowerCase(); + } + }, { + key: "viewedPopupRulePasses", + value: function viewedPopupRulePasses(condition) { + const viewed = this.popupWasViewed(); + return condition.inclusion === false ? !viewed : viewed; + } + }, { + key: "scrollRulePasses", + value: function scrollRulePasses() { + return this.scrollPercentage >= Number(this.scrollRule.value || 0); + } + }, { + key: "matchesDevice", + value: function matchesDevice() { + if (this.deviceValue === 'all') return true; + if (this.deviceValue === 'mobile') return window.innerWidth < 768; + if (this.deviceValue === 'desktop') return window.innerWidth >= 768; + return true; + } + }, { + key: "markViewed", + value: function markViewed() { + try { + localStorage.setItem(this.viewedStorageKey, 'true'); + } catch (_) { + // Some browsers disable storage in private contexts; showing the popup is safer than crashing the page. + } + } + }, { + key: "popupWasViewed", + value: function popupWasViewed() { + try { + return localStorage.getItem(this.viewedStorageKey) === 'true'; + } catch (_) { + return false; + } + } + }, { + key: "showElement", + value: function showElement(element) { + element.hidden = false; + } + }, { + key: "hideElement", + value: function hideElement(element) { + element.hidden = true; + } + }, { + key: "toggleElement", + value: function toggleElement(element, hidden) { + element.hidden = hidden; + } + }, { + key: "currentStep", + get: function () { + return this.stepTargets[this.stepIndex]; + } + }, { + key: "currentStepInputs", + get: function () { + return this.inputsForStep(this.currentStep); + } + }, { + key: "conditions", + get: function () { + var _this$rulesValue; + return ((_this$rulesValue = this.rulesValue) === null || _this$rulesValue === void 0 ? void 0 : _this$rulesValue.conditions) || []; + } + }, { + key: "scrollRule", + get: function () { + return this.conditions.find(condition => condition.group === 'actions' && condition.type === 'scroll_depth'); + } + }, { + key: "scrollPercentage", + get: function () { + const documentElement = document.documentElement; + const scrollableHeight = documentElement.scrollHeight - window.innerHeight; + if (scrollableHeight <= 0) return 100; + return Math.round(window.scrollY / scrollableHeight * 100); + } + }, { + key: "viewedStorageKey", + get: function () { + return `hellotext:popup:${this.idValue}:viewed`; + } + }]); +}(_stimulus.Controller); +_default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton']; +_default.values = { + capture: Object, + device: String, + hasBubble: Boolean, + id: String, + rules: Object +}; \ No newline at end of file diff --git a/lib/controllers/popup_controller.js b/lib/controllers/popup_controller.js new file mode 100644 index 00000000..33d6c4fc --- /dev/null +++ b/lib/controllers/popup_controller.js @@ -0,0 +1,407 @@ +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +import { Controller } from '@hotwired/stimulus'; +import API from '../api'; + +/** + * Public popup runtime controller. + * + * Renders the persisted dashboard popup on merchant sites, applies client-side + * display rules, controls bubble-to-dialog transitions, validates every step, + * submits the collected data, and shows the completion screen. + * + * Targets: + * - bubble: Launcher shown before the popup when bubble mode is enabled. + * - dialog: Popup dialog/surface wrapper. + * - step: Sequential form steps. + * - completed: Completion state shown after submission. + * - input: User-entered popup fields. + * - submitButton: Step buttons disabled while the submission is in flight. + * + * Values: + * - capture: Persisted capture, coupon, and journey metadata. + * - device: Popup device targeting. + * - hasBubble: Whether the popup starts from a bubble. + * - id: Public popup identifier. + * - rules: Persisted AND display rules. + */ +var _default = /*#__PURE__*/function (_Controller) { + function _default() { + _classCallCheck(this, _default); + return _callSuper(this, _default, arguments); + } + _inherits(_default, _Controller); + return _createClass(_default, [{ + key: "connect", + value: function connect() { + this.stepIndex = 0; + this.onScroll = this.evaluateDisplay.bind(this); + this.hideElement(this.element); + this.hideElement(this.dialogTarget); + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget); + this.evaluateDisplay(); + } + }, { + key: "disconnect", + value: function disconnect() { + window.removeEventListener('scroll', this.onScroll); + } + }, { + key: "open", + value: function open(event) { + if (event) event.preventDefault(); + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget); + this.showElement(this.dialogTarget); + this.markViewed(); + } + }, { + key: "close", + value: function close(event) { + if (event) event.preventDefault(); + this.hideElement(this.dialogTarget); + if (this.hasBubbleValue && this.hasBubbleTarget) { + this.showElement(this.element); + this.showElement(this.bubbleTarget); + } else { + this.hideElement(this.element); + } + } + }, { + key: "next", + value: function () { + var _next2 = _asyncToGenerator(function* (event) { + if (event) event.preventDefault(); + this.clearCustomValidity(); + if (!this.currentStepValid()) { + this.showErrorMessages(this.currentStepInputs); + return; + } + this.clearErrorMessages(this.currentStepInputs); + if (this.stepIndex < this.stepTargets.length - 1) { + this.showStep(this.stepIndex + 1); + return; + } + yield this.submit(); + }); + function next(_x) { + return _next2.apply(this, arguments); + } + return next; + }() + }, { + key: "submit", + value: function () { + var _submit = _asyncToGenerator(function* (event) { + if (event) event.preventDefault(); + this.clearCustomValidity(); + if (this.stepIndex < this.stepTargets.length - 1) { + yield this.next(); + return; + } + if (!this.currentStepValid()) { + this.showErrorMessages(this.currentStepInputs); + return; + } + this.clearErrorMessages(this.currentStepInputs); + this.submitButtonTargets.forEach(button => { + button.disabled = true; + }); + var response = yield API.popups.submit(this.idValue, this.submissionPayload()); + this.submitButtonTargets.forEach(button => { + button.disabled = false; + }); + if (response.failed) { + yield this.handleSubmissionError(response); + return; + } + this.showCompleted(); + }); + function submit(_x2) { + return _submit.apply(this, arguments); + } + return submit; + }() + }, { + key: "evaluateDisplay", + value: function evaluateDisplay() { + if (!this.matchesDevice() || !this.rulesWithoutScrollPass()) return; + if (this.scrollRule && !this.scrollRulePasses()) { + window.addEventListener('scroll', this.onScroll, { + passive: true + }); + return; + } + window.removeEventListener('scroll', this.onScroll); + this.showInitialState(); + } + }, { + key: "showInitialState", + value: function showInitialState() { + this.showElement(this.element); + if (this.hasBubbleValue && this.hasBubbleTarget) { + this.showElement(this.bubbleTarget); + this.hideElement(this.dialogTarget); + return; + } + this.showElement(this.dialogTarget); + this.markViewed(); + } + }, { + key: "showStep", + value: function showStep(index) { + this.stepIndex = index; + this.stepTargets.forEach((step, stepIndex) => { + this.toggleElement(step, stepIndex !== index); + }); + this.hideElement(this.completedTarget); + } + }, { + key: "showCompleted", + value: function showCompleted() { + this.stepTargets.forEach(step => this.hideElement(step)); + this.showElement(this.completedTarget); + } + }, { + key: "currentStepValid", + value: function currentStepValid() { + return this.currentStepInputs.every(input => input.checkValidity()); + } + }, { + key: "showErrorMessages", + value: function showErrorMessages(inputs) { + inputs.forEach(input => { + var _input$closest; + var container = (_input$closest = input.closest('.hellotext--popup-field')) === null || _input$closest === void 0 ? void 0 : _input$closest.querySelector('[data-error-container]'); + if (!container) return; + container.textContent = input.validity.valid ? '' : input.validationMessage; + }); + } + }, { + key: "clearErrorMessages", + value: function clearErrorMessages() { + var inputs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.inputTargets; + inputs.forEach(input => { + var _input$closest2; + var container = (_input$closest2 = input.closest('.hellotext--popup-field')) === null || _input$closest2 === void 0 ? void 0 : _input$closest2.querySelector('[data-error-container]'); + if (container) container.textContent = ''; + }); + } + }, { + key: "clearCustomValidity", + value: function clearCustomValidity() { + this.inputTargets.forEach(input => input.setCustomValidity('')); + } + }, { + key: "handleSubmissionError", + value: function () { + var _handleSubmissionError = _asyncToGenerator(function* (response) { + var data; + try { + data = yield response.json(); + } catch (_) { + return; + } + var errors = data.errors || []; + errors.forEach(error => { + var input = this.inputForError(error); + if (!input) return; + input.setCustomValidity(error.description || input.validationMessage); + input.reportValidity(); + }); + this.showErrorMessages(this.inputTargets); + }); + function handleSubmissionError(_x3) { + return _handleSubmissionError.apply(this, arguments); + } + return handleSubmissionError; + }() + }, { + key: "inputForError", + value: function inputForError(error) { + var parameter = error.parameter; + if (!parameter) return null; + return this.inputTargets.find(input => { + return input.dataset.popupFieldKind === parameter || input.dataset.popupFieldKey === parameter; + }); + } + }, { + key: "submissionPayload", + value: function submissionPayload() { + var payload = { + metadata: { + capture: this.captureValue || {}, + fields: {}, + steps: [] + } + }; + this.stepTargets.forEach(step => { + var stepFields = {}; + var inputs = this.inputsForStep(step); + inputs.forEach(input => { + var value = this.inputValue(input); + var key = input.dataset.popupFieldKey || input.name; + stepFields[key] = value; + payload.metadata.fields[key] = value; + if (input.dataset.popupFieldKind === 'email') payload.email = value; + if (input.dataset.popupFieldKind === 'phone') payload.phone = value; + }); + payload.metadata.steps.push({ + id: step.dataset.stepId, + name: step.dataset.stepName, + fields: stepFields + }); + }); + return payload; + } + }, { + key: "inputValue", + value: function inputValue(input) { + if (input.type === 'checkbox') return input.checked; + return input.value; + } + }, { + key: "inputsForStep", + value: function inputsForStep(step) { + return this.inputTargets.filter(input => input.dataset.popupStepId === step.dataset.stepId); + } + }, { + key: "rulesWithoutScrollPass", + value: function rulesWithoutScrollPass() { + return this.conditions.filter(condition => condition.type !== 'scroll_depth').every(condition => this.conditionPasses(condition)); + } + }, { + key: "conditionPasses", + value: function conditionPasses(condition) { + if (condition.group === 'properties' && condition.type === 'page_property') { + return this.pagePropertyRulePasses(condition); + } + if (condition.group === 'actions' && condition.type === 'viewed_popup') { + return this.viewedPopupRulePasses(condition); + } + return true; + } + }, { + key: "pagePropertyRulePasses", + value: function pagePropertyRulePasses(condition) { + var expected = String(condition.value || '').trim().toLowerCase(); + if (!expected) return true; + var actual = this.pagePropertyValue(condition.field); + var includes = actual.includes(expected); + return condition.query === 'does_not_contain' ? !includes : includes; + } + }, { + key: "pagePropertyValue", + value: function pagePropertyValue(field) { + if (field === 'url') return window.location.href.toLowerCase(); + if (field === 'title') return document.title.toLowerCase(); + return window.location.pathname.toLowerCase(); + } + }, { + key: "viewedPopupRulePasses", + value: function viewedPopupRulePasses(condition) { + var viewed = this.popupWasViewed(); + return condition.inclusion === false ? !viewed : viewed; + } + }, { + key: "scrollRulePasses", + value: function scrollRulePasses() { + return this.scrollPercentage >= Number(this.scrollRule.value || 0); + } + }, { + key: "matchesDevice", + value: function matchesDevice() { + if (this.deviceValue === 'all') return true; + if (this.deviceValue === 'mobile') return window.innerWidth < 768; + if (this.deviceValue === 'desktop') return window.innerWidth >= 768; + return true; + } + }, { + key: "markViewed", + value: function markViewed() { + try { + localStorage.setItem(this.viewedStorageKey, 'true'); + } catch (_) { + // Some browsers disable storage in private contexts; showing the popup is safer than crashing the page. + } + } + }, { + key: "popupWasViewed", + value: function popupWasViewed() { + try { + return localStorage.getItem(this.viewedStorageKey) === 'true'; + } catch (_) { + return false; + } + } + }, { + key: "showElement", + value: function showElement(element) { + element.hidden = false; + } + }, { + key: "hideElement", + value: function hideElement(element) { + element.hidden = true; + } + }, { + key: "toggleElement", + value: function toggleElement(element, hidden) { + element.hidden = hidden; + } + }, { + key: "currentStep", + get: function get() { + return this.stepTargets[this.stepIndex]; + } + }, { + key: "currentStepInputs", + get: function get() { + return this.inputsForStep(this.currentStep); + } + }, { + key: "conditions", + get: function get() { + var _this$rulesValue; + return ((_this$rulesValue = this.rulesValue) === null || _this$rulesValue === void 0 ? void 0 : _this$rulesValue.conditions) || []; + } + }, { + key: "scrollRule", + get: function get() { + return this.conditions.find(condition => condition.group === 'actions' && condition.type === 'scroll_depth'); + } + }, { + key: "scrollPercentage", + get: function get() { + var documentElement = document.documentElement; + var scrollableHeight = documentElement.scrollHeight - window.innerHeight; + if (scrollableHeight <= 0) return 100; + return Math.round(window.scrollY / scrollableHeight * 100); + } + }, { + key: "viewedStorageKey", + get: function get() { + return "hellotext:popup:".concat(this.idValue, ":viewed"); + } + }]); +}(Controller); +_default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton']; +_default.values = { + capture: Object, + device: String, + hasBubble: Boolean, + id: String, + rules: Object +}; +export { _default as default }; \ No newline at end of file diff --git a/lib/controllers/webchat/emoji_picker_controller.cjs b/lib/controllers/webchat/emoji_picker_controller.cjs index 384915a2..8116cb21 100644 --- a/lib/controllers/webchat/emoji_picker_controller.cjs +++ b/lib/controllers/webchat/emoji_picker_controller.cjs @@ -7,37 +7,36 @@ exports.default = void 0; var _dom = require("@floating-ui/dom"); var _stimulus = require("@hotwired/stimulus"); var _usePopover = require("../mixins/usePopover"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -let _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +let _default = exports.default = /*#__PURE__*/function (_Controller) { function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "initialize", value: function initialize() { this.onEmojiSelect = this.onEmojiSelect.bind(this); this.pickerLoaded = false; this.pickerLoadPromise = null; this.connected = false; - _get(_getPrototypeOf(_default.prototype), "initialize", this).call(this); + _superPropGet(_default, "initialize", this, 3)([]); } }, { key: "connect", @@ -49,7 +48,7 @@ let _default = /*#__PURE__*/function (_Controller) { popover: this.popoverTarget, strategy: 'absolute' }); - _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + _superPropGet(_default, "connect", this, 3)([]); } }, { key: "disconnect", @@ -57,7 +56,7 @@ let _default = /*#__PURE__*/function (_Controller) { this.connected = false; this.pickerLoadPromise = null; this.floatingUICleanup(); - _get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this); + _superPropGet(_default, "disconnect", this, 3)([]); } }, { key: "onEmojiSelect", @@ -95,7 +94,7 @@ let _default = /*#__PURE__*/function (_Controller) { }, { key: "loadPickerDependencies", value: async function loadPickerDependencies() { - const [pickerModule, i18nModule] = await Promise.all([Promise.resolve().then(() => _interopRequireWildcard(require( /* webpackChunkName: "webchat-emoji" */'emoji-mart'))), this.loadI18n()]); + const [pickerModule, i18nModule] = await Promise.all([Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "webchat-emoji" */'emoji-mart'))), this.loadI18n()]); return { Picker: pickerModule.Picker, i18n: i18nModule.default || i18nModule @@ -105,9 +104,9 @@ let _default = /*#__PURE__*/function (_Controller) { key: "loadI18n", value: function loadI18n() { if (Hellotext.business.locale === 'es') { - return Promise.resolve().then(() => _interopRequireWildcard(require( /* webpackChunkName: "webchat-emoji-es" */'@emoji-mart/data/i18n/es.json'))); + return Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "webchat-emoji-es" */'@emoji-mart/data/i18n/es.json'))); } - return Promise.resolve().then(() => _interopRequireWildcard(require( /* webpackChunkName: "webchat-emoji-en" */'@emoji-mart/data/i18n/en.json'))); + return Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "webchat-emoji-en" */'@emoji-mart/data/i18n/en.json'))); } }, { key: "buildPicker", @@ -133,9 +132,7 @@ let _default = /*#__PURE__*/function (_Controller) { })]; } }]); - return _default; }(_stimulus.Controller); -exports.default = _default; _default.targets = ['button', 'popover']; _default.values = { placement: { diff --git a/lib/controllers/webchat/emoji_picker_controller.js b/lib/controllers/webchat/emoji_picker_controller.js index 037f42fa..84f9cc74 100644 --- a/lib/controllers/webchat/emoji_picker_controller.js +++ b/lib/controllers/webchat/emoji_picker_controller.js @@ -1,37 +1,43 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } import { autoPlacement, offset, shift } from '@floating-ui/dom'; import { Controller } from '@hotwired/stimulus'; import { usePopover } from '../mixins/usePopover'; var _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "initialize", value: function initialize() { this.onEmojiSelect = this.onEmojiSelect.bind(this); this.pickerLoaded = false; this.pickerLoadPromise = null; this.connected = false; - _get(_getPrototypeOf(_default.prototype), "initialize", this).call(this); + _superPropGet(_default, "initialize", this, 3)([]); } }, { key: "connect", @@ -43,7 +49,7 @@ var _default = /*#__PURE__*/function (_Controller) { popover: this.popoverTarget, strategy: 'absolute' }); - _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + _superPropGet(_default, "connect", this, 3)([]); } }, { key: "disconnect", @@ -51,7 +57,7 @@ var _default = /*#__PURE__*/function (_Controller) { this.connected = false; this.pickerLoadPromise = null; this.floatingUICleanup(); - _get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this); + _superPropGet(_default, "disconnect", this, 3)([]); } }, { key: "onEmojiSelect", @@ -85,10 +91,9 @@ var _default = /*#__PURE__*/function (_Controller) { var _loadPicker = _asyncToGenerator(function* () { if (this.pickerLoaded) return; this.pickerLoadPromise || (this.pickerLoadPromise = this.loadPickerDependencies()); - var { - Picker, - i18n - } = yield this.pickerLoadPromise; + var _yield$this$pickerLoa = yield this.pickerLoadPromise, + Picker = _yield$this$pickerLoa.Picker, + i18n = _yield$this$pickerLoa.i18n; if (!this.connected || this.pickerLoaded) return; this.popoverTarget.appendChild(this.buildPicker(Picker, i18n)); this.pickerLoaded = true; @@ -102,7 +107,10 @@ var _default = /*#__PURE__*/function (_Controller) { key: "loadPickerDependencies", value: function () { var _loadPickerDependencies = _asyncToGenerator(function* () { - var [pickerModule, i18nModule] = yield Promise.all([import( /* webpackChunkName: "webchat-emoji" */'emoji-mart'), this.loadI18n()]); + var _yield$Promise$all = yield Promise.all([import(/* webpackChunkName: "webchat-emoji" */'emoji-mart'), this.loadI18n()]), + _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2), + pickerModule = _yield$Promise$all2[0], + i18nModule = _yield$Promise$all2[1]; return { Picker: pickerModule.Picker, i18n: i18nModule.default || i18nModule @@ -117,9 +125,9 @@ var _default = /*#__PURE__*/function (_Controller) { key: "loadI18n", value: function loadI18n() { if (Hellotext.business.locale === 'es') { - return import( /* webpackChunkName: "webchat-emoji-es" */'@emoji-mart/data/i18n/es.json'); + return import(/* webpackChunkName: "webchat-emoji-es" */'@emoji-mart/data/i18n/es.json'); } - return import( /* webpackChunkName: "webchat-emoji-en" */'@emoji-mart/data/i18n/en.json'); + return import(/* webpackChunkName: "webchat-emoji-en" */'@emoji-mart/data/i18n/en.json'); } }, { key: "buildPicker", @@ -145,7 +153,6 @@ var _default = /*#__PURE__*/function (_Controller) { })]; } }]); - return _default; }(Controller); _default.targets = ['button', 'popover']; _default.values = { diff --git a/lib/controllers/webchat_controller.cjs b/lib/controllers/webchat_controller.cjs index 426c605c..a182e6ed 100644 --- a/lib/controllers/webchat_controller.cjs +++ b/lib/controllers/webchat_controller.cjs @@ -16,21 +16,22 @@ var _usePopover = require("./mixins/usePopover"); var _useBehaviour = require("./webchat/useBehaviour"); var _useOpeningSequence = require("./webchat/useOpeningSequence"); var _useTeaser = require("./webchat/useTeaser"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } const POPOVER_ANIMATION_DURATION = 120; const MESSAGE_TIMESTAMP_FORMAT_OPTIONS = { hour: 'numeric', @@ -41,14 +42,13 @@ const SCROLL_ISOLATION_EVENT_OPTIONS = { capture: true, passive: true }; -let _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); +let _default = exports.default = /*#__PURE__*/function (_Controller) { function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "initialize", value: function initialize() { this.messagesAPI = new _messages2.default(this.idValue); @@ -68,7 +68,7 @@ let _default = /*#__PURE__*/function (_Controller) { this.broadcastChannel = new BroadcastChannel(`hellotext--webchat--${this.idValue}`); this.webChatChannel.onDisconnect(this.captureCatchUpCursor); this.webChatChannel.onReconnect(this.catchUpMessages); - _get(_getPrototypeOf(_default.prototype), "initialize", this).call(this); + _superPropGet(_default, "initialize", this, 3)([]); } }, { key: "connect", @@ -105,7 +105,7 @@ let _default = /*#__PURE__*/function (_Controller) { this.broadcastChannel.addEventListener('message', this.onOutboundMessageSent); window.addEventListener('keydown', this.closePopoverOnEscape, true); this.scheduleBehaviourOpen(); - _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + _superPropGet(_default, "connect", this, 3)([]); } }, { key: "disconnect", @@ -124,7 +124,7 @@ let _default = /*#__PURE__*/function (_Controller) { this.clearTypingIndicator(); this.broadcastChannel.close(); this.floatingUICleanup(); - _get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this); + _superPropGet(_default, "disconnect", this, 3)([]); } }, { key: "setupMessagesContainerScrollIsolation", @@ -287,7 +287,7 @@ let _default = /*#__PURE__*/function (_Controller) { image.removeAttribute('data-hellotext--webchat-target'); image.src = attachmentUrl; image.style.display = 'block'; - (_this$messageAttachme = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme === void 0 ? void 0 : _this$messageAttachme.appendChild(image); + (_this$messageAttachme = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme === void 0 || _this$messageAttachme.appendChild(image); }); } element.setAttribute('data-body', body); @@ -333,14 +333,14 @@ let _default = /*#__PURE__*/function (_Controller) { clearTimeout(this.popoverOpenAnimationTimeout); this.popoverOpenAnimationTimeout = null; } - (_this$popoverTarget = this.popoverTarget) === null || _this$popoverTarget === void 0 ? void 0 : _this$popoverTarget.classList.remove('hellotext--webchat-popover-opening'); + (_this$popoverTarget = this.popoverTarget) === null || _this$popoverTarget === void 0 || _this$popoverTarget.classList.remove('hellotext--webchat-popover-opening'); } }, { key: "onPopoverOpened", value: function onPopoverOpened() { var _this$dismissTeaserFo; this.popoverTarget.classList.remove(...this.fadeOutClasses); - (_this$dismissTeaserFo = this.dismissTeaserForSession) === null || _this$dismissTeaserFo === void 0 ? void 0 : _this$dismissTeaserFo.call(this); + (_this$dismissTeaserFo = this.dismissTeaserForSession) === null || _this$dismissTeaserFo === void 0 || _this$dismissTeaserFo.call(this); if (!this.onMobile) { this.focusComposeInput(); } @@ -407,7 +407,7 @@ let _default = /*#__PURE__*/function (_Controller) { } = message; const createdAt = message.created_at || message.createdAt; if (!this.claimMessageId(id)) return; - (_this$hideTeaser = this.hideTeaser) === null || _this$hideTeaser === void 0 ? void 0 : _this$hideTeaser.call(this); + (_this$hideTeaser = this.hideTeaser) === null || _this$hideTeaser === void 0 || _this$hideTeaser.call(this); if (message.carousel) { return this.insertCarouselMessage(message, options); } @@ -425,7 +425,7 @@ let _default = /*#__PURE__*/function (_Controller) { const image = this.attachmentImageTarget.cloneNode(true); image.src = attachmentUrl; image.style.display = 'block'; - (_this$messageAttachme2 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme2 === void 0 ? void 0 : _this$messageAttachme2.appendChild(image); + (_this$messageAttachme2 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme2 === void 0 || _this$messageAttachme2.appendChild(image); }); } this.clearTypingIndicator(); @@ -589,7 +589,7 @@ let _default = /*#__PURE__*/function (_Controller) { } }) { var _this$dismissTeaserFo2, _cardElement$querySel; - (_this$dismissTeaserFo2 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo2 === void 0 ? void 0 : _this$dismissTeaserFo2.call(this); + (_this$dismissTeaserFo2 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo2 === void 0 || _this$dismissTeaserFo2.call(this); const formData = new FormData(); formData.append('message[body]', body); if (id) formData.append('message[replied_to]', id); @@ -599,13 +599,13 @@ let _default = /*#__PURE__*/function (_Controller) { formData.append('locale', _core.Locale.toString()); this.appendOpeningSequenceMessageIds(formData); const element = this.buildMessageElement(); - const attachment = cardElement === null || cardElement === void 0 ? void 0 : (_cardElement$querySel = cardElement.querySelector('img')) === null || _cardElement$querySel === void 0 ? void 0 : _cardElement$querySel.cloneNode(true); + const attachment = cardElement === null || cardElement === void 0 || (_cardElement$querySel = cardElement.querySelector('img')) === null || _cardElement$querySel === void 0 ? void 0 : _cardElement$querySel.cloneNode(true); element.querySelector('[data-body]').innerText = body; if (attachment) { var _this$messageAttachme3; attachment.removeAttribute('width'); attachment.removeAttribute('height'); - (_this$messageAttachme3 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme3 === void 0 ? void 0 : _this$messageAttachme3.appendChild(attachment); + (_this$messageAttachme3 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme3 === void 0 || _this$messageAttachme3.appendChild(attachment); } if (this.typingIndicatorVisible && this.hasTypingIndicatorTarget) { this.messagesContainerTarget.insertBefore(element, this.typingIndicatorTarget); @@ -654,7 +654,7 @@ let _default = /*#__PURE__*/function (_Controller) { const label = [button.dataset.text, button.textContent].map(text => (text || '').trim()).find(text => text.length > 0); const text = value || label; if (!text) return; - (_this$dismissTeaserFo3 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo3 === void 0 ? void 0 : _this$dismissTeaserFo3.call(this); + (_this$dismissTeaserFo3 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo3 === void 0 || _this$dismissTeaserFo3.call(this); this.show(); const buttonType = (button.dataset.type || '').trim() || 'quick_reply'; const formData = new FormData(); @@ -724,7 +724,7 @@ let _default = /*#__PURE__*/function (_Controller) { } return; } - (_this$dismissTeaserFo4 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo4 === void 0 ? void 0 : _this$dismissTeaserFo4.call(this); + (_this$dismissTeaserFo4 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo4 === void 0 || _this$dismissTeaserFo4.call(this); const formData = new FormData(); if (this.inputTarget.value.trim().length > 0) { formData.append('message[body]', this.inputTarget.value); @@ -747,7 +747,7 @@ let _default = /*#__PURE__*/function (_Controller) { if (attachments.length > 0) { attachments.forEach(attachment => { var _this$messageAttachme4; - (_this$messageAttachme4 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme4 === void 0 ? void 0 : _this$messageAttachme4.appendChild(attachment.cloneNode(true)); + (_this$messageAttachme4 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme4 === void 0 || _this$messageAttachme4.appendChild(attachment.cloneNode(true)); }); } @@ -847,7 +847,7 @@ let _default = /*#__PURE__*/function (_Controller) { event.preventDefault(); event.stopPropagation(); this.closePopover(); - (_this$triggerTarget = this.triggerTarget) === null || _this$triggerTarget === void 0 ? void 0 : (_this$triggerTarget$f = _this$triggerTarget.focus) === null || _this$triggerTarget$f === void 0 ? void 0 : _this$triggerTarget$f.call(_this$triggerTarget); + (_this$triggerTarget = this.triggerTarget) === null || _this$triggerTarget === void 0 || (_this$triggerTarget$f = _this$triggerTarget.focus) === null || _this$triggerTarget$f === void 0 || _this$triggerTarget$f.call(_this$triggerTarget); } }, { key: "markMessageFailedFromResponse", @@ -901,7 +901,7 @@ let _default = /*#__PURE__*/function (_Controller) { try { var _jsonResponse$json; const jsonResponse = nativeResponse !== null && nativeResponse !== void 0 && nativeResponse.clone ? nativeResponse.clone() : nativeResponse; - const payload = await (jsonResponse === null || jsonResponse === void 0 ? void 0 : (_jsonResponse$json = jsonResponse.json) === null || _jsonResponse$json === void 0 ? void 0 : _jsonResponse$json.call(jsonResponse)); + const payload = await (jsonResponse === null || jsonResponse === void 0 || (_jsonResponse$json = jsonResponse.json) === null || _jsonResponse$json === void 0 ? void 0 : _jsonResponse$json.call(jsonResponse)); const reason = this.messageFailureReasonFromPayload(payload); if (reason) return reason; } catch (_) { @@ -911,7 +911,7 @@ let _default = /*#__PURE__*/function (_Controller) { try { var _textResponse$text; const textResponse = nativeResponse !== null && nativeResponse !== void 0 && nativeResponse.clone ? nativeResponse.clone() : nativeResponse; - const text = await (textResponse === null || textResponse === void 0 ? void 0 : (_textResponse$text = textResponse.text) === null || _textResponse$text === void 0 ? void 0 : _textResponse$text.call(textResponse)); + const text = await (textResponse === null || textResponse === void 0 || (_textResponse$text = textResponse.text) === null || _textResponse$text === void 0 ? void 0 : _textResponse$text.call(textResponse)); return this.messageFailureReasonFromText(text) || fallback; } catch (_) { return fallback; @@ -932,9 +932,9 @@ let _default = /*#__PURE__*/function (_Controller) { }, { key: "messageFailureReasonFromPayload", value: function messageFailureReasonFromPayload(payload) { - var _payload$error, _payload$errors, _payload$errors2, _payload$errors2$, _payload$errors3, _payload$errors3$; + var _payload$error, _payload$errors, _payload$errors2, _payload$errors3; if (!payload) return null; - return [(_payload$error = payload.error) === null || _payload$error === void 0 ? void 0 : _payload$error.message, payload.message, (_payload$errors = payload.errors) === null || _payload$errors === void 0 ? void 0 : _payload$errors.message, (_payload$errors2 = payload.errors) === null || _payload$errors2 === void 0 ? void 0 : (_payload$errors2$ = _payload$errors2[0]) === null || _payload$errors2$ === void 0 ? void 0 : _payload$errors2$.message, (_payload$errors3 = payload.errors) === null || _payload$errors3 === void 0 ? void 0 : (_payload$errors3$ = _payload$errors3[0]) === null || _payload$errors3$ === void 0 ? void 0 : _payload$errors3$.description].find(reason => typeof reason === 'string' && reason.trim().length > 0); + return [(_payload$error = payload.error) === null || _payload$error === void 0 ? void 0 : _payload$error.message, payload.message, (_payload$errors = payload.errors) === null || _payload$errors === void 0 ? void 0 : _payload$errors.message, (_payload$errors2 = payload.errors) === null || _payload$errors2 === void 0 || (_payload$errors2 = _payload$errors2[0]) === null || _payload$errors2 === void 0 ? void 0 : _payload$errors2.message, (_payload$errors3 = payload.errors) === null || _payload$errors3 === void 0 || (_payload$errors3 = _payload$errors3[0]) === null || _payload$errors3 === void 0 ? void 0 : _payload$errors3.description].find(reason => typeof reason === 'string' && reason.trim().length > 0); } }, { key: "messageAttachmentsContainer", @@ -1121,9 +1121,7 @@ let _default = /*#__PURE__*/function (_Controller) { } } }]); - return _default; }(_stimulus.Controller); -exports.default = _default; _default.messageTimestampFormatters = {}; _default.values = { id: String, diff --git a/lib/controllers/webchat_controller.js b/lib/controllers/webchat_controller.js index 9d771f07..d6350da2 100644 --- a/lib/controllers/webchat_controller.js +++ b/lib/controllers/webchat_controller.js @@ -1,22 +1,23 @@ -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } +function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } +function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } import { flip, offset, shift } from '@floating-ui/dom'; import { Controller } from '@hotwired/stimulus'; import WebchatMessagesAPI from '../api/webchat/messages'; @@ -40,13 +41,12 @@ var SCROLL_ISOLATION_EVENT_OPTIONS = { passive: true }; var _default = /*#__PURE__*/function (_Controller) { - _inherits(_default, _Controller); - var _super = _createSuper(_default); function _default() { _classCallCheck(this, _default); - return _super.apply(this, arguments); + return _callSuper(this, _default, arguments); } - _createClass(_default, [{ + _inherits(_default, _Controller); + return _createClass(_default, [{ key: "initialize", value: function initialize() { this.messagesAPI = new WebchatMessagesAPI(this.idValue); @@ -66,7 +66,7 @@ var _default = /*#__PURE__*/function (_Controller) { this.broadcastChannel = new BroadcastChannel("hellotext--webchat--".concat(this.idValue)); this.webChatChannel.onDisconnect(this.captureCatchUpCursor); this.webChatChannel.onReconnect(this.catchUpMessages); - _get(_getPrototypeOf(_default.prototype), "initialize", this).call(this); + _superPropGet(_default, "initialize", this, 3)([]); } }, { key: "connect", @@ -103,7 +103,7 @@ var _default = /*#__PURE__*/function (_Controller) { this.broadcastChannel.addEventListener('message', this.onOutboundMessageSent); window.addEventListener('keydown', this.closePopoverOnEscape, true); this.scheduleBehaviourOpen(); - _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + _superPropGet(_default, "connect", this, 3)([]); } }, { key: "disconnect", @@ -122,7 +122,7 @@ var _default = /*#__PURE__*/function (_Controller) { this.clearTypingIndicator(); this.broadcastChannel.close(); this.floatingUICleanup(); - _get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this); + _superPropGet(_default, "disconnect", this, 3)([]); } }, { key: "setupMessagesContainerScrollIsolation", @@ -214,9 +214,7 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "onOutboundMessageSent", value: function onOutboundMessageSent(event) { - var { - data - } = event; + var data = event.data; var callbacks = { 'message:sent': data => { var element = new DOMParser().parseFromString(data.element, 'text/html').body.firstElementChild; @@ -253,17 +251,14 @@ var _default = /*#__PURE__*/function (_Controller) { page: this.nextPageValue, session: Hellotext.session }); - var { - next: nextPage, - messages - } = yield response.json(); + var _yield$response$json = yield response.json(), + nextPage = _yield$response$json.next, + messages = _yield$response$json.messages; this.nextPageValue = nextPage; this.oldScrollHeight = this.messagesContainerTarget.scrollHeight; messages.forEach(message => { - var { - body, - attachments - } = message; + var body = message.body, + attachments = message.attachments; var createdAt = message.created_at || message.createdAt; var element = this.messageTemplateTarget.cloneNode(true); element.classList.add('hellotext--webchat-message'); @@ -286,7 +281,7 @@ var _default = /*#__PURE__*/function (_Controller) { image.removeAttribute('data-hellotext--webchat-target'); image.src = attachmentUrl; image.style.display = 'block'; - (_this$messageAttachme = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme === void 0 ? void 0 : _this$messageAttachme.appendChild(image); + (_this$messageAttachme = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme === void 0 || _this$messageAttachme.appendChild(image); }); } element.setAttribute('data-body', body); @@ -337,14 +332,14 @@ var _default = /*#__PURE__*/function (_Controller) { clearTimeout(this.popoverOpenAnimationTimeout); this.popoverOpenAnimationTimeout = null; } - (_this$popoverTarget = this.popoverTarget) === null || _this$popoverTarget === void 0 ? void 0 : _this$popoverTarget.classList.remove('hellotext--webchat-popover-opening'); + (_this$popoverTarget = this.popoverTarget) === null || _this$popoverTarget === void 0 || _this$popoverTarget.classList.remove('hellotext--webchat-popover-opening'); } }, { key: "onPopoverOpened", value: function onPopoverOpened() { var _this$dismissTeaserFo; this.popoverTarget.classList.remove(...this.fadeOutClasses); - (_this$dismissTeaserFo = this.dismissTeaserForSession) === null || _this$dismissTeaserFo === void 0 ? void 0 : _this$dismissTeaserFo.call(this); + (_this$dismissTeaserFo = this.dismissTeaserForSession) === null || _this$dismissTeaserFo === void 0 || _this$dismissTeaserFo.call(this); if (!this.onMobile) { this.focusComposeInput(); } @@ -378,11 +373,9 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "onMessageReaction", value: function onMessageReaction(message) { - var { - message: messageId, - reaction, - type - } = message; + var messageId = message.message, + reaction = message.reaction, + type = message.type; var messageElement = this.messageTargets.find(element => element.dataset.id === messageId); var reactionsContainer = messageElement.querySelector('[data-reactions]'); if (type === 'reaction.destroy') { @@ -404,15 +397,13 @@ var _default = /*#__PURE__*/function (_Controller) { value: function onMessageReceived(message) { var _this$hideTeaser; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var { - id, - body, - attachments, - teaser - } = message; + var id = message.id, + body = message.body, + attachments = message.attachments, + teaser = message.teaser; var createdAt = message.created_at || message.createdAt; if (!this.claimMessageId(id)) return; - (_this$hideTeaser = this.hideTeaser) === null || _this$hideTeaser === void 0 ? void 0 : _this$hideTeaser.call(this); + (_this$hideTeaser = this.hideTeaser) === null || _this$hideTeaser === void 0 || _this$hideTeaser.call(this); if (message.carousel) { return this.insertCarouselMessage(message, options); } @@ -430,7 +421,7 @@ var _default = /*#__PURE__*/function (_Controller) { var image = this.attachmentImageTarget.cloneNode(true); image.src = attachmentUrl; image.style.display = 'block'; - (_this$messageAttachme2 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme2 === void 0 ? void 0 : _this$messageAttachme2.appendChild(image); + (_this$messageAttachme2 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme2 === void 0 || _this$messageAttachme2.appendChild(image); }); } this.clearTypingIndicator(); @@ -476,9 +467,9 @@ var _default = /*#__PURE__*/function (_Controller) { this.fetchingCatchUpMessages = true; try { var response = yield this.messagesAPI.catchUp(afterId); - var { - messages = [] - } = yield response.json(); + var _yield$response$json2 = yield response.json(), + _yield$response$json3 = _yield$response$json2.messages, + messages = _yield$response$json3 === void 0 ? [] : _yield$response$json3; messages.forEach(message => this.onMessageReceived(message, { scroll: false })); @@ -592,16 +583,13 @@ var _default = /*#__PURE__*/function (_Controller) { value: function () { var _sendQuickReplyMessage = _asyncToGenerator(function* (_ref) { var _this$dismissTeaserFo2, _cardElement$querySel; - var { - detail: { - id, - product, - buttonId, - body, - cardElement - } - } = _ref; - (_this$dismissTeaserFo2 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo2 === void 0 ? void 0 : _this$dismissTeaserFo2.call(this); + var _ref$detail = _ref.detail, + id = _ref$detail.id, + product = _ref$detail.product, + buttonId = _ref$detail.buttonId, + body = _ref$detail.body, + cardElement = _ref$detail.cardElement; + (_this$dismissTeaserFo2 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo2 === void 0 || _this$dismissTeaserFo2.call(this); var formData = new FormData(); formData.append('message[body]', body); if (id) formData.append('message[replied_to]', id); @@ -611,13 +599,13 @@ var _default = /*#__PURE__*/function (_Controller) { formData.append('locale', Locale.toString()); this.appendOpeningSequenceMessageIds(formData); var element = this.buildMessageElement(); - var attachment = cardElement === null || cardElement === void 0 ? void 0 : (_cardElement$querySel = cardElement.querySelector('img')) === null || _cardElement$querySel === void 0 ? void 0 : _cardElement$querySel.cloneNode(true); + var attachment = cardElement === null || cardElement === void 0 || (_cardElement$querySel = cardElement.querySelector('img')) === null || _cardElement$querySel === void 0 ? void 0 : _cardElement$querySel.cloneNode(true); element.querySelector('[data-body]').innerText = body; if (attachment) { var _this$messageAttachme3; attachment.removeAttribute('width'); attachment.removeAttribute('height'); - (_this$messageAttachme3 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme3 === void 0 ? void 0 : _this$messageAttachme3.appendChild(attachment); + (_this$messageAttachme3 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme3 === void 0 || _this$messageAttachme3.appendChild(attachment); } if (this.typingIndicatorVisible && this.hasTypingIndicatorTarget) { this.messagesContainerTarget.insertBefore(element, this.typingIndicatorTarget); @@ -672,7 +660,7 @@ var _default = /*#__PURE__*/function (_Controller) { var label = [button.dataset.text, button.textContent].map(text => (text || '').trim()).find(text => text.length > 0); var text = value || label; if (!text) return; - (_this$dismissTeaserFo3 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo3 === void 0 ? void 0 : _this$dismissTeaserFo3.call(this); + (_this$dismissTeaserFo3 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo3 === void 0 || _this$dismissTeaserFo3.call(this); this.show(); var buttonType = (button.dataset.type || '').trim() || 'quick_reply'; var formData = new FormData(); @@ -748,7 +736,7 @@ var _default = /*#__PURE__*/function (_Controller) { } return; } - (_this$dismissTeaserFo4 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo4 === void 0 ? void 0 : _this$dismissTeaserFo4.call(this); + (_this$dismissTeaserFo4 = this.dismissTeaserForSession) === null || _this$dismissTeaserFo4 === void 0 || _this$dismissTeaserFo4.call(this); var formData = new FormData(); if (this.inputTarget.value.trim().length > 0) { formData.append('message[body]', this.inputTarget.value); @@ -771,7 +759,7 @@ var _default = /*#__PURE__*/function (_Controller) { if (attachments.length > 0) { attachments.forEach(attachment => { var _this$messageAttachme4; - (_this$messageAttachme4 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme4 === void 0 ? void 0 : _this$messageAttachme4.appendChild(attachment.cloneNode(true)); + (_this$messageAttachme4 = this.messageAttachmentsContainer(element)) === null || _this$messageAttachme4 === void 0 || _this$messageAttachme4.appendChild(attachment.cloneNode(true)); }); } @@ -848,9 +836,7 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "focusCompose", value: function focusCompose(event) { - var { - target - } = event; + var target = event.target; var ignoredSelector = ['button', 'a', 'input', 'textarea', 'select', 'label', '[role="button"]', 'em-emoji-picker', '[data-hellotext--webchat--emoji-target~="popover"]', '[data-controller~="hellotext--webchat--emoji"]'].join(', '); if (!this.hasInputTarget || target.closest(ignoredSelector)) return; if (!this.focusComposeInput({ @@ -861,9 +847,7 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "closePopoverFromHeader", value: function closePopoverFromHeader(event) { - var { - target - } = event; + var target = event.target; if (target.closest('.hellotext--webchat-header-channel-button, .hellotext--webchat-close-button')) return; event.preventDefault(); this.closePopover(); @@ -876,7 +860,7 @@ var _default = /*#__PURE__*/function (_Controller) { event.preventDefault(); event.stopPropagation(); this.closePopover(); - (_this$triggerTarget = this.triggerTarget) === null || _this$triggerTarget === void 0 ? void 0 : (_this$triggerTarget$f = _this$triggerTarget.focus) === null || _this$triggerTarget$f === void 0 ? void 0 : _this$triggerTarget$f.call(_this$triggerTarget); + (_this$triggerTarget = this.triggerTarget) === null || _this$triggerTarget === void 0 || (_this$triggerTarget$f = _this$triggerTarget.focus) === null || _this$triggerTarget$f === void 0 || _this$triggerTarget$f.call(_this$triggerTarget); } }, { key: "markMessageFailedFromResponse", @@ -939,7 +923,7 @@ var _default = /*#__PURE__*/function (_Controller) { try { var _jsonResponse$json; var jsonResponse = nativeResponse !== null && nativeResponse !== void 0 && nativeResponse.clone ? nativeResponse.clone() : nativeResponse; - var payload = yield jsonResponse === null || jsonResponse === void 0 ? void 0 : (_jsonResponse$json = jsonResponse.json) === null || _jsonResponse$json === void 0 ? void 0 : _jsonResponse$json.call(jsonResponse); + var payload = yield jsonResponse === null || jsonResponse === void 0 || (_jsonResponse$json = jsonResponse.json) === null || _jsonResponse$json === void 0 ? void 0 : _jsonResponse$json.call(jsonResponse); var reason = this.messageFailureReasonFromPayload(payload); if (reason) return reason; } catch (_) { @@ -949,7 +933,7 @@ var _default = /*#__PURE__*/function (_Controller) { try { var _textResponse$text; var textResponse = nativeResponse !== null && nativeResponse !== void 0 && nativeResponse.clone ? nativeResponse.clone() : nativeResponse; - var text = yield textResponse === null || textResponse === void 0 ? void 0 : (_textResponse$text = textResponse.text) === null || _textResponse$text === void 0 ? void 0 : _textResponse$text.call(textResponse); + var text = yield textResponse === null || textResponse === void 0 || (_textResponse$text = textResponse.text) === null || _textResponse$text === void 0 ? void 0 : _textResponse$text.call(textResponse); return this.messageFailureReasonFromText(text) || fallback; } catch (_) { return fallback; @@ -975,9 +959,9 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "messageFailureReasonFromPayload", value: function messageFailureReasonFromPayload(payload) { - var _payload$error, _payload$errors, _payload$errors2, _payload$errors2$, _payload$errors3, _payload$errors3$; + var _payload$error, _payload$errors, _payload$errors2, _payload$errors3; if (!payload) return null; - return [(_payload$error = payload.error) === null || _payload$error === void 0 ? void 0 : _payload$error.message, payload.message, (_payload$errors = payload.errors) === null || _payload$errors === void 0 ? void 0 : _payload$errors.message, (_payload$errors2 = payload.errors) === null || _payload$errors2 === void 0 ? void 0 : (_payload$errors2$ = _payload$errors2[0]) === null || _payload$errors2$ === void 0 ? void 0 : _payload$errors2$.message, (_payload$errors3 = payload.errors) === null || _payload$errors3 === void 0 ? void 0 : (_payload$errors3$ = _payload$errors3[0]) === null || _payload$errors3$ === void 0 ? void 0 : _payload$errors3$.description].find(reason => typeof reason === 'string' && reason.trim().length > 0); + return [(_payload$error = payload.error) === null || _payload$error === void 0 ? void 0 : _payload$error.message, payload.message, (_payload$errors = payload.errors) === null || _payload$errors === void 0 ? void 0 : _payload$errors.message, (_payload$errors2 = payload.errors) === null || _payload$errors2 === void 0 || (_payload$errors2 = _payload$errors2[0]) === null || _payload$errors2 === void 0 ? void 0 : _payload$errors2.message, (_payload$errors3 = payload.errors) === null || _payload$errors3 === void 0 || (_payload$errors3 = _payload$errors3[0]) === null || _payload$errors3 === void 0 ? void 0 : _payload$errors3.description].find(reason => typeof reason === 'string' && reason.trim().length > 0); } }, { key: "messageAttachmentsContainer", @@ -1048,9 +1032,7 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "removeAttachment", value: function removeAttachment(_ref2) { - var { - currentTarget - } = _ref2; + var currentTarget = _ref2.currentTarget; var attachment = currentTarget.closest("[data-hellotext--webchat-target='attachment']"); this.files = this.files.filter(file => file.name !== attachment.dataset.name); this.attachmentInputTarget.value = ''; @@ -1077,9 +1059,7 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "onEmojiSelect", value: function onEmojiSelect(_ref3) { - var { - detail: emoji - } = _ref3; + var emoji = _ref3.detail; var value = this.inputTarget.value; var start = this.inputTarget.selectionStart; var end = this.inputTarget.selectionEnd; @@ -1090,9 +1070,9 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "focusComposeInput", value: function focusComposeInput() { - var { - moveCursorToEnd = false - } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref4$moveCursorToEnd = _ref4.moveCursorToEnd, + moveCursorToEnd = _ref4$moveCursorToEnd === void 0 ? false : _ref4$moveCursorToEnd; if (!this.shouldAutofocusCompose) return false; if (this.hasInputTarget === false) return false; if (this.hasInputTarget === undefined && !this.inputTarget) return false; @@ -1167,7 +1147,6 @@ var _default = /*#__PURE__*/function (_Controller) { } } }]); - return _default; }(Controller); _default.messageTimestampFormatters = {}; _default.values = { diff --git a/lib/core/configuration.cjs b/lib/core/configuration.cjs index 6e7976aa..86d963f4 100644 --- a/lib/core/configuration.cjs +++ b/lib/core/configuration.cjs @@ -6,13 +6,14 @@ Object.defineProperty(exports, "__esModule", { exports.Configuration = void 0; var _forms = require("./configuration/forms"); var _locale = require("./configuration/locale"); +var _popup = require("./configuration/popup"); var _webchat = require("./configuration/webchat"); var _whatsapp = require("./configuration/whatsapp"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * @class Configuration * @classdesc @@ -20,15 +21,16 @@ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id * @property {Forms} [forms] - form configuration + * @property {Popup} [popup] - popup configuration * @property {Webchat} [webchat] - webchat configuration * @property {WhatsApp} [whatsappWidget] - WhatsApp widget configuration * @property {Locale} [locale] - locale configuration */ -let Configuration = /*#__PURE__*/function () { +let Configuration = exports.Configuration = /*#__PURE__*/function () { function Configuration() { _classCallCheck(this, Configuration); } - _createClass(Configuration, null, [{ + return _createClass(Configuration, null, [{ key: "assign", value: /** @@ -45,6 +47,8 @@ let Configuration = /*#__PURE__*/function () { Object.entries(props).forEach(([key, value]) => { if (key === 'forms') { this.forms = _forms.Forms.assign(value); + } else if (key === 'popup') { + this.popup = _popup.Popup.assign(value); } else if (key === 'webchat') { this.webchat = _webchat.Webchat.assign(value); } else if (key === 'whatsappWidget') { @@ -88,13 +92,12 @@ let Configuration = /*#__PURE__*/function () { } } }]); - return Configuration; }(); -exports.Configuration = Configuration; Configuration.apiRoot = 'https://api.hellotext.com/v1'; Configuration.actionCableUrl = 'wss://www.hellotext.com/cable'; Configuration.autoGenerateSession = true; Configuration.session = null; Configuration.forms = _forms.Forms; +Configuration.popup = _popup.Popup; Configuration.webchat = _webchat.Webchat; Configuration.whatsapp = _whatsapp.WhatsApp; \ No newline at end of file diff --git a/lib/core/configuration.js b/lib/core/configuration.js index 11fdb3af..8fab8ce8 100644 --- a/lib/core/configuration.js +++ b/lib/core/configuration.js @@ -1,10 +1,17 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Forms } from './configuration/forms'; import { Locale } from './configuration/locale'; +import { Popup } from './configuration/popup'; import { Webchat } from './configuration/webchat'; import { WhatsApp } from './configuration/whatsapp'; @@ -15,6 +22,7 @@ import { WhatsApp } from './configuration/whatsapp'; * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id * @property {Forms} [forms] - form configuration + * @property {Popup} [popup] - popup configuration * @property {Webchat} [webchat] - webchat configuration * @property {WhatsApp} [whatsappWidget] - WhatsApp widget configuration * @property {Locale} [locale] - locale configuration @@ -23,7 +31,7 @@ var Configuration = /*#__PURE__*/function () { function Configuration() { _classCallCheck(this, Configuration); } - _createClass(Configuration, null, [{ + return _createClass(Configuration, null, [{ key: "assign", value: /** @@ -38,9 +46,13 @@ var Configuration = /*#__PURE__*/function () { if (props) { var shouldInferActionCableUrl = Object.prototype.hasOwnProperty.call(props, 'apiRoot') && !Object.prototype.hasOwnProperty.call(props, 'actionCableUrl'); Object.entries(props).forEach(_ref => { - var [key, value] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; if (key === 'forms') { this.forms = Forms.assign(value); + } else if (key === 'popup') { + this.popup = Popup.assign(value); } else if (key === 'webchat') { this.webchat = Webchat.assign(value); } else if (key === 'whatsappWidget') { @@ -84,13 +96,13 @@ var Configuration = /*#__PURE__*/function () { } } }]); - return Configuration; }(); Configuration.apiRoot = 'https://api.hellotext.com/v1'; Configuration.actionCableUrl = 'wss://www.hellotext.com/cable'; Configuration.autoGenerateSession = true; Configuration.session = null; Configuration.forms = Forms; +Configuration.popup = Popup; Configuration.webchat = Webchat; Configuration.whatsapp = WhatsApp; export { Configuration }; \ No newline at end of file diff --git a/lib/core/configuration/forms.cjs b/lib/core/configuration/forms.cjs index bbd75520..1d8c335f 100644 --- a/lib/core/configuration/forms.cjs +++ b/lib/core/configuration/forms.cjs @@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.Forms = void 0; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * @class Forms * @classdesc @@ -16,11 +16,11 @@ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === * @property {Boolean} autoMount - whether to auto mount forms * @property {Boolean|String} successMessage - whether to show success message after form completion or not */ -let Forms = /*#__PURE__*/function () { +let Forms = exports.Forms = /*#__PURE__*/function () { function Forms() { _classCallCheck(this, Forms); } - _createClass(Forms, null, [{ + return _createClass(Forms, null, [{ key: "assign", value: /** @@ -42,8 +42,6 @@ let Forms = /*#__PURE__*/function () { return this.successMessage; } }]); - return Forms; }(); -exports.Forms = Forms; Forms.autoMount = true; Forms.successMessage = true; \ No newline at end of file diff --git a/lib/core/configuration/forms.js b/lib/core/configuration/forms.js index 305415b0..f8312318 100644 --- a/lib/core/configuration/forms.js +++ b/lib/core/configuration/forms.js @@ -1,8 +1,14 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * @class Forms * @classdesc @@ -14,7 +20,7 @@ var Forms = /*#__PURE__*/function () { function Forms() { _classCallCheck(this, Forms); } - _createClass(Forms, null, [{ + return _createClass(Forms, null, [{ key: "assign", value: /** @@ -25,7 +31,9 @@ var Forms = /*#__PURE__*/function () { function assign(props) { if (props) { Object.entries(props).forEach(_ref => { - var [key, value] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; this[key] = value; }); } @@ -37,7 +45,6 @@ var Forms = /*#__PURE__*/function () { return this.successMessage; } }]); - return Forms; }(); Forms.autoMount = true; Forms.successMessage = true; diff --git a/lib/core/configuration/locale.cjs b/lib/core/configuration/locale.cjs index 8e9ccc58..98520cc9 100644 --- a/lib/core/configuration/locale.cjs +++ b/lib/core/configuration/locale.cjs @@ -4,14 +4,14 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.Locale = void 0; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } var _fromHtmlLangProperty = /*#__PURE__*/_classPrivateFieldLooseKey("fromHtmlLangProperty"); var _fromMetaTag = /*#__PURE__*/_classPrivateFieldLooseKey("fromMetaTag"); var _fromBrowserLanguage = /*#__PURE__*/_classPrivateFieldLooseKey("fromBrowserLanguage"); @@ -22,11 +22,11 @@ var _fromBrowserLanguage = /*#__PURE__*/_classPrivateFieldLooseKey("fromBrowserL * Provides automatic locale detection from HTML lang attribute, meta tags, * and browser language with fallback to 'en'. */ -let Locale = /*#__PURE__*/function () { +let Locale = exports.Locale = /*#__PURE__*/function () { function Locale() { _classCallCheck(this, Locale); } - _createClass(Locale, null, [{ + return _createClass(Locale, null, [{ key: "identifier", get: /** @@ -57,20 +57,18 @@ let Locale = /*#__PURE__*/function () { return this.identifier; } }]); - return Locale; }(); -exports.Locale = Locale; function _get_fromHtmlLangProperty() { - var _document, _document$documentEle; - return (_document = document) === null || _document === void 0 ? void 0 : (_document$documentEle = _document.documentElement) === null || _document$documentEle === void 0 ? void 0 : _document$documentEle.lang; + var _document; + return (_document = document) === null || _document === void 0 || (_document = _document.documentElement) === null || _document === void 0 ? void 0 : _document.lang; } function _get_fromMetaTag() { - var _document2, _document2$querySelec; - return (_document2 = document) === null || _document2 === void 0 ? void 0 : (_document2$querySelec = _document2.querySelector('meta[name="locale"]')) === null || _document2$querySelec === void 0 ? void 0 : _document2$querySelec.content; + var _document2; + return (_document2 = document) === null || _document2 === void 0 || (_document2 = _document2.querySelector('meta[name="locale"]')) === null || _document2 === void 0 ? void 0 : _document2.content; } function _get_fromBrowserLanguage() { - var _navigator, _navigator$language; - return (_navigator = navigator) === null || _navigator === void 0 ? void 0 : (_navigator$language = _navigator.language) === null || _navigator$language === void 0 ? void 0 : _navigator$language.split('-')[0]; // Extract primary language + var _navigator; + return (_navigator = navigator) === null || _navigator === void 0 || (_navigator = _navigator.language) === null || _navigator === void 0 ? void 0 : _navigator.split('-')[0]; // Extract primary language } Object.defineProperty(Locale, _fromBrowserLanguage, { get: _get_fromBrowserLanguage, diff --git a/lib/core/configuration/locale.js b/lib/core/configuration/locale.js index 40c8f050..21aacaa3 100644 --- a/lib/core/configuration/locale.js +++ b/lib/core/configuration/locale.js @@ -1,11 +1,11 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } var _fromHtmlLangProperty = /*#__PURE__*/_classPrivateFieldLooseKey("fromHtmlLangProperty"); var _fromMetaTag = /*#__PURE__*/_classPrivateFieldLooseKey("fromMetaTag"); var _fromBrowserLanguage = /*#__PURE__*/_classPrivateFieldLooseKey("fromBrowserLanguage"); @@ -20,7 +20,7 @@ var Locale = /*#__PURE__*/function () { function Locale() { _classCallCheck(this, Locale); } - _createClass(Locale, null, [{ + return _createClass(Locale, null, [{ key: "identifier", get: /** @@ -51,19 +51,18 @@ var Locale = /*#__PURE__*/function () { return this.identifier; } }]); - return Locale; }(); function _get_fromHtmlLangProperty() { - var _document, _document$documentEle; - return (_document = document) === null || _document === void 0 ? void 0 : (_document$documentEle = _document.documentElement) === null || _document$documentEle === void 0 ? void 0 : _document$documentEle.lang; + var _document; + return (_document = document) === null || _document === void 0 || (_document = _document.documentElement) === null || _document === void 0 ? void 0 : _document.lang; } function _get_fromMetaTag() { - var _document2, _document2$querySelec; - return (_document2 = document) === null || _document2 === void 0 ? void 0 : (_document2$querySelec = _document2.querySelector('meta[name="locale"]')) === null || _document2$querySelec === void 0 ? void 0 : _document2$querySelec.content; + var _document2; + return (_document2 = document) === null || _document2 === void 0 || (_document2 = _document2.querySelector('meta[name="locale"]')) === null || _document2 === void 0 ? void 0 : _document2.content; } function _get_fromBrowserLanguage() { - var _navigator, _navigator$language; - return (_navigator = navigator) === null || _navigator === void 0 ? void 0 : (_navigator$language = _navigator.language) === null || _navigator$language === void 0 ? void 0 : _navigator$language.split('-')[0]; // Extract primary language + var _navigator; + return (_navigator = navigator) === null || _navigator === void 0 || (_navigator = _navigator.language) === null || _navigator === void 0 ? void 0 : _navigator.split('-')[0]; // Extract primary language } Object.defineProperty(Locale, _fromBrowserLanguage, { get: _get_fromBrowserLanguage, diff --git a/lib/core/configuration/popup.cjs b/lib/core/configuration/popup.cjs new file mode 100644 index 00000000..73fc8961 --- /dev/null +++ b/lib/core/configuration/popup.cjs @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Popup = void 0; +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @typedef {'auto' | 'mobile' | 'desktop'} PopupDevice + * @description Runtime device override for popup loading. + */ +/** + * @class Popup + * @classdesc Configuration for dashboard popups. + * @property {String} id - The popup id. + * @property {String} container - The container to append the popup to, defaults to 'body'. + * @property {PopupDevice} device - Runtime device preference, defaults to 'auto'. + */ +let Popup = exports.Popup = /*#__PURE__*/function () { + function Popup() { + _classCallCheck(this, Popup); + } + return _createClass(Popup, null, [{ + key: "id", + get: function () { + return this._id; + }, + set: function (value) { + this._id = value; + } + }, { + key: "container", + get: function () { + return this._container; + }, + set: function (value) { + this._container = value; + } + }, { + key: "device", + get: function () { + return this._device; + }, + set: function (value) { + if (!['auto', 'mobile', 'desktop'].includes(value)) { + throw new Error(`Invalid popup device value: ${value}`); + } + this._device = value; + } + }, { + key: "assign", + value: function assign(props) { + if (props) { + Object.entries(props).forEach(([key, value]) => { + this[key] = value; + }); + } + return this; + } + }]); +}(); +Popup._id = void 0; +Popup._container = 'body'; +Popup._device = 'auto'; \ No newline at end of file diff --git a/lib/core/configuration/popup.js b/lib/core/configuration/popup.js new file mode 100644 index 00000000..43e01076 --- /dev/null +++ b/lib/core/configuration/popup.js @@ -0,0 +1,72 @@ +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @typedef {'auto' | 'mobile' | 'desktop'} PopupDevice + * @description Runtime device override for popup loading. + */ +/** + * @class Popup + * @classdesc Configuration for dashboard popups. + * @property {String} id - The popup id. + * @property {String} container - The container to append the popup to, defaults to 'body'. + * @property {PopupDevice} device - Runtime device preference, defaults to 'auto'. + */ +var Popup = /*#__PURE__*/function () { + function Popup() { + _classCallCheck(this, Popup); + } + return _createClass(Popup, null, [{ + key: "id", + get: function get() { + return this._id; + }, + set: function set(value) { + this._id = value; + } + }, { + key: "container", + get: function get() { + return this._container; + }, + set: function set(value) { + this._container = value; + } + }, { + key: "device", + get: function get() { + return this._device; + }, + set: function set(value) { + if (!['auto', 'mobile', 'desktop'].includes(value)) { + throw new Error("Invalid popup device value: ".concat(value)); + } + this._device = value; + } + }, { + key: "assign", + value: function assign(props) { + if (props) { + Object.entries(props).forEach(_ref => { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + this[key] = value; + }); + } + return this; + } + }]); +}(); +Popup._id = void 0; +Popup._container = 'body'; +Popup._device = 'auto'; +export { Popup }; \ No newline at end of file diff --git a/lib/core/configuration/webchat.cjs b/lib/core/configuration/webchat.cjs index ff060407..39a30797 100644 --- a/lib/core/configuration/webchat.cjs +++ b/lib/core/configuration/webchat.cjs @@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.modes = exports.Webchat = void 0; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * @typedef {'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'} Placement * @description Valid placements for the webchat. @@ -45,7 +45,7 @@ const strategies = { /** * @enum {Mode} */ -const modes = { +const modes = exports.modes = { MODAL: 'modal', POPOVER: 'popover' }; @@ -85,12 +85,11 @@ const modes = { * @property {WhatsApp} whatsapp - WhatsApp handoff overrides. * @property {Strategy} strategy - the strategy used to position the webchat. Defaults to 'absolute' */ -exports.modes = modes; -let Webchat = /*#__PURE__*/function () { +let Webchat = exports.Webchat = /*#__PURE__*/function () { function Webchat() { _classCallCheck(this, Webchat); } - _createClass(Webchat, null, [{ + return _createClass(Webchat, null, [{ key: "container", get: function () { return this._container; @@ -273,9 +272,7 @@ let Webchat = /*#__PURE__*/function () { return typeof value === 'object' && value !== null && !Array.isArray(value); } }]); - return Webchat; }(); -exports.Webchat = Webchat; Webchat._id = void 0; Webchat._container = 'body'; Webchat._placement = 'bottom-right'; diff --git a/lib/core/configuration/webchat.js b/lib/core/configuration/webchat.js index 0e3f7774..79c189b7 100644 --- a/lib/core/configuration/webchat.js +++ b/lib/core/configuration/webchat.js @@ -1,8 +1,14 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * @typedef {'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'} Placement * @description Valid placements for the webchat. @@ -83,7 +89,7 @@ var Webchat = /*#__PURE__*/function () { function Webchat() { _classCallCheck(this, Webchat); } - _createClass(Webchat, null, [{ + return _createClass(Webchat, null, [{ key: "container", get: function get() { return this._container; @@ -125,7 +131,9 @@ var Webchat = /*#__PURE__*/function () { throw new Error('Style must be an object'); } Object.entries(value).forEach(_ref => { - var [key, value] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; if (!['primaryColor', 'secondaryColor', 'typography'].includes(key)) { throw new Error("Invalid style property: ".concat(key)); } @@ -147,16 +155,20 @@ var Webchat = /*#__PURE__*/function () { if (!this.isPlainObject(value)) { throw new Error('Appearance must be an object'); } - Object.entries(value).forEach(_ref2 => { - var [key, nestedValue] = _ref2; + Object.entries(value).forEach(_ref3 => { + var _ref4 = _slicedToArray(_ref3, 2), + key = _ref4[0], + nestedValue = _ref4[1]; if (!['header', 'launcher'].includes(key)) { throw new Error("Invalid appearance property: ".concat(key)); } if (!this.isPlainObject(nestedValue)) { throw new Error("Appearance ".concat(key, " must be an object")); } - Object.entries(nestedValue).forEach(_ref3 => { - var [nestedKey, propertyValue] = _ref3; + Object.entries(nestedValue).forEach(_ref5 => { + var _ref6 = _slicedToArray(_ref5, 2), + nestedKey = _ref6[0], + propertyValue = _ref6[1]; if (key === 'header' && nestedKey !== 'name') { throw new Error("Invalid appearance header property: ".concat(nestedKey)); } @@ -182,8 +194,10 @@ var Webchat = /*#__PURE__*/function () { if (!this.isPlainObject(value)) { throw new Error('WhatsApp must be an object'); } - Object.entries(value).forEach(_ref4 => { - var [key, nestedValue] = _ref4; + Object.entries(value).forEach(_ref7 => { + var _ref8 = _slicedToArray(_ref7, 2), + key = _ref8[0], + nestedValue = _ref8[1]; if (!['number', 'restrictToChannel'].includes(key)) { throw new Error("Invalid WhatsApp property: ".concat(key)); } @@ -253,8 +267,10 @@ var Webchat = /*#__PURE__*/function () { key: "assign", value: function assign(props) { if (props) { - Object.entries(props).forEach(_ref5 => { - var [key, value] = _ref5; + Object.entries(props).forEach(_ref9 => { + var _ref0 = _slicedToArray(_ref9, 2), + key = _ref0[0], + value = _ref0[1]; this[key] = value; }); } @@ -271,7 +287,6 @@ var Webchat = /*#__PURE__*/function () { return typeof value === 'object' && value !== null && !Array.isArray(value); } }]); - return Webchat; }(); Webchat._id = void 0; Webchat._container = 'body'; diff --git a/lib/core/configuration/whatsapp.cjs b/lib/core/configuration/whatsapp.cjs index 4dee0e50..05c09586 100644 --- a/lib/core/configuration/whatsapp.cjs +++ b/lib/core/configuration/whatsapp.cjs @@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.WhatsApp = void 0; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * @typedef {'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'} Placement * @description Valid placements for the WhatsApp widget. @@ -40,11 +40,11 @@ const placements = { * @property {String} body - Prefilled WhatsApp compose text. * @property {WhatsAppWidgetAppearance} appearance - Appearance overrides. */ -let WhatsApp = /*#__PURE__*/function () { +let WhatsApp = exports.WhatsApp = /*#__PURE__*/function () { function WhatsApp() { _classCallCheck(this, WhatsApp); } - _createClass(WhatsApp, null, [{ + return _createClass(WhatsApp, null, [{ key: "id", get: function () { return this._id; @@ -139,9 +139,7 @@ let WhatsApp = /*#__PURE__*/function () { return typeof value === 'object' && value !== null && !Array.isArray(value); } }]); - return WhatsApp; }(); -exports.WhatsApp = WhatsApp; WhatsApp._id = void 0; WhatsApp._container = 'body'; WhatsApp._placement = 'bottom-right'; diff --git a/lib/core/configuration/whatsapp.js b/lib/core/configuration/whatsapp.js index 810df729..18e63923 100644 --- a/lib/core/configuration/whatsapp.js +++ b/lib/core/configuration/whatsapp.js @@ -1,8 +1,14 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * @typedef {'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'} Placement * @description Valid placements for the WhatsApp widget. @@ -38,7 +44,7 @@ var WhatsApp = /*#__PURE__*/function () { function WhatsApp() { _classCallCheck(this, WhatsApp); } - _createClass(WhatsApp, null, [{ + return _createClass(WhatsApp, null, [{ key: "id", get: function get() { return this._id; @@ -75,15 +81,19 @@ var WhatsApp = /*#__PURE__*/function () { throw new Error('Appearance must be an object'); } Object.entries(value).forEach(_ref => { - var [key, nestedValue] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + nestedValue = _ref2[1]; if (key !== 'launcher') { throw new Error("Invalid appearance property: ".concat(key)); } if (!this.isPlainObject(nestedValue)) { throw new Error("Appearance ".concat(key, " must be an object")); } - Object.entries(nestedValue).forEach(_ref2 => { - var [nestedKey, propertyValue] = _ref2; + Object.entries(nestedValue).forEach(_ref3 => { + var _ref4 = _slicedToArray(_ref3, 2), + nestedKey = _ref4[0], + propertyValue = _ref4[1]; if (nestedKey !== 'iconUrl') { throw new Error("Invalid appearance launcher property: ".concat(nestedKey)); } @@ -123,8 +133,10 @@ var WhatsApp = /*#__PURE__*/function () { key: "assign", value: function assign(props) { if (props) { - Object.entries(props).forEach(_ref3 => { - var [key, value] = _ref3; + Object.entries(props).forEach(_ref5 => { + var _ref6 = _slicedToArray(_ref5, 2), + key = _ref6[0], + value = _ref6[1]; this[key] = value; }); } @@ -136,7 +148,6 @@ var WhatsApp = /*#__PURE__*/function () { return typeof value === 'object' && value !== null && !Array.isArray(value); } }]); - return WhatsApp; }(); WhatsApp._id = void 0; WhatsApp._container = 'body'; diff --git a/lib/core/event.cjs b/lib/core/event.cjs index 4f07e9fe..63cae00c 100644 --- a/lib/core/event.cjs +++ b/lib/core/event.cjs @@ -5,17 +5,17 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; var _errors = require("../errors"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let Event = /*#__PURE__*/function () { +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let Event = exports.default = /*#__PURE__*/function () { function Event() { _classCallCheck(this, Event); this.subscribers = {}; } - _createClass(Event, [{ + return _createClass(Event, [{ key: "addSubscriber", value: function addSubscriber(eventName, callback) { if (Event.invalid(eventName)) { @@ -40,7 +40,7 @@ let Event = /*#__PURE__*/function () { key: "dispatch", value: function dispatch(eventName, data) { var _this$subscribers$eve; - (_this$subscribers$eve = this.subscribers[eventName]) === null || _this$subscribers$eve === void 0 ? void 0 : _this$subscribers$eve.forEach(subscriber => { + (_this$subscribers$eve = this.subscribers[eventName]) === null || _this$subscribers$eve === void 0 || _this$subscribers$eve.forEach(subscriber => { subscriber(data); }); } @@ -65,7 +65,5 @@ let Event = /*#__PURE__*/function () { return this.events.find(eventName => eventName === name) !== undefined; } }]); - return Event; }(); -exports.default = Event; Event.events = ['session-set', 'utm-set', 'forms:collected', 'form:completed', 'webchat:mounted', 'webchat:opened', 'webchat:closed', 'webchat:message:sent', 'webchat:message:received', 'cart.added']; \ No newline at end of file diff --git a/lib/core/event.js b/lib/core/event.js index c4298c18..0e7fa86c 100644 --- a/lib/core/event.js +++ b/lib/core/event.js @@ -1,18 +1,18 @@ -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { InvalidEvent } from '../errors'; var Event = /*#__PURE__*/function () { function Event() { _classCallCheck(this, Event); this.subscribers = {}; } - _createClass(Event, [{ + return _createClass(Event, [{ key: "addSubscriber", value: function addSubscriber(eventName, callback) { if (Event.invalid(eventName)) { @@ -36,7 +36,7 @@ var Event = /*#__PURE__*/function () { key: "dispatch", value: function dispatch(eventName, data) { var _this$subscribers$eve; - (_this$subscribers$eve = this.subscribers[eventName]) === null || _this$subscribers$eve === void 0 ? void 0 : _this$subscribers$eve.forEach(subscriber => { + (_this$subscribers$eve = this.subscribers[eventName]) === null || _this$subscribers$eve === void 0 || _this$subscribers$eve.forEach(subscriber => { subscriber(data); }); } @@ -61,7 +61,6 @@ var Event = /*#__PURE__*/function () { return this.events.find(eventName => eventName === name) !== undefined; } }]); - return Event; }(); Event.events = ['session-set', 'utm-set', 'forms:collected', 'form:completed', 'webchat:mounted', 'webchat:opened', 'webchat:closed', 'webchat:message:sent', 'webchat:message:received', 'cart.added']; export { Event as default }; \ No newline at end of file diff --git a/lib/core/index.cjs b/lib/core/index.cjs index 5cf716c2..013ffa71 100644 --- a/lib/core/index.cjs +++ b/lib/core/index.cjs @@ -38,4 +38,4 @@ var _locale = require("./configuration/locale"); var _webchat = require("./configuration/webchat"); var _whatsapp = require("./configuration/whatsapp"); var _event = _interopRequireDefault(require("./event")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } \ No newline at end of file diff --git a/lib/core/sanitize_html.cjs b/lib/core/sanitize_html.cjs index 77f9852f..fc66f83e 100644 --- a/lib/core/sanitize_html.cjs +++ b/lib/core/sanitize_html.cjs @@ -7,7 +7,7 @@ exports.sanitizedRichTextFragment = sanitizedRichTextFragment; exports.sanitizedWebchatComponentFragment = sanitizedWebchatComponentFragment; exports.setSanitizedRichText = setSanitizedRichText; var _dompurify = _interopRequireDefault(require("dompurify")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } const RICH_TEXT_SANITIZER_OPTIONS = { ADD_ATTR: ['target'], ALLOW_DATA_ATTR: false, diff --git a/lib/errors/invalid_event.cjs b/lib/errors/invalid_event.cjs index 1b4400a2..7253bdcd 100644 --- a/lib/errors/invalid_event.cjs +++ b/lib/errors/invalid_event.cjs @@ -4,31 +4,29 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.InvalidEvent = void 0; -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -let InvalidEvent = /*#__PURE__*/function (_Error) { - _inherits(InvalidEvent, _Error); - var _super = _createSuper(InvalidEvent); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function (t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +let InvalidEvent = exports.InvalidEvent = /*#__PURE__*/function (_Error) { function InvalidEvent(event) { var _this; _classCallCheck(this, InvalidEvent); - _this = _super.call(this, `${event} is not valid. Please provide a valid event name`); + _this = _callSuper(this, InvalidEvent, [`${event} is not valid. Please provide a valid event name`]); _this.name = 'InvalidEvent'; return _this; } + _inherits(InvalidEvent, _Error); return _createClass(InvalidEvent); -}( /*#__PURE__*/_wrapNativeSuper(Error)); -exports.InvalidEvent = InvalidEvent; \ No newline at end of file +}(/*#__PURE__*/_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/lib/errors/invalid_event.js b/lib/errors/invalid_event.js index 61922a57..687d0a9d 100644 --- a/lib/errors/invalid_event.js +++ b/lib/errors/invalid_event.js @@ -1,28 +1,27 @@ -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } var InvalidEvent = /*#__PURE__*/function (_Error) { - _inherits(InvalidEvent, _Error); - var _super = _createSuper(InvalidEvent); function InvalidEvent(event) { var _this; _classCallCheck(this, InvalidEvent); - _this = _super.call(this, "".concat(event, " is not valid. Please provide a valid event name")); + _this = _callSuper(this, InvalidEvent, ["".concat(event, " is not valid. Please provide a valid event name")]); _this.name = 'InvalidEvent'; return _this; } + _inherits(InvalidEvent, _Error); return _createClass(InvalidEvent); -}( /*#__PURE__*/_wrapNativeSuper(Error)); +}(/*#__PURE__*/_wrapNativeSuper(Error)); export { InvalidEvent }; \ No newline at end of file diff --git a/lib/errors/not_initialized_error.cjs b/lib/errors/not_initialized_error.cjs index 548a2b14..ee4a148f 100644 --- a/lib/errors/not_initialized_error.cjs +++ b/lib/errors/not_initialized_error.cjs @@ -4,31 +4,29 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.NotInitializedError = void 0; -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -let NotInitializedError = /*#__PURE__*/function (_Error) { - _inherits(NotInitializedError, _Error); - var _super = _createSuper(NotInitializedError); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function (t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +let NotInitializedError = exports.NotInitializedError = /*#__PURE__*/function (_Error) { function NotInitializedError() { var _this; _classCallCheck(this, NotInitializedError); - _this = _super.call(this, 'You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id'); + _this = _callSuper(this, NotInitializedError, ['You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id']); _this.name = 'NotInitializedError'; return _this; } + _inherits(NotInitializedError, _Error); return _createClass(NotInitializedError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); -exports.NotInitializedError = NotInitializedError; \ No newline at end of file +}(/*#__PURE__*/_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/lib/errors/not_initialized_error.js b/lib/errors/not_initialized_error.js index e21ad6ae..33c5058d 100644 --- a/lib/errors/not_initialized_error.js +++ b/lib/errors/not_initialized_error.js @@ -1,28 +1,27 @@ -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } var NotInitializedError = /*#__PURE__*/function (_Error) { - _inherits(NotInitializedError, _Error); - var _super = _createSuper(NotInitializedError); function NotInitializedError() { var _this; _classCallCheck(this, NotInitializedError); - _this = _super.call(this, 'You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id'); + _this = _callSuper(this, NotInitializedError, ['You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id']); _this.name = 'NotInitializedError'; return _this; } + _inherits(NotInitializedError, _Error); return _createClass(NotInitializedError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); +}(/*#__PURE__*/_wrapNativeSuper(Error)); export { NotInitializedError }; \ No newline at end of file diff --git a/lib/hellotext.cjs b/lib/hellotext.cjs index a7f80f65..8cc3d708 100644 --- a/lib/hellotext.cjs +++ b/lib/hellotext.cjs @@ -8,18 +8,17 @@ var _core = require("./core"); var _api = _interopRequireWildcard(require("./api")); var _models = require("./models"); var _errors = require("./errors"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } let Hellotext = /*#__PURE__*/function () { function Hellotext() { _classCallCheck(this, Hellotext); } - _createClass(Hellotext, null, [{ + return _createClass(Hellotext, null, [{ key: "initialize", value: /** @@ -35,6 +34,7 @@ let Hellotext = /*#__PURE__*/function () { this.forms = new _models.FormCollection(); this.query = new _models.Query(); const businessData = await this.business.hydrate(); + const popupConfig = config.popup === false ? false : this.mergePopupConfig(businessData && businessData.popup || {}, config.popup || {}); const webchatConfig = config.webchat === false ? false : this.mergeWebchatConfig(businessData && businessData.webchat || {}, config.webchat || {}); const whatsappConfig = config.whatsappWidget === false ? false : this.mergeWhatsAppConfig(businessData && businessData.whatsapp || {}, config.whatsappWidget || {}); const hasExplicitBehaviourOverride = config.webchat && config.webchat !== false && Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour'); @@ -47,6 +47,10 @@ let Hellotext = /*#__PURE__*/function () { _core.Configuration.whatsapp.assign(whatsappConfig); this.whatsapp = await _models.WhatsAppWidget.load(whatsappConfig.id); } + if (popupConfig && popupConfig.id) { + _core.Configuration.popup.assign(popupConfig); + this.popup = await _models.Popup.load(popupConfig.id); + } if (typeof MutationObserver !== 'undefined') { this.forms.collectExistingFormsOnPage(); } @@ -61,6 +65,11 @@ let Hellotext = /*#__PURE__*/function () { value: function mergeWhatsAppConfig(dashboardConfig, localConfig) { return this.deepMergePlainObjects(dashboardConfig, localConfig); } + }, { + key: "mergePopupConfig", + value: function mergePopupConfig(dashboardConfig, localConfig) { + return this.deepMergePlainObjects(dashboardConfig, localConfig); + } }, { key: "deepMergePlainObjects", value: function deepMergePlainObjects(base, override) { @@ -230,12 +239,11 @@ let Hellotext = /*#__PURE__*/function () { }; } }]); - return Hellotext; }(); Hellotext.eventEmitter = new _core.Event(); Hellotext.forms = void 0; Hellotext.business = void 0; +Hellotext.popup = void 0; Hellotext.webchat = void 0; Hellotext.whatsapp = void 0; -var _default = Hellotext; -exports.default = _default; \ No newline at end of file +var _default = exports.default = Hellotext; \ No newline at end of file diff --git a/lib/hellotext.js b/lib/hellotext.js index fe5767be..d2b25126 100644 --- a/lib/hellotext.js +++ b/lib/hellotext.js @@ -1,24 +1,30 @@ -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Configuration, Event } from './core'; import API, { Response, keepaliveFor } from './api'; -import { Business, Fingerprint, FormCollection, Page, Query, Session, User, Webchat, WhatsAppWidget } from './models'; +import { Business, Fingerprint, FormCollection, Page, Popup, Query, Session, User, Webchat, WhatsAppWidget } from './models'; import { NotInitializedError } from './errors'; var Hellotext = /*#__PURE__*/function () { function Hellotext() { _classCallCheck(this, Hellotext); } - _createClass(Hellotext, null, [{ + return _createClass(Hellotext, null, [{ key: "initialize", - value: + value: ( /** * initialize the module. * @param business public business id @@ -34,6 +40,7 @@ var Hellotext = /*#__PURE__*/function () { this.forms = new FormCollection(); this.query = new Query(); var businessData = yield this.business.hydrate(); + var popupConfig = config.popup === false ? false : this.mergePopupConfig(businessData && businessData.popup || {}, config.popup || {}); var webchatConfig = config.webchat === false ? false : this.mergeWebchatConfig(businessData && businessData.webchat || {}, config.webchat || {}); var whatsappConfig = config.whatsappWidget === false ? false : this.mergeWhatsAppConfig(businessData && businessData.whatsapp || {}, config.whatsappWidget || {}); var hasExplicitBehaviourOverride = config.webchat && config.webchat !== false && Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour'); @@ -46,6 +53,10 @@ var Hellotext = /*#__PURE__*/function () { Configuration.whatsapp.assign(whatsappConfig); this.whatsapp = yield WhatsAppWidget.load(whatsappConfig.id); } + if (popupConfig && popupConfig.id) { + Configuration.popup.assign(popupConfig); + this.popup = yield Popup.load(popupConfig.id); + } if (typeof MutationObserver !== 'undefined') { this.forms.collectExistingFormsOnPage(); } @@ -54,7 +65,7 @@ var Hellotext = /*#__PURE__*/function () { return _initialize.apply(this, arguments); } return initialize; - }() + }()) }, { key: "mergeWebchatConfig", value: function mergeWebchatConfig(dashboardConfig, localConfig) { @@ -65,12 +76,19 @@ var Hellotext = /*#__PURE__*/function () { value: function mergeWhatsAppConfig(dashboardConfig, localConfig) { return this.deepMergePlainObjects(dashboardConfig, localConfig); } + }, { + key: "mergePopupConfig", + value: function mergePopupConfig(dashboardConfig, localConfig) { + return this.deepMergePlainObjects(dashboardConfig, localConfig); + } }, { key: "deepMergePlainObjects", value: function deepMergePlainObjects(base, override) { var result = _objectSpread({}, base); Object.entries(override).forEach(_ref => { - var [key, value] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; if (this.isPlainObject(value) && this.isPlainObject(result[key])) { result[key] = this.deepMergePlainObjects(result[key], value); } else { @@ -94,7 +112,7 @@ var Hellotext = /*#__PURE__*/function () { */ }, { key: "track", - value: function () { + value: (function () { var _track = _asyncToGenerator(function* (action) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.notInitialized) { @@ -138,9 +156,10 @@ var Hellotext = /*#__PURE__*/function () { * @param { IdentificationOptions } options - the options for the identification * @returns {Promise} */ + ) }, { key: "identify", - value: function () { + value: (function () { var _identify = _asyncToGenerator(function* (externalId) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var fingerprint = yield Fingerprint.generate(this.session, externalId, options); @@ -177,6 +196,7 @@ var Hellotext = /*#__PURE__*/function () { * * @returns {void} */ + ) }, { key: "forget", value: function forget() { @@ -244,11 +264,11 @@ var Hellotext = /*#__PURE__*/function () { }; } }]); - return Hellotext; }(); Hellotext.eventEmitter = new Event(); Hellotext.forms = void 0; Hellotext.business = void 0; +Hellotext.popup = void 0; Hellotext.webchat = void 0; Hellotext.whatsapp = void 0; export default Hellotext; \ No newline at end of file diff --git a/lib/index.cjs b/lib/index.cjs index b63d8a77..a0e8a2b0 100644 --- a/lib/index.cjs +++ b/lib/index.cjs @@ -8,14 +8,15 @@ var _stimulus = require("@hotwired/stimulus"); var _hellotext = _interopRequireDefault(require("./hellotext")); var _form_controller = _interopRequireDefault(require("./controllers/form_controller")); var _message_controller = _interopRequireDefault(require("./controllers/message_controller")); +var _popup_controller = _interopRequireDefault(require("./controllers/popup_controller")); var _emoji_picker_controller = _interopRequireDefault(require("./controllers/webchat/emoji_picker_controller")); var _webchat_controller = _interopRequireDefault(require("./controllers/webchat_controller")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } const application = _stimulus.Application.start(); application.register('hellotext--form', _form_controller.default); +application.register('hellotext--popup', _popup_controller.default); application.register('hellotext--webchat', _webchat_controller.default); application.register('hellotext--webchat--emoji', _emoji_picker_controller.default); application.register('hellotext--message', _message_controller.default); window.Hellotext = _hellotext.default; -var _default = _hellotext.default; -exports.default = _default; \ No newline at end of file +var _default = exports.default = _hellotext.default; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index 12fe9247..145e3f4a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -2,10 +2,12 @@ import { Application } from '@hotwired/stimulus'; import Hellotext from './hellotext'; import FormController from './controllers/form_controller'; import MessageController from './controllers/message_controller'; +import PopupController from './controllers/popup_controller'; import WebChatEmojiController from './controllers/webchat/emoji_picker_controller'; import WebchatController from './controllers/webchat_controller'; var application = Application.start(); application.register('hellotext--form', FormController); +application.register('hellotext--popup', PopupController); application.register('hellotext--webchat', WebchatController); application.register('hellotext--webchat--emoji', WebChatEmojiController); application.register('hellotext--message', MessageController); diff --git a/lib/locales/en.cjs b/lib/locales/en.cjs index c475cb20..cb23ef2f 100644 --- a/lib/locales/en.cjs +++ b/lib/locales/en.cjs @@ -4,7 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; -var _default = { +var _default = exports.default = { white_label: { powered_by: 'By' }, @@ -18,5 +18,4 @@ var _default = { phone_and_email: 'Click the links sent via SMS and email to verify your submission.', none: 'Your submission has been received.' } -}; -exports.default = _default; \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/locales/es.cjs b/lib/locales/es.cjs index aee207d9..197260c1 100644 --- a/lib/locales/es.cjs +++ b/lib/locales/es.cjs @@ -4,7 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; -var _default = { +var _default = exports.default = { white_label: { powered_by: 'Por' }, @@ -18,5 +18,4 @@ var _default = { phone_and_email: 'Haga clic en los enlaces enviados por SMS y e-mail para verificar su envío.', none: 'Su envío ha sido recibido.' } -}; -exports.default = _default; \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/locales/index.cjs b/lib/locales/index.cjs index 4d46917f..24460a35 100644 --- a/lib/locales/index.cjs +++ b/lib/locales/index.cjs @@ -6,9 +6,8 @@ Object.defineProperty(exports, "__esModule", { exports.default = void 0; var _en = _interopRequireDefault(require("./en")); var _es = _interopRequireDefault(require("./es")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _default = { +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var _default = exports.default = { en: _en.default, es: _es.default -}; -exports.default = _default; \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/models/business.cjs b/lib/models/business.cjs index bc9a6e88..37b6b451 100644 --- a/lib/models/business.cjs +++ b/lib/models/business.cjs @@ -6,12 +6,12 @@ Object.defineProperty(exports, "__esModule", { exports.Business = void 0; var _locales = _interopRequireDefault(require("../locales")); var _businesses = _interopRequireDefault(require("../api/businesses")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } const stylesheetAttribute = 'data-hellotext-stylesheet'; const stylesheetLoadTimeout = 10000; @@ -37,7 +37,9 @@ const stylesheetLoadTimeout = 10000; * @property {Object} [features] - Feature flags enabled for the business. * @property {String} [locale] - Default dashboard locale for the business. * @property {String} [style_url] - Stylesheet URL to inject for dashboard-managed surfaces. + * @property {{id: String}|null} [popup] - Dashboard popup defaults. * @property {BusinessWebchat|null} [webchat] - Dashboard webchat defaults. + * @property {{id: String}|null} [whatsapp] - Dashboard WhatsApp widget defaults. * @property {String|Array} [whitelist] - Domain whitelist configuration. * @property {String} [subscription] - Current business subscription tier. */ @@ -45,7 +47,7 @@ const stylesheetLoadTimeout = 10000; /** * Public business context used by the SDK for tracking, forms, and webchat defaults. */ -let Business = /*#__PURE__*/function () { +let Business = exports.Business = /*#__PURE__*/function () { /** * @param {String} id - Public business id. */ @@ -65,7 +67,7 @@ let Business = /*#__PURE__*/function () { * * @returns {Promise} */ - _createClass(Business, [{ + return _createClass(Business, [{ key: "hydrate", value: async function hydrate() { try { @@ -217,6 +219,4 @@ let Business = /*#__PURE__*/function () { return linkTag.dataset.hellotextStylesheetLoaded === 'true' || !!linkTag.sheet; } }]); - return Business; -}(); -exports.Business = Business; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/business.js b/lib/models/business.js index 89b1572c..49065885 100644 --- a/lib/models/business.js +++ b/lib/models/business.js @@ -1,10 +1,10 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import locales from '../locales'; import BusinessesAPI from '../api/businesses'; var stylesheetAttribute = 'data-hellotext-stylesheet'; @@ -32,7 +32,9 @@ var stylesheetLoadTimeout = 10000; * @property {Object} [features] - Feature flags enabled for the business. * @property {String} [locale] - Default dashboard locale for the business. * @property {String} [style_url] - Stylesheet URL to inject for dashboard-managed surfaces. + * @property {{id: String}|null} [popup] - Dashboard popup defaults. * @property {BusinessWebchat|null} [webchat] - Dashboard webchat defaults. + * @property {{id: String}|null} [whatsapp] - Dashboard WhatsApp widget defaults. * @property {String|Array} [whitelist] - Domain whitelist configuration. * @property {String} [subscription] - Current business subscription tier. */ @@ -60,9 +62,9 @@ var Business = /*#__PURE__*/function () { * * @returns {Promise} */ - _createClass(Business, [{ + return _createClass(Business, [{ key: "hydrate", - value: function () { + value: (function () { var _hydrate = _asyncToGenerator(function* () { try { var response = yield BusinessesAPI.get(this.id); @@ -91,6 +93,7 @@ var Business = /*#__PURE__*/function () { * @param {BusinessData} data * @returns {void} */ + ) }, { key: "setData", value: function setData(data) { @@ -217,6 +220,5 @@ var Business = /*#__PURE__*/function () { return linkTag.dataset.hellotextStylesheetLoaded === 'true' || !!linkTag.sheet; } }]); - return Business; }(); export { Business }; \ No newline at end of file diff --git a/lib/models/cookies.cjs b/lib/models/cookies.cjs index c6a5df59..6adbe2ef 100644 --- a/lib/models/cookies.cjs +++ b/lib/models/cookies.cjs @@ -6,17 +6,17 @@ Object.defineProperty(exports, "__esModule", { exports.Cookies = void 0; var _hellotext = _interopRequireDefault(require("../hellotext")); var _page = require("./page"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let Cookies = /*#__PURE__*/function () { +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let Cookies = exports.Cookies = /*#__PURE__*/function () { function Cookies() { _classCallCheck(this, Cookies); } - _createClass(Cookies, null, [{ + return _createClass(Cookies, null, [{ key: "set", value: function set(name, value) { if (typeof document !== 'undefined') { @@ -62,6 +62,4 @@ let Cookies = /*#__PURE__*/function () { } } }]); - return Cookies; -}(); -exports.Cookies = Cookies; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/cookies.js b/lib/models/cookies.js index 2ccbe69e..2ff29606 100644 --- a/lib/models/cookies.js +++ b/lib/models/cookies.js @@ -1,15 +1,15 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import Hellotext from '../hellotext'; import { Page } from './page'; var Cookies = /*#__PURE__*/function () { function Cookies() { _classCallCheck(this, Cookies); } - _createClass(Cookies, null, [{ + return _createClass(Cookies, null, [{ key: "set", value: function set(name, value) { if (typeof document !== 'undefined') { @@ -55,6 +55,5 @@ var Cookies = /*#__PURE__*/function () { } } }]); - return Cookies; }(); export { Cookies }; \ No newline at end of file diff --git a/lib/models/fingerprint.cjs b/lib/models/fingerprint.cjs index ebd89381..7d20e5b9 100644 --- a/lib/models/fingerprint.cjs +++ b/lib/models/fingerprint.cjs @@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.Fingerprint = void 0; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function normalizeValue(value) { // Collapse "missing" values so callers can add optional fields incrementally // without changing the fingerprint when the effective payload is the same. @@ -69,11 +69,11 @@ async function sha256(value) { const hex = Array.from(new Uint8Array(digest)).map(byte => byte.toString(16).padStart(2, '0')).join(''); return `v1:${hex}`; } -let Fingerprint = /*#__PURE__*/function () { +let Fingerprint = exports.Fingerprint = /*#__PURE__*/function () { function Fingerprint() { _classCallCheck(this, Fingerprint); } - _createClass(Fingerprint, null, [{ + return _createClass(Fingerprint, null, [{ key: "matches", value: function matches(storedFingerprint, fingerprint) { return !!storedFingerprint && storedFingerprint === fingerprint; @@ -84,6 +84,4 @@ let Fingerprint = /*#__PURE__*/function () { return await sha256(serializePayload(session, userId, options)); } }]); - return Fingerprint; -}(); -exports.Fingerprint = Fingerprint; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/fingerprint.js b/lib/models/fingerprint.js index 9532a311..66117284 100644 --- a/lib/models/fingerprint.js +++ b/lib/models/fingerprint.js @@ -1,13 +1,13 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function normalizeValue(value) { // Collapse "missing" values so callers can add optional fields incrementally // without changing the fingerprint when the effective payload is the same. @@ -78,7 +78,7 @@ var Fingerprint = /*#__PURE__*/function () { function Fingerprint() { _classCallCheck(this, Fingerprint); } - _createClass(Fingerprint, null, [{ + return _createClass(Fingerprint, null, [{ key: "matches", value: function matches(storedFingerprint, fingerprint) { return !!storedFingerprint && storedFingerprint === fingerprint; @@ -96,6 +96,5 @@ var Fingerprint = /*#__PURE__*/function () { return generate; }() }]); - return Fingerprint; }(); export { Fingerprint }; \ No newline at end of file diff --git a/lib/models/form.cjs b/lib/models/form.cjs index ebeee4ce..ed0b03d2 100644 --- a/lib/models/form.cjs +++ b/lib/models/form.cjs @@ -8,17 +8,17 @@ var _hellotext = _interopRequireDefault(require("../hellotext")); var _input_builder = require("../builders/input_builder"); var _logo_builder = require("../builders/logo_builder"); var _sanitize_html = require("../core/sanitize_html"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } var _findOrCreateComponent = /*#__PURE__*/_classPrivateFieldLooseKey("findOrCreateComponent"); -let Form = /*#__PURE__*/function () { +let Form = exports.Form = /*#__PURE__*/function () { function Form(data, element = null) { _classCallCheck(this, Form); Object.defineProperty(this, _findOrCreateComponent, { @@ -27,14 +27,14 @@ let Form = /*#__PURE__*/function () { this.data = data; this.element = element || document.querySelector(`[data-hello-form="${this.id}"]`) || document.createElement('form'); } - _createClass(Form, [{ + return _createClass(Form, [{ key: "mount", value: async function mount({ ifCompleted = true } = {}) { if (ifCompleted && this.hasBeenCompleted) { var _this$element; - (_this$element = this.element) === null || _this$element === void 0 ? void 0 : _this$element.remove(); + (_this$element = this.element) === null || _this$element === void 0 || _this$element.remove(); return _hellotext.default.eventEmitter.dispatch('form:completed', { id: this.id, ...JSON.parse(localStorage.getItem(`hello-form-${this.id}`)) @@ -153,9 +153,7 @@ let Form = /*#__PURE__*/function () { }]; } }]); - return Form; }(); -exports.Form = Form; function _findOrCreateComponent2(selector, tag) { const existingElement = this.element.querySelector(selector); if (existingElement) { diff --git a/lib/models/form.js b/lib/models/form.js index 3630e178..945741cc 100644 --- a/lib/models/form.js +++ b/lib/models/form.js @@ -1,16 +1,16 @@ -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } import Hellotext from '../hellotext'; import { InputBuilder } from '../builders/input_builder'; import { LogoBuilder } from '../builders/logo_builder'; @@ -26,16 +26,16 @@ var Form = /*#__PURE__*/function () { this.data = data; this.element = element || document.querySelector("[data-hello-form=\"".concat(this.id, "\"]")) || document.createElement('form'); } - _createClass(Form, [{ + return _createClass(Form, [{ key: "mount", value: function () { var _mount = _asyncToGenerator(function* () { - var { - ifCompleted = true - } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$ifCompleted = _ref.ifCompleted, + ifCompleted = _ref$ifCompleted === void 0 ? true : _ref$ifCompleted; if (ifCompleted && this.hasBeenCompleted) { var _this$element; - (_this$element = this.element) === null || _this$element === void 0 ? void 0 : _this$element.remove(); + (_this$element = this.element) === null || _this$element === void 0 || _this$element.remove(); return Hellotext.eventEmitter.dispatch('form:completed', _objectSpread({ id: this.id }, JSON.parse(localStorage.getItem("hello-form-".concat(this.id))))); @@ -158,7 +158,6 @@ var Form = /*#__PURE__*/function () { }]; } }]); - return Form; }(); function _findOrCreateComponent2(selector, tag) { var existingElement = this.element.querySelector(selector); diff --git a/lib/models/form_collection.cjs b/lib/models/form_collection.cjs index c7807d9c..8a6d42e5 100644 --- a/lib/models/form_collection.cjs +++ b/lib/models/form_collection.cjs @@ -9,17 +9,17 @@ var _hellotext = _interopRequireDefault(require("../hellotext")); var _core = require("../core"); var _form = require("./form"); var _errors = require("../errors"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } var _formIdsToFetch = /*#__PURE__*/_classPrivateFieldLooseKey("formIdsToFetch"); -let FormCollection = /*#__PURE__*/function () { +let FormCollection = exports.FormCollection = /*#__PURE__*/function () { function FormCollection() { _classCallCheck(this, FormCollection); Object.defineProperty(this, _formIdsToFetch, { @@ -38,7 +38,7 @@ let FormCollection = /*#__PURE__*/function () { }); } } - _createClass(FormCollection, [{ + return _createClass(FormCollection, [{ key: "collectExistingFormsOnPage", value: function collectExistingFormsOnPage() { if (Array.from(document.querySelectorAll('[data-hello-form]')).length > 0) { @@ -124,9 +124,7 @@ let FormCollection = /*#__PURE__*/function () { return this.forms.length; } }]); - return FormCollection; }(); -exports.FormCollection = FormCollection; function _get_formIdsToFetch() { return Array.from(document.querySelectorAll('[data-hello-form]')).map(form => form.dataset.helloForm).filter(this.excludes); } \ No newline at end of file diff --git a/lib/models/form_collection.js b/lib/models/form_collection.js index 058936ac..0de4fdb5 100644 --- a/lib/models/form_collection.js +++ b/lib/models/form_collection.js @@ -1,13 +1,13 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } import API from '../api/forms'; import Hellotext from '../hellotext'; import { Configuration, Locale } from '../core'; @@ -33,7 +33,7 @@ var FormCollection = /*#__PURE__*/function () { }); } } - _createClass(FormCollection, [{ + return _createClass(FormCollection, [{ key: "collectExistingFormsOnPage", value: function collectExistingFormsOnPage() { if (Array.from(document.querySelectorAll('[data-hello-form]')).length > 0) { @@ -125,7 +125,6 @@ var FormCollection = /*#__PURE__*/function () { return this.forms.length; } }]); - return FormCollection; }(); function _get_formIdsToFetch() { return Array.from(document.querySelectorAll('[data-hello-form]')).map(form => form.dataset.helloForm).filter(this.excludes); diff --git a/lib/models/index.cjs b/lib/models/index.cjs index b639d35d..dd79fe79 100644 --- a/lib/models/index.cjs +++ b/lib/models/index.cjs @@ -39,6 +39,12 @@ Object.defineProperty(exports, "Page", { return _page.Page; } }); +Object.defineProperty(exports, "Popup", { + enumerable: true, + get: function () { + return _popup.Popup; + } +}); Object.defineProperty(exports, "Query", { enumerable: true, get: function () { @@ -81,6 +87,7 @@ var _fingerprint = require("./fingerprint"); var _form = require("./form"); var _form_collection = require("./form_collection"); var _page = require("./page"); +var _popup = require("./popup"); var _query = require("./query"); var _session = require("./session"); var _user = require("./user"); diff --git a/lib/models/index.js b/lib/models/index.js index 1e230a8e..464cd818 100644 --- a/lib/models/index.js +++ b/lib/models/index.js @@ -4,6 +4,7 @@ export { Fingerprint } from './fingerprint'; export { Form } from './form'; export { FormCollection } from './form_collection'; export { Page } from './page'; +export { Popup } from './popup'; export { Query } from './query'; export { Session } from './session'; export { User } from './user'; diff --git a/lib/models/page.cjs b/lib/models/page.cjs index 5343b2fc..2f20c39c 100644 --- a/lib/models/page.cjs +++ b/lib/models/page.cjs @@ -5,12 +5,12 @@ Object.defineProperty(exports, "__esModule", { }); exports.Page = void 0; var _utm = require("./utm"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let Page = /*#__PURE__*/function () { +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let Page = exports.Page = /*#__PURE__*/function () { function Page(url = null) { _classCallCheck(this, Page); this.utm = new _utm.UTM(); @@ -21,7 +21,7 @@ let Page = /*#__PURE__*/function () { * Get the current page URL * @returns {string} The page URL */ - _createClass(Page, [{ + return _createClass(Page, [{ key: "url", get: function () { return this._url !== null && this._url !== undefined ? this._url : window.location.href; @@ -159,6 +159,4 @@ let Page = /*#__PURE__*/function () { } } }]); - return Page; -}(); -exports.Page = Page; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/page.js b/lib/models/page.js index 6f498c8a..d4ba0605 100644 --- a/lib/models/page.js +++ b/lib/models/page.js @@ -1,8 +1,8 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { UTM } from './utm'; var Page = /*#__PURE__*/function () { function Page() { @@ -16,7 +16,7 @@ var Page = /*#__PURE__*/function () { * Get the current page URL * @returns {string} The page URL */ - _createClass(Page, [{ + return _createClass(Page, [{ key: "url", get: function get() { return this._url !== null && this._url !== undefined ? this._url : window.location.href; @@ -155,6 +155,5 @@ var Page = /*#__PURE__*/function () { } } }]); - return Page; }(); export { Page }; \ No newline at end of file diff --git a/lib/models/popup.cjs b/lib/models/popup.cjs new file mode 100644 index 00000000..29d3a132 --- /dev/null +++ b/lib/models/popup.cjs @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Popup = void 0; +var _core = require("../core"); +var _api = _interopRequireDefault(require("../api")); +var _business = require("./business"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let Popup = exports.Popup = /*#__PURE__*/function () { + function Popup(data) { + _classCallCheck(this, Popup); + this.data = data; + this.mounted = false; + this.rendered = Promise.resolve(false); + } + return _createClass(Popup, [{ + key: "render", + value: async function render() { + if (!this.data.html) return false; + const container = this.containerToAppendTo; + if (!container) { + console.warn(`Hellotext popup was not mounted because the container ${_core.Configuration.popup.container} was not found.`); + return false; + } + if (!(await this.stylesheetLoaded)) { + console.warn('Hellotext popup was not mounted because its stylesheet failed to load.'); + return false; + } + container.appendChild(this.data.html); + this.mounted = true; + return true; + } + }, { + key: "containerToAppendTo", + get: function () { + try { + return document.querySelector(_core.Configuration.popup.container); + } catch (_) { + return null; + } + } + }, { + key: "stylesheetLoaded", + get: function () { + return _business.Business.waitForStylesheet(_business.Business.latestStylesheet); + } + }], [{ + key: "load", + value: async function load(id) { + const popup = new Popup({ + id, + html: await _api.default.popups.get(id) + }); + popup.rendered = popup.render(); + return popup; + } + }]); +}(); \ No newline at end of file diff --git a/lib/models/popup.js b/lib/models/popup.js new file mode 100644 index 00000000..b1e9fb09 --- /dev/null +++ b/lib/models/popup.js @@ -0,0 +1,73 @@ +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +import { Configuration } from '../core'; +import API from '../api'; +import { Business } from './business'; +var Popup = /*#__PURE__*/function () { + function Popup(data) { + _classCallCheck(this, Popup); + this.data = data; + this.mounted = false; + this.rendered = Promise.resolve(false); + } + return _createClass(Popup, [{ + key: "render", + value: function () { + var _render = _asyncToGenerator(function* () { + if (!this.data.html) return false; + var container = this.containerToAppendTo; + if (!container) { + console.warn("Hellotext popup was not mounted because the container ".concat(Configuration.popup.container, " was not found.")); + return false; + } + if (!(yield this.stylesheetLoaded)) { + console.warn('Hellotext popup was not mounted because its stylesheet failed to load.'); + return false; + } + container.appendChild(this.data.html); + this.mounted = true; + return true; + }); + function render() { + return _render.apply(this, arguments); + } + return render; + }() + }, { + key: "containerToAppendTo", + get: function get() { + try { + return document.querySelector(Configuration.popup.container); + } catch (_) { + return null; + } + } + }, { + key: "stylesheetLoaded", + get: function get() { + return Business.waitForStylesheet(Business.latestStylesheet); + } + }], [{ + key: "load", + value: function () { + var _load = _asyncToGenerator(function* (id) { + var popup = new Popup({ + id, + html: yield API.popups.get(id) + }); + popup.rendered = popup.render(); + return popup; + }); + function load(_x) { + return _load.apply(this, arguments); + } + return load; + }() + }]); +}(); +export { Popup }; \ No newline at end of file diff --git a/lib/models/query.cjs b/lib/models/query.cjs index a75b7749..4e4c173b 100644 --- a/lib/models/query.cjs +++ b/lib/models/query.cjs @@ -4,17 +4,17 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.Query = void 0; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let Query = /*#__PURE__*/function () { +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let Query = exports.Query = /*#__PURE__*/function () { function Query() { _classCallCheck(this, Query); this.urlSearchParams = new URLSearchParams(window.location.search); } - _createClass(Query, [{ + return _createClass(Query, [{ key: "get", value: function get(param) { return this.urlSearchParams.get(this.toHellotextParam(param)); @@ -45,6 +45,4 @@ let Query = /*#__PURE__*/function () { return new this().inPreviewMode; } }]); - return Query; -}(); -exports.Query = Query; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/query.js b/lib/models/query.js index 5e137481..6f7fd221 100644 --- a/lib/models/query.js +++ b/lib/models/query.js @@ -1,14 +1,14 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } var Query = /*#__PURE__*/function () { function Query() { _classCallCheck(this, Query); this.urlSearchParams = new URLSearchParams(window.location.search); } - _createClass(Query, [{ + return _createClass(Query, [{ key: "get", value: function get(param) { return this.urlSearchParams.get(this.toHellotextParam(param)); @@ -39,6 +39,5 @@ var Query = /*#__PURE__*/function () { return new this().inPreviewMode; } }]); - return Query; }(); export { Query }; \ No newline at end of file diff --git a/lib/models/session.cjs b/lib/models/session.cjs index f462930f..bca09cb0 100644 --- a/lib/models/session.cjs +++ b/lib/models/session.cjs @@ -9,23 +9,23 @@ var _cookies = require("./cookies"); var _page2 = require("./page"); var _query2 = require("./query"); var _api = _interopRequireDefault(require("../api")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } var _session = /*#__PURE__*/_classPrivateFieldLooseKey("session"); var _query = /*#__PURE__*/_classPrivateFieldLooseKey("query"); var _page = /*#__PURE__*/_classPrivateFieldLooseKey("page"); -let Session = /*#__PURE__*/function () { +let Session = exports.Session = /*#__PURE__*/function () { function Session() { _classCallCheck(this, Session); } - _createClass(Session, null, [{ + return _createClass(Session, null, [{ key: "session", get: function () { return _classPrivateFieldLooseBase(this, _session)[_session]; @@ -62,9 +62,7 @@ let Session = /*#__PURE__*/function () { } } }]); - return Session; }(); -exports.Session = Session; Object.defineProperty(Session, _session, { writable: true, value: void 0 diff --git a/lib/models/session.js b/lib/models/session.js index f65bd71e..8946ca6e 100644 --- a/lib/models/session.js +++ b/lib/models/session.js @@ -1,11 +1,11 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; -function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; } +function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } import { Configuration } from '../core'; import { Cookies } from './cookies'; import { Page } from './page'; @@ -18,7 +18,7 @@ var Session = /*#__PURE__*/function () { function Session() { _classCallCheck(this, Session); } - _createClass(Session, null, [{ + return _createClass(Session, null, [{ key: "session", get: function get() { return _classPrivateFieldLooseBase(this, _session)[_session]; @@ -56,7 +56,6 @@ var Session = /*#__PURE__*/function () { } } }]); - return Session; }(); Object.defineProperty(Session, _session, { writable: true, diff --git a/lib/models/user.cjs b/lib/models/user.cjs index d50bbdee..10084290 100644 --- a/lib/models/user.cjs +++ b/lib/models/user.cjs @@ -5,16 +5,16 @@ Object.defineProperty(exports, "__esModule", { }); exports.User = void 0; var _cookies = require("./cookies"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let User = /*#__PURE__*/function () { +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let User = exports.User = /*#__PURE__*/function () { function User() { _classCallCheck(this, User); } - _createClass(User, null, [{ + return _createClass(User, null, [{ key: "id", get: function () { return _cookies.Cookies.get('hello_user_id'); @@ -57,6 +57,4 @@ let User = /*#__PURE__*/function () { }; } }]); - return User; -}(); -exports.User = User; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/user.js b/lib/models/user.js index d168c5b2..0746e2f4 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -1,14 +1,14 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Cookies } from './cookies'; var User = /*#__PURE__*/function () { function User() { _classCallCheck(this, User); } - _createClass(User, null, [{ + return _createClass(User, null, [{ key: "id", get: function get() { return Cookies.get('hello_user_id'); @@ -51,6 +51,5 @@ var User = /*#__PURE__*/function () { }; } }]); - return User; }(); export { User }; \ No newline at end of file diff --git a/lib/models/utm.cjs b/lib/models/utm.cjs index 1f12fa4f..44797632 100644 --- a/lib/models/utm.cjs +++ b/lib/models/utm.cjs @@ -5,12 +5,12 @@ Object.defineProperty(exports, "__esModule", { }); exports.UTM = void 0; var _cookies = require("./cookies"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let UTM = /*#__PURE__*/function () { +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let UTM = exports.UTM = /*#__PURE__*/function () { function UTM() { _classCallCheck(this, UTM); const urlSearchParams = new URLSearchParams(window.location.search); @@ -23,7 +23,7 @@ let UTM = /*#__PURE__*/function () { }; this.save(utmsFromUrl); } - _createClass(UTM, [{ + return _createClass(UTM, [{ key: "save", value: function save(utmParams) { if (!utmParams.source || !utmParams.medium) return; @@ -41,6 +41,4 @@ let UTM = /*#__PURE__*/function () { } } }]); - return UTM; -}(); -exports.UTM = UTM; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/utm.js b/lib/models/utm.js index ae286958..461f6989 100644 --- a/lib/models/utm.js +++ b/lib/models/utm.js @@ -1,8 +1,14 @@ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Cookies } from './cookies'; var UTM = /*#__PURE__*/function () { function UTM() { @@ -17,12 +23,14 @@ var UTM = /*#__PURE__*/function () { }; this.save(utmsFromUrl); } - _createClass(UTM, [{ + return _createClass(UTM, [{ key: "save", value: function save(utmParams) { if (!utmParams.source || !utmParams.medium) return; var cleanUtms = Object.fromEntries(Object.entries(utmParams).filter(_ref => { - var [_, value] = _ref; + var _ref2 = _slicedToArray(_ref, 2), + _ = _ref2[0], + value = _ref2[1]; return value; })); cleanUtms.observed_at = new Date().toISOString(); @@ -38,6 +46,5 @@ var UTM = /*#__PURE__*/function () { } } }]); - return UTM; }(); export { UTM }; \ No newline at end of file diff --git a/lib/models/webchat.cjs b/lib/models/webchat.cjs index 135cd34b..c8153736 100644 --- a/lib/models/webchat.cjs +++ b/lib/models/webchat.cjs @@ -7,20 +7,20 @@ exports.Webchat = void 0; var _core = require("../core"); var _api = _interopRequireDefault(require("../api")); var _business = require("./business"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let Webchat = /*#__PURE__*/function () { +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let Webchat = exports.Webchat = /*#__PURE__*/function () { function Webchat(data) { _classCallCheck(this, Webchat); this.data = data; this.mounted = false; this.rendered = Promise.resolve(false); } - _createClass(Webchat, [{ + return _createClass(Webchat, [{ key: "render", value: async function render() { this.applyBehaviourOverride(); @@ -87,6 +87,4 @@ let Webchat = /*#__PURE__*/function () { return webchat; } }]); - return Webchat; -}(); -exports.Webchat = Webchat; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/webchat.js b/lib/models/webchat.js index c530bc89..d9990d40 100644 --- a/lib/models/webchat.js +++ b/lib/models/webchat.js @@ -1,10 +1,10 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Configuration } from '../core'; import API from '../api'; import { Business } from './business'; @@ -15,7 +15,7 @@ var Webchat = /*#__PURE__*/function () { this.mounted = false; this.rendered = Promise.resolve(false); } - _createClass(Webchat, [{ + return _createClass(Webchat, [{ key: "render", value: function () { var _render = _asyncToGenerator(function* () { @@ -94,6 +94,5 @@ var Webchat = /*#__PURE__*/function () { return load; }() }]); - return Webchat; }(); export { Webchat }; \ No newline at end of file diff --git a/lib/models/whatsapp_widget.cjs b/lib/models/whatsapp_widget.cjs index d5e3d413..b87d4416 100644 --- a/lib/models/whatsapp_widget.cjs +++ b/lib/models/whatsapp_widget.cjs @@ -7,20 +7,20 @@ exports.WhatsAppWidget = void 0; var _core = require("../core"); var _api = _interopRequireDefault(require("../api")); var _business = require("./business"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -let WhatsAppWidget = /*#__PURE__*/function () { +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +let WhatsAppWidget = exports.WhatsAppWidget = /*#__PURE__*/function () { function WhatsAppWidget(data) { _classCallCheck(this, WhatsAppWidget); this.data = data; this.mounted = false; this.rendered = Promise.resolve(false); } - _createClass(WhatsAppWidget, [{ + return _createClass(WhatsAppWidget, [{ key: "render", value: async function render() { if (!this.data.html) return false; @@ -72,6 +72,4 @@ let WhatsAppWidget = /*#__PURE__*/function () { return widget; } }]); - return WhatsAppWidget; -}(); -exports.WhatsAppWidget = WhatsAppWidget; \ No newline at end of file +}(); \ No newline at end of file diff --git a/lib/models/whatsapp_widget.js b/lib/models/whatsapp_widget.js index 24ca0b45..757f1a06 100644 --- a/lib/models/whatsapp_widget.js +++ b/lib/models/whatsapp_widget.js @@ -1,10 +1,10 @@ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { Configuration } from '../core'; import API from '../api'; import { Business } from './business'; @@ -15,7 +15,7 @@ var WhatsAppWidget = /*#__PURE__*/function () { this.mounted = false; this.rendered = Promise.resolve(false); } - _createClass(WhatsAppWidget, [{ + return _createClass(WhatsAppWidget, [{ key: "render", value: function () { var _render = _asyncToGenerator(function* () { @@ -79,6 +79,5 @@ var WhatsAppWidget = /*#__PURE__*/function () { return load; }() }]); - return WhatsAppWidget; }(); export { WhatsAppWidget }; \ No newline at end of file diff --git a/lib/vanilla.cjs b/lib/vanilla.cjs index aeb0812a..5ad289b5 100644 --- a/lib/vanilla.cjs +++ b/lib/vanilla.cjs @@ -10,4 +10,4 @@ Object.defineProperty(exports, "default", { } }); var _hellotext = _interopRequireDefault(require("./hellotext")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } \ No newline at end of file diff --git a/src/api/popups.js b/src/api/popups.js index 7be866f4..b79bda53 100644 --- a/src/api/popups.js +++ b/src/api/popups.js @@ -13,7 +13,7 @@ class PopupsAPI { url.searchParams.append('session', Hellotext.session) url.searchParams.append('locale', Locale.toString()) - url.searchParams.append('device', Configuration.popup.device) + url.searchParams.append('device', this.runtimeDevice) const response = await this.fetchPopup(url) @@ -55,6 +55,12 @@ class PopupsAPI { } } + static get runtimeDevice() { + if (Configuration.popup.device !== 'auto') return Configuration.popup.device + + return window.innerWidth <= 767 ? 'mobile' : 'desktop' + } + static async parsePopupResponse(response) { try { return await response.json() diff --git a/styles/index.css b/styles/index.css index 07f4e518..608cd522 100644 --- a/styles/index.css +++ b/styles/index.css @@ -396,3 +396,303 @@ form[data-hello-form] [data-logo-container] [data-hello-brand] { border-radius: 24px 24px 0 0; } } + +/* Popup runtime markup. Keep these selectors in sync with + * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */ +.hellotext--popup__bubble { + position: fixed; + bottom: 24px; + z-index: 1; + appearance: none; + border: 0; + background: transparent; + cursor: pointer; + font: inherit; + max-width: min(320px, calc(100vw - 32px)); + padding: 0; + pointer-events: auto; +} + +.hellotext--popup__bubble--left { left: 24px; } +.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); } +.hellotext--popup__bubble--right { right: 24px; } + +.hellotext--popup__bubble-content { + display: block; + border-radius: 999px; + box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18); + font-weight: 700; + min-height: 44px; + padding: 12px 18px; +} + +.hellotext--popup__dialog { + position: fixed; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + padding: 24px; + background: rgba(20, 4, 52, 0.35); + pointer-events: auto; +} + +.hellotext--popup__frame { + display: flex; + width: min(768px, calc(100vw - 32px)); + max-height: calc(100vh - 32px); +} + +.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); } + +.hellotext--popup__frame--desktop-footer { + align-self: flex-end; + width: 100vw; + max-height: none; +} + +.hellotext--popup__panel { + position: relative; + display: flex; + width: 100%; + min-height: 420px; + overflow: hidden; + border: 1px solid rgba(20, 4, 52, 0.1); + border-radius: 28px; + box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18); +} + +.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; } + +.hellotext--popup__panel--desktop-column { + flex-direction: column; + min-height: 0; +} + +.hellotext--popup__panel--desktop-footer { + min-height: 132px; + border-right: 0; + border-bottom: 0; + border-left: 0; + border-radius: 24px 24px 0 0; +} + +.hellotext--popup__media { + width: 40%; + min-height: 420px; + flex: 0 0 40%; + background-position: center; + background-repeat: no-repeat; +} + +.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; } +.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; } + +.hellotext--popup__panel--desktop-column .hellotext--popup__media { + width: 100%; + min-height: 0; + flex-basis: auto; + border-radius: 28px 28px 0 0; +} + +.hellotext--popup__content { + display: flex; + width: 60%; + min-width: 0; + flex: 1 1 auto; + flex-direction: column; + justify-content: center; + margin: 0; + padding: 28px; +} + +.hellotext--popup__content--desktop-column { width: 100%; } + +.hellotext--popup__content--desktop-footer { + width: 100%; + align-items: center; + padding: 24px 56px; +} + +.hellotext--popup__step { + display: flex; + width: 100%; + flex-direction: column; +} + +.hellotext--popup__step--desktop-footer { + display: grid; + grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto; + align-items: center; + justify-content: center; + gap: 12px 28px; +} + +.hellotext--popup__step-header, +.hellotext--popup__completion-headline { + width: 100%; + margin: 0; + font-size: 18px; + line-height: 1.25; +} + +.hellotext--popup__rich-text * { color: inherit; } + +.hellotext--popup__step-header h1, +.hellotext--popup__step-header h2, +.hellotext--popup__step-header h3, +.hellotext--popup__completion-headline h1, +.hellotext--popup__completion-headline h2, +.hellotext--popup__completion-headline h3 { + margin: 0 0 8px; + font-size: clamp(32px, 7vw, 48px); + line-height: 0.95; +} + +.hellotext--popup__fields-region { width: 100%; } + +.hellotext--popup__fields { + display: flex; + width: 100%; + flex-direction: column; + gap: 10px; + margin-top: 20px; +} + +.hellotext--popup__field { width: 100%; } + +.hellotext--popup__input { + width: 100%; + min-height: 48px; + border: 1px solid rgba(20, 4, 52, 0.16); + border-radius: 12px; + background: #fff; + color: #140434; + font: inherit; + font-size: 16px; + outline: 0; + padding: 12px 16px; +} + +.hellotext--popup__input:focus { + border-color: currentColor; + box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12); +} + +.hellotext--popup__checkbox-label { + display: flex; + align-items: center; + gap: 10px; + min-height: 48px; + border: 1px solid rgba(20, 4, 52, 0.16); + border-radius: 12px; + background: #fff; + color: #140434; + padding: 12px 16px; +} + +.hellotext--popup__checkbox { width: 16px; height: 16px; } + +.hellotext--popup__error, +.hellotext--popup__global-error { + display: block; + min-height: 18px; + margin: 4px 0 0; + color: #d92d20; + font-size: 12px; +} + +.hellotext--popup__actions { + display: flex; + width: 100%; + margin-top: 20px; +} + +.hellotext--popup__actions--left { justify-content: flex-start; } +.hellotext--popup__actions--center { justify-content: center; } +.hellotext--popup__actions--right { justify-content: flex-end; } +.hellotext--popup__actions--full_width { justify-content: stretch; } + +.hellotext--popup__button, +.hellotext--popup__completion-button { + appearance: none; + min-height: 48px; + border: 0; + border-radius: 999px; + cursor: pointer; + font: inherit; + font-weight: 700; + padding: 12px 24px; + text-align: center; +} + +.hellotext--popup__button--full_width { width: 100%; } +.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; } + +.hellotext--popup__step-footer, +.hellotext--popup__completion-footer { + width: 100%; + margin-top: 16px; + font-size: 12px; + opacity: 0.72; +} + +.hellotext--popup__completed { width: 100%; text-align: center; } +.hellotext--popup__completion-description { margin-top: 12px; } +.hellotext--popup__completion-button { margin-top: 20px; } + +.hellotext--popup__close { + top: 12px; + right: 12px; + z-index: 2; + cursor: pointer; +} + +.hellotext--popup__visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +@media (max-width: 767px) { + .hellotext--popup__dialog { padding: 16px; } + .hellotext--popup__frame, + .hellotext--popup__frame--desktop-column { + width: min(350px, calc(100vw - 32px)); + max-height: calc(100vh - 32px); + } + .hellotext--popup__frame--desktop-footer { + align-self: flex-end; + width: 100vw; + max-height: none; + } + .hellotext--popup__panel, + .hellotext--popup__panel--desktop-image_to_right, + .hellotext--popup__panel--desktop-column { + min-height: 0; + flex-direction: column; + overflow-y: auto; + } + .hellotext--popup__panel--desktop-footer { + width: 100vw; + border-radius: 24px 24px 0 0; + } + .hellotext--popup__media { + display: block; + width: 100%; + min-height: 0; + flex: 0 0 auto; + border-radius: 28px 28px 0 0; + } + .hellotext--popup__content, + .hellotext--popup__content--desktop-footer { + width: 100%; + padding: 24px; + } + .hellotext--popup__step--desktop-footer { display: flex; } +} From 68815673e8f8dc22fafd5ca2086d19f4da2bd25a Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Mon, 24 Aug 2026 11:38:33 -0400 Subject: [PATCH 04/11] popups: interpolate completion values in preview and runtime --- .../controllers/popup_controller_test.js | 56 +++++++++++++++++++ dist/hellotext.js | 2 +- lib/controllers/popup_controller.cjs | 52 +++++++++++++++++ lib/controllers/popup_controller.js | 52 +++++++++++++++++ src/controllers/popup_controller.js | 52 +++++++++++++++++ 5 files changed, 213 insertions(+), 1 deletion(-) diff --git a/__tests__/controllers/popup_controller_test.js b/__tests__/controllers/popup_controller_test.js index a59af36e..a5f3e36d 100644 --- a/__tests__/controllers/popup_controller_test.js +++ b/__tests__/controllers/popup_controller_test.js @@ -38,6 +38,10 @@ describe('PopupController', () => { stepTwo.dataset.stepName = 'Step 2' stepTwo.hidden = true completed.hidden = true + completed.innerHTML = [ + '

We sent it to {destination}', + ' via {channel}. It may take a minute to arrive.

', + ].join('') stepOne.appendChild(emailInput) stepTwo.appendChild(phoneInput) @@ -176,6 +180,58 @@ describe('PopupController', () => { expect(stepOne.hidden).toBe(true) expect(stepTwo.hidden).toBe(true) expect(completed.hidden).toBe(false) + expect(completed.textContent).toBe( + 'We sent it to customer@example.com via email. It may take a minute to arrive.', + ) + expect(completed.querySelector('strong').textContent).toBe('customer@example.com') + }) + + it('uses a readable channel when the popup only requires one identity field', () => { + const { completed, emailInput, phoneInput } = buildController({ hasBubble: false }) + + phoneInput.required = false + emailInput.value = 'customer@example.com' + + controller.showCompleted() + + expect(completed.textContent).toBe( + 'We sent it to customer@example.com via email. It may take a minute to arrive.', + ) + + emailInput.value = 'updated@example.com' + controller.showCompleted() + + expect(completed.textContent).toBe( + 'We sent it to updated@example.com via email. It may take a minute to arrive.', + ) + }) + + it('falls back to the first populated optional identity field', () => { + const { completed, emailInput, phoneInput } = buildController({ hasBubble: false }) + + emailInput.required = false + phoneInput.required = false + emailInput.value = 'customer@example.com' + + controller.showCompleted() + + expect(completed.textContent).toBe( + 'We sent it to customer@example.com via email. It may take a minute to arrive.', + ) + }) + + it('formats a required phone with the popup country prefix', () => { + const { completed, emailInput, phoneInput } = buildController({ hasBubble: false }) + + emailInput.required = false + phoneInput.dataset.popupPhonePrefix = '+58' + phoneInput.value = '04126625353' + + controller.showCompleted() + + expect(completed.textContent).toBe( + 'We sent it to +584126625353 via phone. It may take a minute to arrive.', + ) }) it('validates the last step before submitting', async () => { diff --git a/dist/hellotext.js b/dist/hellotext.js index e4494ffe..b00b572b 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,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class U{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class q{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new U(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 q(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new q(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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>gs});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function q(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=q(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=q(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=q(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=U.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=U,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(Fe({session:Ei.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=qe;function We(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function $e(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){We(o,r,i,a,s,"next",e)}function s(e){We(o,r,i,a,s,"throw",e)}a(void 0)})}}function Ke(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Xe(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xe(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ei.headers}),r=yield n.json();return Ei.business.data||(Ei.business.setData(r.business),Ei.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ze(o,r,i,a,s,"next",e)}function s(e){Ze(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&Qe(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const nt=tt;function rt(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function it(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){rt(o,r,i,a,s,"next",e)}function s(e){rt(o,r,i,a,s,"throw",e)}a(void 0)})}}function ot(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ei.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){pt(o,r,i,a,s,"next",e)}function s(e){pt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&dt(e.prototype,null),t&&dt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const yt=mt;function gt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(St,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(St,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&xt(e.prototype,t),n&&xt(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function Ct(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return jt(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jt(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));At.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(At.get("hello_utm"))||{}}catch(e){return{}}}}],t&&_t(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new It,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Lt(t.prototype,n),r&&Lt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Dt;Bt(this,Ht)[Ht]=e,Bt(this,qt)[qt]=new ye,this.session=Bt(this,qt)[qt].session||Z.session||At.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Rt(e.prototype,null),t&&Rt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function $t(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ei.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const rn=Object.entries,on=Object.setPrototypeOf,an=Object.isFrozen,sn=Object.getPrototypeOf,ln=Object.getOwnPropertyDescriptor;let cn=Object.freeze,un=Object.seal,hn=Object.create,pn="undefined"!=typeof Reflect&&Reflect,dn=pn.apply,fn=pn.construct;cn||(cn=function(e){return e}),un||(un=function(e){return e}),dn||(dn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:On;if(on&&on(e,null),!wn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(an(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Fn(e){for(let t=0;t/g),er=un(/\${[\w\W]*/g),tr=un(/^data-[\-\w.\u00B7-\uFFFF]+$/),nr=un(/^aria-[\-\w]+$/),rr=un(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ir=un(/^(?:\w+script|data):/i),or=un(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ar=un(/^html$/i),sr=un(/^[a-z][.\w]*(-[.\w]+)+$/i),lr=un(/<[/\w!]/g),cr=un(/<[/\w]/g),ur=un(/<\/no(script|embed|frames)/i),hr=un(/\/>/i),pr=function(){return"undefined"==typeof window?null:window},dr=function(e,t,n,r){return _n(e,t)&&wn(e[t])?Rn(r.base?Bn(r.base):{},e[t],r.transform):n};var fr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:pr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=Vn(p,"cloneNode"),f=Vn(p,"remove"),m=Vn(p,"nextSibling"),y=Vn(p,"childNodes"),g=Vn(p,"parentNode"),v=Vn(p,"shadowRoot"),b=Vn(p,"attributes"),w=s&&s.prototype?Vn(s.prototype,"nodeType"):null,O=s&&s.prototype?Vn(s.prototype,"nodeName"):null,T=s&&s.prototype?Vn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Ln('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof rn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=Zn,F=Qn,B=er,V=tr,z=nr,U=ir,q=or,H=sr;let W=rr,$=null;const K=Rn({},[...zn,...Un,...qn,...Wn,...Kn]);let G=null;const J=Rn({},[...Gn,...Jn,...Yn,...Xn]);let Y=Object.seal(hn(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}})),X=null,Z=null;const Q=Object.seal(hn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Rn({},["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 Te=null;const xe=Rn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Rn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Rn({},[Ee,Ce,Pe],Tn),Ie=cn(["mi","mo","mn","ms","mtext"]);let Le=Rn({},Ie);const Ne=cn(["annotation-xml"]);let De=Rn({},Ne);const Re=Rn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const Ue=r.createElement("form"),qe=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Bn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Tn:On,$=dr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=dr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=dr(e,"ALLOWED_NAMESPACES",Me,{transform:Tn}),ke=dr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=dr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=dr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=dr(e,"FORBID_TAGS",Bn({}),{transform:Ve}),Z=dr(e,"FORBID_ATTR",Bn({}),{transform:Ve}),be=!!_n(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Bn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return In(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:rr,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=_n(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Bn(e.MATHML_TEXT_INTEGRATION_POINTS):Rn({},Ie),De=_n(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Bn(e.HTML_INTEGRATION_POINTS):Rn({},Ne);const t=_n(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Bn(e.CUSTOM_ELEMENT_HANDLING):hn(null);if(Y=hn(null),_n(t,"tagNameCheck")&&qe(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),_n(t,"attributeNameCheck")&&qe(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),_n(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),un(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Rn({},Kn),G=hn(null),!0===be.html&&(Rn($,zn),Rn(G,Gn)),!0===be.svg&&(Rn($,Un),Rn(G,Jn),Rn(G,Xn)),!0===be.svgFilters&&(Rn($,qn),Rn(G,Jn),Rn(G,Xn)),!0===be.mathMl&&(Rn($,Wn),Rn(G,Yn),Rn(G,Xn))),Q.tagCheck=null,Q.attributeCheck=null,_n(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:wn(e.ADD_TAGS)&&($===K&&($=Bn($)),Rn($,e.ADD_TAGS,Ve))),_n(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:wn(e.ADD_ATTR)&&(G===J&&(G=Bn(G)),Rn(G,e.ADD_ATTR,Ve))),_n(e,"ADD_URI_SAFE_ATTR")&&wn(e.ADD_URI_SAFE_ATTR)&&Rn(ke,e.ADD_URI_SAFE_ATTR,Ve),_n(e,"FORBID_CONTENTS")&&wn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.FORBID_CONTENTS,Ve)),_n(e,"ADD_FORBID_CONTENTS")&&wn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Rn($,["html","head","body"]),$.table&&(Rn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));cn&&cn(e),ze=e},We=Rn({},[...Un,...qn,...Hn]),$e=Rn({},[...Wn,...$n]),Ke=function(e){vn(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Ln("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];mn(t,t=>{vn(e,t)}),mn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{vn(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){vn(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=xn(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=kn(e,R," "),e=kn(e,F," "),kn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&mn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&mn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Bn(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&In(lr,e.textContent)&&In(lr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!In(cr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=On(e.tagName),r=On(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&In(ur,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(vn(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in Ue))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&In(V,t));else if(ee&&In(z,t));else if(i){if(ke[t]);else if(In(W,kn(n,q,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Sn(n,"data:")||!Te[e])if(ne&&!In(U,kn(n,q,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&In(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Rn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[On(e)]&&In(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):gn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:En(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Sn(h,ye)||(Je(a,e),h=ye+h),oe&&In(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&xn(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&In(hr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return Cn(e);case"boolean":return Pn(e);case"bigint":return An?An(e):"0";case"symbol":return jn?jn(e):"Symbol()";case"undefined":default:return Mn(e);case"function":case"object":{if(null===e)return Mn(e);const t=e,n=Vn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Mn(e)}return Mn(e)}}}(e)))throw Ln("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Bn($)),D.uponSanitizeAttribute.length>0&&(G=Bn(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&In(cr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Ln("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Ln("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),mn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return mn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&In(ar,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&_n(D,e)&&vn(D[e],t)},n.removeHook=function(e,t){if(_n(D,e)){if(void 0!==t){const n=yn(D[e],t);return-1===n?void 0:bn(D[e],n,1)[0]}return gn(D[e])}},n.removeHooks=function(e){_n(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),mr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},yr={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function gr(e,t){var n=fr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function vr(e,t){e.replaceChildren(function(e){return gr(e,mr)}(t))}function br(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wr(e,t,n){return(t=xr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Or(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Tr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,Cr,{value:Ar}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ei.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ei.business.features.white_label||this.element.prepend(en.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Or(o,r,i,a,s,"next",e)}function s(e){Or(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-header]","header");vr(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-inputs]","main");e.map(e=>Gt.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)}},{key:"buildButton",value:function(e){var t=kr(this,Cr)[Cr]("[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)}},{key:"buildFooter",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-footer]","footer");vr(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ei.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Tr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Ar(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function jr(e){var t="function"==typeof Map?new Map:void 0;return jr=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(_r())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Mr(i,n.prototype),i}(e,arguments,Ir(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Mr(n,e)},jr(e)}function _r(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_r=function(){return!!e})()}function Mr(e,t){return Mr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Mr(e,t)}function Ir(e){return Ir=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ir(e)}var Lr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Ir(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,_r()?Reflect.construct(t,n||[],Ir(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Mr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(jr(Error));function Nr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Dr(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ei.notInitialized)throw new Lr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,Vr)[Vr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ei.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Nr(o,r,i,a,s,"next",e)}function s(e){Nr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ei.business.data||(Ei.business.setData(e.business),Ei.business.setLocale(j.toString())),Ei.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 Pr(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Dr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Ur(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function qr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Hr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){qr(o,r,i,a,s,"next",e)}function s(e){qr(o,r,i,a,s,"throw",e)}a(void 0)})}}function Wr(e,t){for(var n=0;ndi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=di(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function fi(e,t){var n=di(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function mi(){return(mi=ci(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var yi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=ci(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return mi.apply(this,arguments)}(fi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&si(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function gi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new Et(e),this.page=new Dt,Z.assign(t),Wt.initialize(this.page),this.forms=new zr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Kr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield Zr.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ri.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=bi({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return gi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Ti(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Lr;var n=bi(bi({},t&&t.headers||{}),this.headers),r=bi(bi({},ai.identificationData),t.user_parameters||{}),i=t&&t.url?new Dt(t.url):this.page,o=bi(bi({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield wt.events.create({headers:n,body:o,keepalive:bt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Ti(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield yi.generate(this.session,e,n);if(yi.matches(ai.fingerprint,r))return new ke(!0,{json:(t=Ti(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield wt.identifications.create(bi({user_id:e},n));return i.succeeded&&ai.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ai.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Wt.session}},{key:"isInitialized",get:function(){return void 0!==Wt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Lr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&xi(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Si.eventEmitter=new ce,Si.forms=void 0,Si.business=void 0,Si.popup=void 0,Si.webchat=void 0,Si.whatsapp=void 0;const Ei=Si;function Ci(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Pi(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ei.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){Ci(o,n,r,a,s,"next",e)}function s(e){Ci(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ei.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&Pi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Di(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ri(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Bi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function $i(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Ki(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$i(o,r,i,a,s,"next",e)}function s(e){$i(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gi(e,t){for(var n=0;n{e.disabled=!0});var t=yield wt.popups.submit(this.idValue,this.submissionPayload());this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed?yield this.handleSubmissionError(t):this.showCompleted()}else this.showErrorMessages(this.currentStepInputs)}),function(e){return o.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.showElement(this.completedTarget)}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Ki(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Gi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a}(g.xI);eo.targets=["bubble","dialog","step","completed","input","submitButton"],eo.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const to=["start","end"],no=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+to[0],t+"-"+to[1]),[]),ro=Math.min,io=Math.max,oo=Math.round,ao=Math.floor,so=e=>({x:e,y:e}),lo={left:"right",right:"left",bottom:"top",top:"bottom"};function co(e,t){return"function"==typeof e?e(t):e}function uo(e){return e.split("-")[0]}function ho(e){return e.split("-")[1]}function po(e){return"x"===e?"y":"x"}function fo(e){return"y"===e?"height":"width"}function mo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function yo(e){return po(mo(e))}function go(e,t,n){void 0===n&&(n=!1);const r=ho(e),i=yo(e),o=fo(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=xo(a)),[a,xo(a)]}function vo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const bo=["left","right"],wo=["right","left"],Oo=["top","bottom"],To=["bottom","top"];function xo(e){const t=uo(e);return lo[t]+e.slice(t.length)}function ko(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function So(e,t,n){let{reference:r,floating:i}=e;const o=mo(t),a=yo(t),s=fo(a),l=uo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=ho(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Eo(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=co(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=ko(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=ko(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const Co=new Set(["left","top"]);function Po(){return"undefined"!=typeof window}function Ao(e){return Mo(e)?(e.nodeName||"").toLowerCase():"#document"}function jo(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function _o(e){var t;return null==(t=(Mo(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Mo(e){return!!Po()&&(e instanceof Node||e instanceof jo(e).Node)}function Io(e){return!!Po()&&(e instanceof Element||e instanceof jo(e).Element)}function Lo(e){return!!Po()&&(e instanceof HTMLElement||e instanceof jo(e).HTMLElement)}function No(e){return!(!Po()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof jo(e).ShadowRoot)}function Do(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=$o(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Ro(e){return/^(table|td|th)$/.test(Ao(e))}function Fo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Bo=/transform|translate|scale|rotate|perspective|filter/,Vo=/paint|layout|strict|content/,zo=e=>!!e&&"none"!==e;let Uo;function qo(e){const t=Io(e)?$o(e):e;return zo(t.transform)||zo(t.translate)||zo(t.scale)||zo(t.rotate)||zo(t.perspective)||!Ho()&&(zo(t.backdropFilter)||zo(t.filter))||Bo.test(t.willChange||"")||Vo.test(t.contain||"")}function Ho(){return null==Uo&&(Uo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Uo}function Wo(e){return/^(html|body|#document)$/.test(Ao(e))}function $o(e){return jo(e).getComputedStyle(e)}function Ko(e){return Io(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Go(e){if("html"===Ao(e))return e;const t=e.assignedSlot||e.parentNode||No(e)&&e.host||_o(e);return No(t)?t.host:t}function Jo(e){const t=Go(e);return Wo(t)?(e.ownerDocument||e).body:Lo(t)&&Do(t)?t:Jo(t)}function Yo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Jo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=jo(i);if(o){const e=Xo(a);return t.concat(a,a.visualViewport||[],Do(i)?i:[],e&&n?Yo(e):[])}return t.concat(i,Yo(i,[],n))}function Xo(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Zo(e){const t=$o(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Lo(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=oo(n)!==o||oo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function Qo(e){return Io(e)?e:e.contextElement}function ea(e){const t=Qo(e);if(!Lo(t))return so(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Zo(t);let a=(o?oo(n.width):n.width)/r,s=(o?oo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ta=so(0);function na(e){const t=jo(e);return Ho()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ta}function ra(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=Qo(e);let a=so(1);t&&(r?Io(r)&&(a=ea(r)):a=ea(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===jo(e)}(o,n,r)?na(o):so(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=jo(o),t=Io(r)?jo(r):r;let n=e,i=Xo(n);for(;i&&t!==n;){const e=ea(i),t=i.getBoundingClientRect(),r=$o(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=jo(i),i=Xo(n)}}return ko({width:u,height:h,x:l,y:c})}function ia(e,t){const n=Ko(e).scrollLeft;return t?t.left+n:ra(_o(e)).left+n}function oa(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ia(e,n),y:n.top+t.scrollTop}}function aa(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=jo(e),o=_o(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ho()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(ia(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Ko(e),n=e.ownerDocument.body,r=io(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=io(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+ia(e);const a=-t.scrollTop;return"rtl"===$o(n).direction&&(o+=io(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(_o(e));else if(Io(t))r=function(e,t){const n=ra(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ea(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=na(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ko(r)}function sa(e,t,n){const r=Lo(t),i=_o(t),o="fixed"===n,a=ra(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=so(0);if((r||!o)&&(("body"!==Ao(t)||Do(i))&&(s=Ko(t)),r)){const e=ra(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=ia(i));const c=!i||r||o?so(0):oa(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function la(e){return"static"===$o(e).position}function ca(e,t){if(!Lo(e)||"fixed"===$o(e).position)return null;if(t)return t(e);let n=e.offsetParent;return _o(e)===n&&(n=n.ownerDocument.body),n}function ua(e,t){const n=jo(e);if(Fo(e))return n;if(!Lo(e)){let t=Go(e);for(;t&&!Wo(t);){if(Io(t)&&!la(t))return t;t=Go(t)}return n}let r=ca(e,t);for(;r&&Ro(r)&&la(r);)r=ca(r,t);return r&&Wo(r)&&la(r)&&!qo(r)?n:r||function(e){let t=Go(e);for(;Lo(t)&&!Wo(t);){if(qo(t))return t;if(Fo(t))return null;t=Go(t)}return null}(e)||n}const ha={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=_o(r),s=!!t&&Fo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=so(1);const u=so(0),h=Lo(r);if((h||!o)&&(("body"!==Ao(r)||Do(a))&&(l=Ko(r)),h)){const e=ra(r);c=ea(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?so(0):oa(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:_o,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?Fo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Yo(e,[],!1).filter(e=>Io(e)&&"body"!==Ao(e)),i=null;const o="fixed"===$o(e).position;let a=o?Go(e):e;for(;Io(a)&&!Wo(a);){const e=$o(a),t=qo(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Go(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=aa(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;eho(t)===e),...n.filter(t=>ho(t)!==e)]:n.filter(e=>uo(e)===e)).filter(n=>!e||ho(n)===e||!!t&&vo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=go(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[uo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=ho(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,ho(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},ma=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=co(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=mo(i),d=po(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],io(n,ro(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ya=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=co(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=uo(i),v=mo(s),b=uo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[xo(s)]:function(e){const t=xo(e);return[vo(e),t,vo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=ho(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?wo:bo:t?bo:wo;case"left":case"right":return t?Oo:To;default:return[]}}(uo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(vo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=go(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===mo(t)||E.every(e=>mo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=mo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var ga=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=Qo(e),u=i||o?[...c?Yo(c):[],...t?Yo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=_o(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-ao(h)+"px "+-ao(o.clientWidth-(u+p))+"px "+-ao(o.clientHeight-(h+d))+"px "+-ao(u)+"px",threshold:io(0,ro(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!pa(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=jo(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?ra(e):null;return l&&function t(){const r=ra(e);m&&!pa(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...ha,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Eo},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=So(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function va(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ja(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ja(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ei.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ei.session})}},{key:"create",value:(i=Ma(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ei.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ei.headers,body:JSON.stringify({session:Ei.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Ia(t.prototype,n),r&&Ia(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Da=Na;function Ra(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Ra(t.prototype,n),r&&Ra(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Va(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ka(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ha(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ha(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ha(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&Va(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ba);const Ja=Ga;var Ya=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},Xa=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},Za=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function Qa(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function es(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=rs(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ei.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),vr(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){U.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ei.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ei.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",vr(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=rs(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return gr(e,yr)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=rs(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ei.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ei.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=rs(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ei.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=rs(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ei.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=rs(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=rs(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[da(this.offsetValue),ma({padding:this.paddingValue}),ya()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ds.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ps)}catch(e){return new Intl.DateTimeFormat(void 0,ps)}}}],r&&is(n.prototype,r),i&&is(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);ms.messageTimestampFormatters={},ms.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},ms.classes=["fadeOut"],ms.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"];var ys=g.lg.start();ys.register("hellotext--form",Ni),ys.register("hellotext--popup",eo),ys.register("hellotext--webchat",ms),ys.register("hellotext--webchat--emoji",Aa),ys.register("hellotext--message",Wi),window.Hellotext=Ei;const gs=Ei},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c(()=>{"use strict";var e={891(e,t,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} 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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class U{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),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 H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>gs});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function U(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=U(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=U(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=U(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=q.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=q,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(Fe({session:Ei.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=Ue;function We(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function $e(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){We(o,r,i,a,s,"next",e)}function s(e){We(o,r,i,a,s,"throw",e)}a(void 0)})}}function Ke(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Xe(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xe(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ei.headers}),r=yield n.json();return Ei.business.data||(Ei.business.setData(r.business),Ei.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ze(o,r,i,a,s,"next",e)}function s(e){Ze(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&Qe(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const nt=tt;function rt(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function it(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){rt(o,r,i,a,s,"next",e)}function s(e){rt(o,r,i,a,s,"throw",e)}a(void 0)})}}function ot(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ei.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){pt(o,r,i,a,s,"next",e)}function s(e){pt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&dt(e.prototype,null),t&&dt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const yt=mt;function gt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(St,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(St,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&xt(e.prototype,t),n&&xt(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function Ct(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return jt(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jt(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),At.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(At.get("hello_utm"))||{}}catch(e){return{}}}}],t&&_t(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new It,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Lt(t.prototype,n),r&&Lt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Dt;Bt(this,Ht)[Ht]=e,Bt(this,Ut)[Ut]=new ye,this.session=Bt(this,Ut)[Ut].session||Z.session||At.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Rt(e.prototype,null),t&&Rt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function $t(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ei.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const rn=Object.entries,on=Object.setPrototypeOf,an=Object.isFrozen,sn=Object.getPrototypeOf,ln=Object.getOwnPropertyDescriptor;let cn=Object.freeze,un=Object.seal,hn=Object.create,pn="undefined"!=typeof Reflect&&Reflect,dn=pn.apply,fn=pn.construct;cn||(cn=function(e){return e}),un||(un=function(e){return e}),dn||(dn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:On;if(on&&on(e,null),!wn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(an(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Fn(e){for(let t=0;t/g),er=un(/\${[\w\W]*/g),tr=un(/^data-[\-\w.\u00B7-\uFFFF]+$/),nr=un(/^aria-[\-\w]+$/),rr=un(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ir=un(/^(?:\w+script|data):/i),or=un(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ar=un(/^html$/i),sr=un(/^[a-z][.\w]*(-[.\w]+)+$/i),lr=un(/<[/\w!]/g),cr=un(/<[/\w]/g),ur=un(/<\/no(script|embed|frames)/i),hr=un(/\/>/i),pr=function(){return"undefined"==typeof window?null:window},dr=function(e,t,n,r){return _n(e,t)&&wn(e[t])?Rn(r.base?Bn(r.base):{},e[t],r.transform):n};var fr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:pr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=Vn(p,"cloneNode"),f=Vn(p,"remove"),m=Vn(p,"nextSibling"),y=Vn(p,"childNodes"),g=Vn(p,"parentNode"),v=Vn(p,"shadowRoot"),b=Vn(p,"attributes"),w=s&&s.prototype?Vn(s.prototype,"nodeType"):null,O=s&&s.prototype?Vn(s.prototype,"nodeName"):null,T=s&&s.prototype?Vn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Ln('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof rn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=Zn,F=Qn,B=er,V=tr,z=nr,q=ir,U=or,H=sr;let W=rr,$=null;const K=Rn({},[...zn,...qn,...Un,...Wn,...Kn]);let G=null;const J=Rn({},[...Gn,...Jn,...Yn,...Xn]);let Y=Object.seal(hn(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}})),X=null,Z=null;const Q=Object.seal(hn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Rn({},["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 Te=null;const xe=Rn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Rn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Rn({},[Ee,Ce,Pe],Tn),Ie=cn(["mi","mo","mn","ms","mtext"]);let Le=Rn({},Ie);const Ne=cn(["annotation-xml"]);let De=Rn({},Ne);const Re=Rn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const qe=r.createElement("form"),Ue=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Bn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Tn:On,$=dr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=dr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=dr(e,"ALLOWED_NAMESPACES",Me,{transform:Tn}),ke=dr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=dr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=dr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=dr(e,"FORBID_TAGS",Bn({}),{transform:Ve}),Z=dr(e,"FORBID_ATTR",Bn({}),{transform:Ve}),be=!!_n(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Bn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return In(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:rr,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=_n(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Bn(e.MATHML_TEXT_INTEGRATION_POINTS):Rn({},Ie),De=_n(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Bn(e.HTML_INTEGRATION_POINTS):Rn({},Ne);const t=_n(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Bn(e.CUSTOM_ELEMENT_HANDLING):hn(null);if(Y=hn(null),_n(t,"tagNameCheck")&&Ue(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),_n(t,"attributeNameCheck")&&Ue(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),_n(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),un(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Rn({},Kn),G=hn(null),!0===be.html&&(Rn($,zn),Rn(G,Gn)),!0===be.svg&&(Rn($,qn),Rn(G,Jn),Rn(G,Xn)),!0===be.svgFilters&&(Rn($,Un),Rn(G,Jn),Rn(G,Xn)),!0===be.mathMl&&(Rn($,Wn),Rn(G,Yn),Rn(G,Xn))),Q.tagCheck=null,Q.attributeCheck=null,_n(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:wn(e.ADD_TAGS)&&($===K&&($=Bn($)),Rn($,e.ADD_TAGS,Ve))),_n(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:wn(e.ADD_ATTR)&&(G===J&&(G=Bn(G)),Rn(G,e.ADD_ATTR,Ve))),_n(e,"ADD_URI_SAFE_ATTR")&&wn(e.ADD_URI_SAFE_ATTR)&&Rn(ke,e.ADD_URI_SAFE_ATTR,Ve),_n(e,"FORBID_CONTENTS")&&wn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.FORBID_CONTENTS,Ve)),_n(e,"ADD_FORBID_CONTENTS")&&wn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Rn($,["html","head","body"]),$.table&&(Rn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));cn&&cn(e),ze=e},We=Rn({},[...qn,...Un,...Hn]),$e=Rn({},[...Wn,...$n]),Ke=function(e){vn(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Ln("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];mn(t,t=>{vn(e,t)}),mn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{vn(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){vn(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=xn(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=kn(e,R," "),e=kn(e,F," "),kn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&mn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&mn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Bn(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&In(lr,e.textContent)&&In(lr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!In(cr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=On(e.tagName),r=On(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&In(ur,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(vn(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in qe))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&In(V,t));else if(ee&&In(z,t));else if(i){if(ke[t]);else if(In(W,kn(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Sn(n,"data:")||!Te[e])if(ne&&!In(q,kn(n,U,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&In(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Rn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[On(e)]&&In(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):gn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:En(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Sn(h,ye)||(Je(a,e),h=ye+h),oe&&In(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&xn(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&In(hr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return Cn(e);case"boolean":return Pn(e);case"bigint":return An?An(e):"0";case"symbol":return jn?jn(e):"Symbol()";case"undefined":default:return Mn(e);case"function":case"object":{if(null===e)return Mn(e);const t=e,n=Vn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Mn(e)}return Mn(e)}}}(e)))throw Ln("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Bn($)),D.uponSanitizeAttribute.length>0&&(G=Bn(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&In(cr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Ln("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Ln("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),mn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return mn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&In(ar,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&_n(D,e)&&vn(D[e],t)},n.removeHook=function(e,t){if(_n(D,e)){if(void 0!==t){const n=yn(D[e],t);return-1===n?void 0:bn(D[e],n,1)[0]}return gn(D[e])}},n.removeHooks=function(e){_n(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),mr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},yr={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function gr(e,t){var n=fr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function vr(e,t){e.replaceChildren(function(e){return gr(e,mr)}(t))}function br(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wr(e,t,n){return(t=xr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Or(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Tr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,Cr,{value:Ar}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ei.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ei.business.features.white_label||this.element.prepend(en.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Or(o,r,i,a,s,"next",e)}function s(e){Or(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-header]","header");vr(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-inputs]","main");e.map(e=>Gt.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)}},{key:"buildButton",value:function(e){var t=kr(this,Cr)[Cr]("[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)}},{key:"buildFooter",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-footer]","footer");vr(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ei.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Tr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Ar(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function jr(e){var t="function"==typeof Map?new Map:void 0;return jr=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(_r())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Mr(i,n.prototype),i}(e,arguments,Ir(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Mr(n,e)},jr(e)}function _r(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_r=function(){return!!e})()}function Mr(e,t){return Mr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Mr(e,t)}function Ir(e){return Ir=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ir(e)}var Lr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Ir(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,_r()?Reflect.construct(t,n||[],Ir(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Mr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(jr(Error));function Nr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Dr(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ei.notInitialized)throw new Lr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,Vr)[Vr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ei.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Nr(o,r,i,a,s,"next",e)}function s(e){Nr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ei.business.data||(Ei.business.setData(e.business),Ei.business.setLocale(j.toString())),Ei.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 Pr(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Dr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function qr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function Ur(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Hr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ur(o,r,i,a,s,"next",e)}function s(e){Ur(o,r,i,a,s,"throw",e)}a(void 0)})}}function Wr(e,t){for(var n=0;ndi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=di(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function fi(e,t){var n=di(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function mi(){return(mi=ci(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var yi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=ci(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return mi.apply(this,arguments)}(fi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&si(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function gi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new Et(e),this.page=new Dt,Z.assign(t),Wt.initialize(this.page),this.forms=new zr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Kr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield Zr.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ri.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=bi({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return gi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Ti(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Lr;var n=bi(bi({},t&&t.headers||{}),this.headers),r=bi(bi({},ai.identificationData),t.user_parameters||{}),i=t&&t.url?new Dt(t.url):this.page,o=bi(bi({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield wt.events.create({headers:n,body:o,keepalive:bt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Ti(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield yi.generate(this.session,e,n);if(yi.matches(ai.fingerprint,r))return new ke(!0,{json:(t=Ti(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield wt.identifications.create(bi({user_id:e},n));return i.succeeded&&ai.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ai.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Wt.session}},{key:"isInitialized",get:function(){return void 0!==Wt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Lr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&xi(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Si.eventEmitter=new ce,Si.forms=void 0,Si.business=void 0,Si.popup=void 0,Si.webchat=void 0,Si.whatsapp=void 0;const Ei=Si;function Ci(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Pi(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ei.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){Ci(o,n,r,a,s,"next",e)}function s(e){Ci(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ei.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&Pi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Di(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ri(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Bi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function $i(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Ki(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$i(o,r,i,a,s,"next",e)}function s(e){$i(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gi(e,t){for(var n=0;n{e.disabled=!0});var t=yield wt.popups.submit(this.idValue,this.submissionPayload());this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed?yield this.handleSubmissionError(t):this.showCompleted()}else this.showErrorMessages(this.currentStepInputs)}),function(e){return o.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.identityInputs.map(e=>({kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value);if(e){var t={destination:e.value,channel:e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Ki(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Gi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a}(g.xI);eo.targets=["bubble","dialog","step","completed","input","submitButton"],eo.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const to=["start","end"],no=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+to[0],t+"-"+to[1]),[]),ro=Math.min,io=Math.max,oo=Math.round,ao=Math.floor,so=e=>({x:e,y:e}),lo={left:"right",right:"left",bottom:"top",top:"bottom"};function co(e,t){return"function"==typeof e?e(t):e}function uo(e){return e.split("-")[0]}function ho(e){return e.split("-")[1]}function po(e){return"x"===e?"y":"x"}function fo(e){return"y"===e?"height":"width"}function mo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function yo(e){return po(mo(e))}function go(e,t,n){void 0===n&&(n=!1);const r=ho(e),i=yo(e),o=fo(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=xo(a)),[a,xo(a)]}function vo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const bo=["left","right"],wo=["right","left"],Oo=["top","bottom"],To=["bottom","top"];function xo(e){const t=uo(e);return lo[t]+e.slice(t.length)}function ko(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function So(e,t,n){let{reference:r,floating:i}=e;const o=mo(t),a=yo(t),s=fo(a),l=uo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=ho(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Eo(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=co(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=ko(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=ko(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const Co=new Set(["left","top"]);function Po(){return"undefined"!=typeof window}function Ao(e){return Mo(e)?(e.nodeName||"").toLowerCase():"#document"}function jo(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function _o(e){var t;return null==(t=(Mo(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Mo(e){return!!Po()&&(e instanceof Node||e instanceof jo(e).Node)}function Io(e){return!!Po()&&(e instanceof Element||e instanceof jo(e).Element)}function Lo(e){return!!Po()&&(e instanceof HTMLElement||e instanceof jo(e).HTMLElement)}function No(e){return!(!Po()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof jo(e).ShadowRoot)}function Do(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=$o(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Ro(e){return/^(table|td|th)$/.test(Ao(e))}function Fo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Bo=/transform|translate|scale|rotate|perspective|filter/,Vo=/paint|layout|strict|content/,zo=e=>!!e&&"none"!==e;let qo;function Uo(e){const t=Io(e)?$o(e):e;return zo(t.transform)||zo(t.translate)||zo(t.scale)||zo(t.rotate)||zo(t.perspective)||!Ho()&&(zo(t.backdropFilter)||zo(t.filter))||Bo.test(t.willChange||"")||Vo.test(t.contain||"")}function Ho(){return null==qo&&(qo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),qo}function Wo(e){return/^(html|body|#document)$/.test(Ao(e))}function $o(e){return jo(e).getComputedStyle(e)}function Ko(e){return Io(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Go(e){if("html"===Ao(e))return e;const t=e.assignedSlot||e.parentNode||No(e)&&e.host||_o(e);return No(t)?t.host:t}function Jo(e){const t=Go(e);return Wo(t)?(e.ownerDocument||e).body:Lo(t)&&Do(t)?t:Jo(t)}function Yo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Jo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=jo(i);if(o){const e=Xo(a);return t.concat(a,a.visualViewport||[],Do(i)?i:[],e&&n?Yo(e):[])}return t.concat(i,Yo(i,[],n))}function Xo(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Zo(e){const t=$o(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Lo(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=oo(n)!==o||oo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function Qo(e){return Io(e)?e:e.contextElement}function ea(e){const t=Qo(e);if(!Lo(t))return so(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Zo(t);let a=(o?oo(n.width):n.width)/r,s=(o?oo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ta=so(0);function na(e){const t=jo(e);return Ho()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ta}function ra(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=Qo(e);let a=so(1);t&&(r?Io(r)&&(a=ea(r)):a=ea(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===jo(e)}(o,n,r)?na(o):so(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=jo(o),t=Io(r)?jo(r):r;let n=e,i=Xo(n);for(;i&&t!==n;){const e=ea(i),t=i.getBoundingClientRect(),r=$o(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=jo(i),i=Xo(n)}}return ko({width:u,height:h,x:l,y:c})}function ia(e,t){const n=Ko(e).scrollLeft;return t?t.left+n:ra(_o(e)).left+n}function oa(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ia(e,n),y:n.top+t.scrollTop}}function aa(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=jo(e),o=_o(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ho()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(ia(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Ko(e),n=e.ownerDocument.body,r=io(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=io(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+ia(e);const a=-t.scrollTop;return"rtl"===$o(n).direction&&(o+=io(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(_o(e));else if(Io(t))r=function(e,t){const n=ra(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ea(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=na(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ko(r)}function sa(e,t,n){const r=Lo(t),i=_o(t),o="fixed"===n,a=ra(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=so(0);if((r||!o)&&(("body"!==Ao(t)||Do(i))&&(s=Ko(t)),r)){const e=ra(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=ia(i));const c=!i||r||o?so(0):oa(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function la(e){return"static"===$o(e).position}function ca(e,t){if(!Lo(e)||"fixed"===$o(e).position)return null;if(t)return t(e);let n=e.offsetParent;return _o(e)===n&&(n=n.ownerDocument.body),n}function ua(e,t){const n=jo(e);if(Fo(e))return n;if(!Lo(e)){let t=Go(e);for(;t&&!Wo(t);){if(Io(t)&&!la(t))return t;t=Go(t)}return n}let r=ca(e,t);for(;r&&Ro(r)&&la(r);)r=ca(r,t);return r&&Wo(r)&&la(r)&&!Uo(r)?n:r||function(e){let t=Go(e);for(;Lo(t)&&!Wo(t);){if(Uo(t))return t;if(Fo(t))return null;t=Go(t)}return null}(e)||n}const ha={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=_o(r),s=!!t&&Fo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=so(1);const u=so(0),h=Lo(r);if((h||!o)&&(("body"!==Ao(r)||Do(a))&&(l=Ko(r)),h)){const e=ra(r);c=ea(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?so(0):oa(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:_o,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?Fo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Yo(e,[],!1).filter(e=>Io(e)&&"body"!==Ao(e)),i=null;const o="fixed"===$o(e).position;let a=o?Go(e):e;for(;Io(a)&&!Wo(a);){const e=$o(a),t=Uo(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Go(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=aa(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;eho(t)===e),...n.filter(t=>ho(t)!==e)]:n.filter(e=>uo(e)===e)).filter(n=>!e||ho(n)===e||!!t&&vo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=go(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[uo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=ho(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,ho(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},ma=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=co(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=mo(i),d=po(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],io(n,ro(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ya=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=co(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=uo(i),v=mo(s),b=uo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[xo(s)]:function(e){const t=xo(e);return[vo(e),t,vo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=ho(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?wo:bo:t?bo:wo;case"left":case"right":return t?Oo:To;default:return[]}}(uo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(vo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=go(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===mo(t)||E.every(e=>mo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=mo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var ga=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=Qo(e),u=i||o?[...c?Yo(c):[],...t?Yo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=_o(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-ao(h)+"px "+-ao(o.clientWidth-(u+p))+"px "+-ao(o.clientHeight-(h+d))+"px "+-ao(u)+"px",threshold:io(0,ro(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!pa(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=jo(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?ra(e):null;return l&&function t(){const r=ra(e);m&&!pa(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...ha,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Eo},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=So(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function va(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ja(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ja(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ei.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ei.session})}},{key:"create",value:(i=Ma(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ei.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ei.headers,body:JSON.stringify({session:Ei.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Ia(t.prototype,n),r&&Ia(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Da=Na;function Ra(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Ra(t.prototype,n),r&&Ra(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Va(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ka(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ha(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ha(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ha(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&Va(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ba);const Ja=Ga;var Ya=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},Xa=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},Za=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function Qa(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function es(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=rs(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ei.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),vr(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){q.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ei.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ei.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",vr(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=rs(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return gr(e,yr)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=rs(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ei.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ei.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=rs(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ei.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=rs(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ei.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=rs(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=rs(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[da(this.offsetValue),ma({padding:this.paddingValue}),ya()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ds.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ps)}catch(e){return new Intl.DateTimeFormat(void 0,ps)}}}],r&&is(n.prototype,r),i&&is(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);ms.messageTimestampFormatters={},ms.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},ms.classes=["fadeOut"],ms.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"];var ys=g.lg.start();ys.register("hellotext--form",Ni),ys.register("hellotext--popup",eo),ys.register("hellotext--webchat",ms),ys.register("hellotext--webchat--emoji",Aa),ys.register("hellotext--message",Wi),window.Hellotext=Ei;const gs=Ei},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c this.hideElement(step)); + this.interpolateCompletionCopy(); this.showElement(this.completedTarget); } + }, { + key: "interpolateCompletionCopy", + value: function interpolateCompletionCopy() { + const identity = this.identityInputs.map(input => ({ + kind: input.dataset.popupFieldKind, + value: this.identityValue(input) + })).find(({ + value + }) => value); + if (!identity) return; + const replacements = { + destination: identity.value, + channel: identity.kind + }; + this.completionTextTemplates.forEach(({ + node, + template + }) => { + node.nodeValue = template.replace(/\{(destination|channel)\}/g, (placeholder, key) => replacements[key] || placeholder); + }); + } + }, { + key: "identityValue", + value: function identityValue(input) { + const value = this.inputValue(input).trim(); + if (input.dataset.popupFieldKind !== 'phone' || value.startsWith('+')) return value; + const prefix = input.dataset.popupPhonePrefix; + return prefix ? `${prefix}${value.replace(/^0+/, '')}` : value; + } }, { key: "currentStepValid", value: function currentStepValid() { @@ -261,6 +291,28 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { value: function inputsForStep(step) { return this.inputTargets.filter(input => input.dataset.popupStepId === step.dataset.stepId); } + }, { + key: "identityInputs", + get: function () { + const inputs = this.inputTargets.filter(input => { + return ['email', 'phone'].includes(input.dataset.popupFieldKind); + }); + return inputs.filter(input => input.required).concat(inputs.filter(input => !input.required)); + } + }, { + key: "completionTextTemplates", + get: function () { + if (this._completionTextTemplates) return this._completionTextTemplates; + const walker = document.createTreeWalker(this.completedTarget, NodeFilter.SHOW_TEXT); + this._completionTextTemplates = []; + while (walker.nextNode()) { + this._completionTextTemplates.push({ + node: walker.currentNode, + template: walker.currentNode.nodeValue + }); + } + return this._completionTextTemplates; + } }, { key: "rulesWithoutScrollPass", value: function rulesWithoutScrollPass() { diff --git a/lib/controllers/popup_controller.js b/lib/controllers/popup_controller.js index 33d6c4fc..36871efb 100644 --- a/lib/controllers/popup_controller.js +++ b/lib/controllers/popup_controller.js @@ -171,8 +171,38 @@ var _default = /*#__PURE__*/function (_Controller) { key: "showCompleted", value: function showCompleted() { this.stepTargets.forEach(step => this.hideElement(step)); + this.interpolateCompletionCopy(); this.showElement(this.completedTarget); } + }, { + key: "interpolateCompletionCopy", + value: function interpolateCompletionCopy() { + var identity = this.identityInputs.map(input => ({ + kind: input.dataset.popupFieldKind, + value: this.identityValue(input) + })).find(_ref => { + var value = _ref.value; + return value; + }); + if (!identity) return; + var replacements = { + destination: identity.value, + channel: identity.kind + }; + this.completionTextTemplates.forEach(_ref2 => { + var node = _ref2.node, + template = _ref2.template; + node.nodeValue = template.replace(/\{(destination|channel)\}/g, (placeholder, key) => replacements[key] || placeholder); + }); + } + }, { + key: "identityValue", + value: function identityValue(input) { + var value = this.inputValue(input).trim(); + if (input.dataset.popupFieldKind !== 'phone' || value.startsWith('+')) return value; + var prefix = input.dataset.popupPhonePrefix; + return prefix ? "".concat(prefix).concat(value.replace(/^0+/, '')) : value; + } }, { key: "currentStepValid", value: function currentStepValid() { @@ -276,6 +306,28 @@ var _default = /*#__PURE__*/function (_Controller) { value: function inputsForStep(step) { return this.inputTargets.filter(input => input.dataset.popupStepId === step.dataset.stepId); } + }, { + key: "identityInputs", + get: function get() { + var inputs = this.inputTargets.filter(input => { + return ['email', 'phone'].includes(input.dataset.popupFieldKind); + }); + return inputs.filter(input => input.required).concat(inputs.filter(input => !input.required)); + } + }, { + key: "completionTextTemplates", + get: function get() { + if (this._completionTextTemplates) return this._completionTextTemplates; + var walker = document.createTreeWalker(this.completedTarget, NodeFilter.SHOW_TEXT); + this._completionTextTemplates = []; + while (walker.nextNode()) { + this._completionTextTemplates.push({ + node: walker.currentNode, + template: walker.currentNode.nodeValue + }); + } + return this._completionTextTemplates; + } }, { key: "rulesWithoutScrollPass", value: function rulesWithoutScrollPass() { diff --git a/src/controllers/popup_controller.js b/src/controllers/popup_controller.js index 82f325b2..a4ade526 100644 --- a/src/controllers/popup_controller.js +++ b/src/controllers/popup_controller.js @@ -162,9 +162,40 @@ export default class extends Controller { showCompleted() { this.stepTargets.forEach(step => this.hideElement(step)) + this.interpolateCompletionCopy() this.showElement(this.completedTarget) } + interpolateCompletionCopy() { + const identity = this.identityInputs.map(input => ({ + kind: input.dataset.popupFieldKind, + value: this.identityValue(input), + })).find(({ value }) => value) + + if (!identity) return + + const replacements = { + destination: identity.value, + channel: identity.kind, + } + + this.completionTextTemplates.forEach(({ node, template }) => { + node.nodeValue = template.replace( + /\{(destination|channel)\}/g, + (placeholder, key) => replacements[key] || placeholder, + ) + }) + } + + identityValue(input) { + const value = this.inputValue(input).trim() + if (input.dataset.popupFieldKind !== 'phone' || value.startsWith('+')) return value + + const prefix = input.dataset.popupPhonePrefix + + return prefix ? `${prefix}${value.replace(/^0+/, '')}` : value + } + currentStepValid() { return this.currentStepInputs.every(input => input.checkValidity()) } @@ -264,6 +295,27 @@ export default class extends Controller { return this.inputTargets.filter(input => input.dataset.popupStepId === step.dataset.stepId) } + get identityInputs() { + const inputs = this.inputTargets.filter(input => { + return ['email', 'phone'].includes(input.dataset.popupFieldKind) + }) + + return inputs.filter(input => input.required).concat(inputs.filter(input => !input.required)) + } + + get completionTextTemplates() { + if (this._completionTextTemplates) return this._completionTextTemplates + + const walker = document.createTreeWalker(this.completedTarget, NodeFilter.SHOW_TEXT) + this._completionTextTemplates = [] + + while (walker.nextNode()) { + this._completionTextTemplates.push({ node: walker.currentNode, template: walker.currentNode.nodeValue }) + } + + return this._completionTextTemplates + } + rulesWithoutScrollPass() { return this.conditions .filter(condition => condition.type !== 'scroll_depth') From d9e0e28202ecfd08d8f134e5836847740bc1d64f Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Mon, 24 Aug 2026 16:44:47 -0400 Subject: [PATCH 05/11] popups: add idempotency key to popup submissions --- __tests__/api/popups_test.js | 12 ++++++++++++ dist/hellotext.js | 2 +- lib/api/popups.cjs | 13 ++++++++++++- lib/api/popups.js | 15 ++++++++++++++- src/api/popups.js | 13 ++++++++++++- 5 files changed, 51 insertions(+), 4 deletions(-) diff --git a/__tests__/api/popups_test.js b/__tests__/api/popups_test.js index 7870d06f..11b3bc15 100644 --- a/__tests__/api/popups_test.js +++ b/__tests__/api/popups_test.js @@ -101,6 +101,7 @@ describe('PopupsAPI', () => { expect(request[0]).toBe('https://api.hellotext.test/v1/public/popups/popup-id/submissions') expect(request[1].method).toBe('POST') expect(request[1].headers.Authorization).toBe('Bearer business-id') + expect(request[1].headers['Idempotency-Key']).toMatch(/^[a-zA-Z0-9._:-]+$/) expect(body).toEqual({ session: 'session-123', popup_submission: { @@ -114,4 +115,15 @@ describe('PopupsAPI', () => { }) expect(response.succeeded).toBe(true) }) + + it('generates a new idempotency key for each submission attempt', async () => { + await PopupsAPI.submit('popup-id', {}) + await PopupsAPI.submit('popup-id', {}) + + const keys = global.fetch.mock.calls.map(([, request]) => request.headers['Idempotency-Key']) + + expect(keys[0]).toBeTruthy() + expect(keys[1]).toBeTruthy() + expect(keys[0]).not.toBe(keys[1]) + }) }) diff --git a/dist/hellotext.js b/dist/hellotext.js index b00b572b..54139c8e 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,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} 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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class U{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),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 H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>gs});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function U(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=U(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=U(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=U(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=q.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=q,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(Fe({session:Ei.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=Ue;function We(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function $e(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){We(o,r,i,a,s,"next",e)}function s(e){We(o,r,i,a,s,"throw",e)}a(void 0)})}}function Ke(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Xe(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xe(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ei.headers}),r=yield n.json();return Ei.business.data||(Ei.business.setData(r.business),Ei.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ze(o,r,i,a,s,"next",e)}function s(e){Ze(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&Qe(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const nt=tt;function rt(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function it(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){rt(o,r,i,a,s,"next",e)}function s(e){rt(o,r,i,a,s,"throw",e)}a(void 0)})}}function ot(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ei.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ei.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){pt(o,r,i,a,s,"next",e)}function s(e){pt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&dt(e.prototype,null),t&&dt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const yt=mt;function gt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(St,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(St,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&xt(e.prototype,t),n&&xt(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function Ct(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return jt(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jt(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),At.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(At.get("hello_utm"))||{}}catch(e){return{}}}}],t&&_t(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new It,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Lt(t.prototype,n),r&&Lt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Dt;Bt(this,Ht)[Ht]=e,Bt(this,Ut)[Ut]=new ye,this.session=Bt(this,Ut)[Ut].session||Z.session||At.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Rt(e.prototype,null),t&&Rt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function $t(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ei.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const rn=Object.entries,on=Object.setPrototypeOf,an=Object.isFrozen,sn=Object.getPrototypeOf,ln=Object.getOwnPropertyDescriptor;let cn=Object.freeze,un=Object.seal,hn=Object.create,pn="undefined"!=typeof Reflect&&Reflect,dn=pn.apply,fn=pn.construct;cn||(cn=function(e){return e}),un||(un=function(e){return e}),dn||(dn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:On;if(on&&on(e,null),!wn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(an(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Fn(e){for(let t=0;t/g),er=un(/\${[\w\W]*/g),tr=un(/^data-[\-\w.\u00B7-\uFFFF]+$/),nr=un(/^aria-[\-\w]+$/),rr=un(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ir=un(/^(?:\w+script|data):/i),or=un(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ar=un(/^html$/i),sr=un(/^[a-z][.\w]*(-[.\w]+)+$/i),lr=un(/<[/\w!]/g),cr=un(/<[/\w]/g),ur=un(/<\/no(script|embed|frames)/i),hr=un(/\/>/i),pr=function(){return"undefined"==typeof window?null:window},dr=function(e,t,n,r){return _n(e,t)&&wn(e[t])?Rn(r.base?Bn(r.base):{},e[t],r.transform):n};var fr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:pr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=Vn(p,"cloneNode"),f=Vn(p,"remove"),m=Vn(p,"nextSibling"),y=Vn(p,"childNodes"),g=Vn(p,"parentNode"),v=Vn(p,"shadowRoot"),b=Vn(p,"attributes"),w=s&&s.prototype?Vn(s.prototype,"nodeType"):null,O=s&&s.prototype?Vn(s.prototype,"nodeName"):null,T=s&&s.prototype?Vn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Ln('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof rn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=Zn,F=Qn,B=er,V=tr,z=nr,q=ir,U=or,H=sr;let W=rr,$=null;const K=Rn({},[...zn,...qn,...Un,...Wn,...Kn]);let G=null;const J=Rn({},[...Gn,...Jn,...Yn,...Xn]);let Y=Object.seal(hn(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}})),X=null,Z=null;const Q=Object.seal(hn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Rn({},["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 Te=null;const xe=Rn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Rn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Rn({},[Ee,Ce,Pe],Tn),Ie=cn(["mi","mo","mn","ms","mtext"]);let Le=Rn({},Ie);const Ne=cn(["annotation-xml"]);let De=Rn({},Ne);const Re=Rn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const qe=r.createElement("form"),Ue=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Bn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Tn:On,$=dr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=dr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=dr(e,"ALLOWED_NAMESPACES",Me,{transform:Tn}),ke=dr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=dr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=dr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=dr(e,"FORBID_TAGS",Bn({}),{transform:Ve}),Z=dr(e,"FORBID_ATTR",Bn({}),{transform:Ve}),be=!!_n(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Bn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return In(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:rr,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=_n(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Bn(e.MATHML_TEXT_INTEGRATION_POINTS):Rn({},Ie),De=_n(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Bn(e.HTML_INTEGRATION_POINTS):Rn({},Ne);const t=_n(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Bn(e.CUSTOM_ELEMENT_HANDLING):hn(null);if(Y=hn(null),_n(t,"tagNameCheck")&&Ue(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),_n(t,"attributeNameCheck")&&Ue(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),_n(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),un(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Rn({},Kn),G=hn(null),!0===be.html&&(Rn($,zn),Rn(G,Gn)),!0===be.svg&&(Rn($,qn),Rn(G,Jn),Rn(G,Xn)),!0===be.svgFilters&&(Rn($,Un),Rn(G,Jn),Rn(G,Xn)),!0===be.mathMl&&(Rn($,Wn),Rn(G,Yn),Rn(G,Xn))),Q.tagCheck=null,Q.attributeCheck=null,_n(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:wn(e.ADD_TAGS)&&($===K&&($=Bn($)),Rn($,e.ADD_TAGS,Ve))),_n(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:wn(e.ADD_ATTR)&&(G===J&&(G=Bn(G)),Rn(G,e.ADD_ATTR,Ve))),_n(e,"ADD_URI_SAFE_ATTR")&&wn(e.ADD_URI_SAFE_ATTR)&&Rn(ke,e.ADD_URI_SAFE_ATTR,Ve),_n(e,"FORBID_CONTENTS")&&wn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.FORBID_CONTENTS,Ve)),_n(e,"ADD_FORBID_CONTENTS")&&wn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Bn(we)),Rn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Rn($,["html","head","body"]),$.table&&(Rn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));cn&&cn(e),ze=e},We=Rn({},[...qn,...Un,...Hn]),$e=Rn({},[...Wn,...$n]),Ke=function(e){vn(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Ln("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];mn(t,t=>{vn(e,t)}),mn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{vn(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){vn(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=xn(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=kn(e,R," "),e=kn(e,F," "),kn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&mn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&mn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Bn(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&In(lr,e.textContent)&&In(lr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!In(cr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=On(e.tagName),r=On(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&In(ur,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(vn(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in qe))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&In(V,t));else if(ee&&In(z,t));else if(i){if(ke[t]);else if(In(W,kn(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Sn(n,"data:")||!Te[e])if(ne&&!In(q,kn(n,U,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&In(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&In(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Rn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[On(e)]&&In(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):gn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:En(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Sn(h,ye)||(Je(a,e),h=ye+h),oe&&In(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&xn(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&In(hr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return Cn(e);case"boolean":return Pn(e);case"bigint":return An?An(e):"0";case"symbol":return jn?jn(e):"Symbol()";case"undefined":default:return Mn(e);case"function":case"object":{if(null===e)return Mn(e);const t=e,n=Vn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Mn(e)}return Mn(e)}}}(e)))throw Ln("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Bn($)),D.uponSanitizeAttribute.length>0&&(G=Bn(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&In(cr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Ln("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Ln("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),mn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return mn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&In(ar,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&_n(D,e)&&vn(D[e],t)},n.removeHook=function(e,t){if(_n(D,e)){if(void 0!==t){const n=yn(D[e],t);return-1===n?void 0:bn(D[e],n,1)[0]}return gn(D[e])}},n.removeHooks=function(e){_n(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),mr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},yr={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function gr(e,t){var n=fr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function vr(e,t){e.replaceChildren(function(e){return gr(e,mr)}(t))}function br(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wr(e,t,n){return(t=xr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Or(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Tr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,Cr,{value:Ar}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ei.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ei.business.features.white_label||this.element.prepend(en.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Or(o,r,i,a,s,"next",e)}function s(e){Or(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-header]","header");vr(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-inputs]","main");e.map(e=>Gt.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)}},{key:"buildButton",value:function(e){var t=kr(this,Cr)[Cr]("[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)}},{key:"buildFooter",value:function(e){var t=kr(this,Cr)[Cr]("[data-form-footer]","footer");vr(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ei.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Tr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Ar(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function jr(e){var t="function"==typeof Map?new Map:void 0;return jr=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(_r())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Mr(i,n.prototype),i}(e,arguments,Ir(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Mr(n,e)},jr(e)}function _r(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_r=function(){return!!e})()}function Mr(e,t){return Mr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Mr(e,t)}function Ir(e){return Ir=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ir(e)}var Lr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Ir(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,_r()?Reflect.construct(t,n||[],Ir(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Mr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(jr(Error));function Nr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Dr(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ei.notInitialized)throw new Lr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,Vr)[Vr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ei.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Nr(o,r,i,a,s,"next",e)}function s(e){Nr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ei.business.data||(Ei.business.setData(e.business),Ei.business.setLocale(j.toString())),Ei.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 Pr(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Dr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function qr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function Ur(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Hr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ur(o,r,i,a,s,"next",e)}function s(e){Ur(o,r,i,a,s,"throw",e)}a(void 0)})}}function Wr(e,t){for(var n=0;ndi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=di(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function fi(e,t){var n=di(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function mi(){return(mi=ci(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var yi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=ci(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return mi.apply(this,arguments)}(fi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&si(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function gi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new Et(e),this.page=new Dt,Z.assign(t),Wt.initialize(this.page),this.forms=new zr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Kr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield Zr.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ri.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=bi({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return gi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Ti(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Lr;var n=bi(bi({},t&&t.headers||{}),this.headers),r=bi(bi({},ai.identificationData),t.user_parameters||{}),i=t&&t.url?new Dt(t.url):this.page,o=bi(bi({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield wt.events.create({headers:n,body:o,keepalive:bt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Ti(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield yi.generate(this.session,e,n);if(yi.matches(ai.fingerprint,r))return new ke(!0,{json:(t=Ti(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield wt.identifications.create(bi({user_id:e},n));return i.succeeded&&ai.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ai.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Wt.session}},{key:"isInitialized",get:function(){return void 0!==Wt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Lr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&xi(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Si.eventEmitter=new ce,Si.forms=void 0,Si.business=void 0,Si.popup=void 0,Si.webchat=void 0,Si.whatsapp=void 0;const Ei=Si;function Ci(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Pi(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ei.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){Ci(o,n,r,a,s,"next",e)}function s(e){Ci(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ei.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&Pi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Di(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ri(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Bi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function $i(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Ki(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$i(o,r,i,a,s,"next",e)}function s(e){$i(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gi(e,t){for(var n=0;n{e.disabled=!0});var t=yield wt.popups.submit(this.idValue,this.submissionPayload());this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed?yield this.handleSubmissionError(t):this.showCompleted()}else this.showErrorMessages(this.currentStepInputs)}),function(e){return o.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.identityInputs.map(e=>({kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value);if(e){var t={destination:e.value,channel:e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Ki(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Gi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a}(g.xI);eo.targets=["bubble","dialog","step","completed","input","submitButton"],eo.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const to=["start","end"],no=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+to[0],t+"-"+to[1]),[]),ro=Math.min,io=Math.max,oo=Math.round,ao=Math.floor,so=e=>({x:e,y:e}),lo={left:"right",right:"left",bottom:"top",top:"bottom"};function co(e,t){return"function"==typeof e?e(t):e}function uo(e){return e.split("-")[0]}function ho(e){return e.split("-")[1]}function po(e){return"x"===e?"y":"x"}function fo(e){return"y"===e?"height":"width"}function mo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function yo(e){return po(mo(e))}function go(e,t,n){void 0===n&&(n=!1);const r=ho(e),i=yo(e),o=fo(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=xo(a)),[a,xo(a)]}function vo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const bo=["left","right"],wo=["right","left"],Oo=["top","bottom"],To=["bottom","top"];function xo(e){const t=uo(e);return lo[t]+e.slice(t.length)}function ko(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function So(e,t,n){let{reference:r,floating:i}=e;const o=mo(t),a=yo(t),s=fo(a),l=uo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=ho(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Eo(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=co(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=ko(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=ko(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const Co=new Set(["left","top"]);function Po(){return"undefined"!=typeof window}function Ao(e){return Mo(e)?(e.nodeName||"").toLowerCase():"#document"}function jo(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function _o(e){var t;return null==(t=(Mo(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Mo(e){return!!Po()&&(e instanceof Node||e instanceof jo(e).Node)}function Io(e){return!!Po()&&(e instanceof Element||e instanceof jo(e).Element)}function Lo(e){return!!Po()&&(e instanceof HTMLElement||e instanceof jo(e).HTMLElement)}function No(e){return!(!Po()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof jo(e).ShadowRoot)}function Do(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=$o(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Ro(e){return/^(table|td|th)$/.test(Ao(e))}function Fo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Bo=/transform|translate|scale|rotate|perspective|filter/,Vo=/paint|layout|strict|content/,zo=e=>!!e&&"none"!==e;let qo;function Uo(e){const t=Io(e)?$o(e):e;return zo(t.transform)||zo(t.translate)||zo(t.scale)||zo(t.rotate)||zo(t.perspective)||!Ho()&&(zo(t.backdropFilter)||zo(t.filter))||Bo.test(t.willChange||"")||Vo.test(t.contain||"")}function Ho(){return null==qo&&(qo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),qo}function Wo(e){return/^(html|body|#document)$/.test(Ao(e))}function $o(e){return jo(e).getComputedStyle(e)}function Ko(e){return Io(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Go(e){if("html"===Ao(e))return e;const t=e.assignedSlot||e.parentNode||No(e)&&e.host||_o(e);return No(t)?t.host:t}function Jo(e){const t=Go(e);return Wo(t)?(e.ownerDocument||e).body:Lo(t)&&Do(t)?t:Jo(t)}function Yo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Jo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=jo(i);if(o){const e=Xo(a);return t.concat(a,a.visualViewport||[],Do(i)?i:[],e&&n?Yo(e):[])}return t.concat(i,Yo(i,[],n))}function Xo(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Zo(e){const t=$o(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Lo(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=oo(n)!==o||oo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function Qo(e){return Io(e)?e:e.contextElement}function ea(e){const t=Qo(e);if(!Lo(t))return so(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Zo(t);let a=(o?oo(n.width):n.width)/r,s=(o?oo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ta=so(0);function na(e){const t=jo(e);return Ho()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ta}function ra(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=Qo(e);let a=so(1);t&&(r?Io(r)&&(a=ea(r)):a=ea(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===jo(e)}(o,n,r)?na(o):so(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=jo(o),t=Io(r)?jo(r):r;let n=e,i=Xo(n);for(;i&&t!==n;){const e=ea(i),t=i.getBoundingClientRect(),r=$o(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=jo(i),i=Xo(n)}}return ko({width:u,height:h,x:l,y:c})}function ia(e,t){const n=Ko(e).scrollLeft;return t?t.left+n:ra(_o(e)).left+n}function oa(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ia(e,n),y:n.top+t.scrollTop}}function aa(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=jo(e),o=_o(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ho()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(ia(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Ko(e),n=e.ownerDocument.body,r=io(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=io(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+ia(e);const a=-t.scrollTop;return"rtl"===$o(n).direction&&(o+=io(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(_o(e));else if(Io(t))r=function(e,t){const n=ra(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ea(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=na(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ko(r)}function sa(e,t,n){const r=Lo(t),i=_o(t),o="fixed"===n,a=ra(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=so(0);if((r||!o)&&(("body"!==Ao(t)||Do(i))&&(s=Ko(t)),r)){const e=ra(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=ia(i));const c=!i||r||o?so(0):oa(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function la(e){return"static"===$o(e).position}function ca(e,t){if(!Lo(e)||"fixed"===$o(e).position)return null;if(t)return t(e);let n=e.offsetParent;return _o(e)===n&&(n=n.ownerDocument.body),n}function ua(e,t){const n=jo(e);if(Fo(e))return n;if(!Lo(e)){let t=Go(e);for(;t&&!Wo(t);){if(Io(t)&&!la(t))return t;t=Go(t)}return n}let r=ca(e,t);for(;r&&Ro(r)&&la(r);)r=ca(r,t);return r&&Wo(r)&&la(r)&&!Uo(r)?n:r||function(e){let t=Go(e);for(;Lo(t)&&!Wo(t);){if(Uo(t))return t;if(Fo(t))return null;t=Go(t)}return null}(e)||n}const ha={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=_o(r),s=!!t&&Fo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=so(1);const u=so(0),h=Lo(r);if((h||!o)&&(("body"!==Ao(r)||Do(a))&&(l=Ko(r)),h)){const e=ra(r);c=ea(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?so(0):oa(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:_o,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?Fo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Yo(e,[],!1).filter(e=>Io(e)&&"body"!==Ao(e)),i=null;const o="fixed"===$o(e).position;let a=o?Go(e):e;for(;Io(a)&&!Wo(a);){const e=$o(a),t=Uo(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Go(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=aa(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;eho(t)===e),...n.filter(t=>ho(t)!==e)]:n.filter(e=>uo(e)===e)).filter(n=>!e||ho(n)===e||!!t&&vo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=go(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[uo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=ho(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,ho(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},ma=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=co(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=mo(i),d=po(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],io(n,ro(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ya=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=co(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=uo(i),v=mo(s),b=uo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[xo(s)]:function(e){const t=xo(e);return[vo(e),t,vo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=ho(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?wo:bo:t?bo:wo;case"left":case"right":return t?Oo:To;default:return[]}}(uo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(vo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=go(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===mo(t)||E.every(e=>mo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=mo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var ga=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=Qo(e),u=i||o?[...c?Yo(c):[],...t?Yo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=_o(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-ao(h)+"px "+-ao(o.clientWidth-(u+p))+"px "+-ao(o.clientHeight-(h+d))+"px "+-ao(u)+"px",threshold:io(0,ro(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!pa(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=jo(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?ra(e):null;return l&&function t(){const r=ra(e);m&&!pa(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...ha,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Eo},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=So(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function va(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ja(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ja(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ei.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ei.session})}},{key:"create",value:(i=Ma(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ei.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ei.headers,body:JSON.stringify({session:Ei.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Ia(t.prototype,n),r&&Ia(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Da=Na;function Ra(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Ra(t.prototype,n),r&&Ra(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Va(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ka(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ha(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ha(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ha(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&Va(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ba);const Ja=Ga;var Ya=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},Xa=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},Za=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function Qa(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function es(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=rs(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ei.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),vr(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){q.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ei.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ei.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",vr(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=rs(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return gr(e,yr)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ei.eventEmitter.dispatch("webchat:message:received",es(es({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=rs(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ei.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ei.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=rs(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ei.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=rs(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ei.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ei.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=rs(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=rs(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[da(this.offsetValue),ma({padding:this.paddingValue}),ya()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ds.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ps)}catch(e){return new Intl.DateTimeFormat(void 0,ps)}}}],r&&is(n.prototype,r),i&&is(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);ms.messageTimestampFormatters={},ms.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},ms.classes=["fadeOut"],ms.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"];var ys=g.lg.start();ys.register("hellotext--form",Ni),ys.register("hellotext--popup",eo),ys.register("hellotext--webchat",ms),ys.register("hellotext--webchat--emoji",Aa),ys.register("hellotext--message",Wi),window.Hellotext=Ei;const gs=Ei},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c(()=>{"use strict";var e={891(e,t,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class U{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class q{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new U(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 q(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new q(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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>ws});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function q(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=q(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=q(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=q(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=U.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=U,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(Fe({session:Ai.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=qe;function We(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $e(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return et(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ai.headers}),r=yield n.json();return Ai.business.data||(Ai.business.setData(r.business),Ai.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){tt(o,r,i,a,s,"next",e)}function s(e){tt(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&nt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ot=it;function at(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function st(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){at(o,r,i,a,s,"next",e)}function s(e){at(o,r,i,a,s,"throw",e)}a(void 0)})}}function lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ai.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){mt(o,r,i,a,s,"next",e)}function s(e){mt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&yt(e.prototype,null),t&&yt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const bt=vt;function wt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(Pt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(Pt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&Et(e.prototype,t),n&&Et(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return It(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),Mt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(Mt.get("hello_utm"))||{}}catch(e){return{}}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new Dt,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Rt(t.prototype,n),r&&Rt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Vt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Bt;Ut(this,Kt)[Kt]=e,Ut(this,$t)[$t]=new ye,this.session=Ut(this,$t)[$t].session||Z.session||Mt.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Vt(e.prototype,null),t&&Vt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ai.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const sn=Object.entries,ln=Object.setPrototypeOf,cn=Object.isFrozen,un=Object.getPrototypeOf,hn=Object.getOwnPropertyDescriptor;let pn=Object.freeze,dn=Object.seal,fn=Object.create,mn="undefined"!=typeof Reflect&&Reflect,yn=mn.apply,gn=mn.construct;pn||(pn=function(e){return e}),dn||(dn=function(e){return e}),yn||(yn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:kn;if(ln&&ln(e,null),!xn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(cn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function zn(e){for(let t=0;t/g),rr=dn(/\${[\w\W]*/g),ir=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),or=dn(/^aria-[\-\w]+$/),ar=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sr=dn(/^(?:\w+script|data):/i),lr=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cr=dn(/^html$/i),ur=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),hr=dn(/<[/\w!]/g),pr=dn(/<[/\w]/g),dr=dn(/<\/no(script|embed|frames)/i),fr=dn(/\/>/i),mr=function(){return"undefined"==typeof window?null:window},yr=function(e,t,n,r){return Ln(e,t)&&xn(e[t])?Vn(r.base?Un(r.base):{},e[t],r.transform):n};var gr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=qn(p,"cloneNode"),f=qn(p,"remove"),m=qn(p,"nextSibling"),y=qn(p,"childNodes"),g=qn(p,"parentNode"),v=qn(p,"shadowRoot"),b=qn(p,"attributes"),w=s&&s.prototype?qn(s.prototype,"nodeType"):null,O=s&&s.prototype?qn(s.prototype,"nodeName"):null,T=s&&s.prototype?qn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Rn('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof sn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=tr,F=nr,B=rr,V=ir,z=or,U=sr,q=lr,H=ur;let W=ar,$=null;const K=Vn({},[...Hn,...Wn,...$n,...Gn,...Yn]);let G=null;const J=Vn({},[...Xn,...Zn,...Qn,...er]);let Y=Object.seal(fn(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}})),X=null,Z=null;const Q=Object.seal(fn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Vn({},["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 Te=null;const xe=Vn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Vn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Vn({},[Ee,Ce,Pe],Sn),Ie=pn(["mi","mo","mn","ms","mtext"]);let Le=Vn({},Ie);const Ne=pn(["annotation-xml"]);let De=Vn({},Ne);const Re=Vn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const Ue=r.createElement("form"),qe=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Un(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Sn:kn,$=yr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=yr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=yr(e,"ALLOWED_NAMESPACES",Me,{transform:Sn}),ke=yr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=yr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=yr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=yr(e,"FORBID_TAGS",Un({}),{transform:Ve}),Z=yr(e,"FORBID_ATTR",Un({}),{transform:Ve}),be=!!Ln(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Un(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return Dn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:ar,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=Ln(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Un(e.MATHML_TEXT_INTEGRATION_POINTS):Vn({},Ie),De=Ln(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Un(e.HTML_INTEGRATION_POINTS):Vn({},Ne);const t=Ln(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Un(e.CUSTOM_ELEMENT_HANDLING):fn(null);if(Y=fn(null),Ln(t,"tagNameCheck")&&qe(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Ln(t,"attributeNameCheck")&&qe(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Ln(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),dn(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Vn({},Yn),G=fn(null),!0===be.html&&(Vn($,Hn),Vn(G,Xn)),!0===be.svg&&(Vn($,Wn),Vn(G,Zn),Vn(G,er)),!0===be.svgFilters&&(Vn($,$n),Vn(G,Zn),Vn(G,er)),!0===be.mathMl&&(Vn($,Gn),Vn(G,Qn),Vn(G,er))),Q.tagCheck=null,Q.attributeCheck=null,Ln(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:xn(e.ADD_TAGS)&&($===K&&($=Un($)),Vn($,e.ADD_TAGS,Ve))),Ln(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:xn(e.ADD_ATTR)&&(G===J&&(G=Un(G)),Vn(G,e.ADD_ATTR,Ve))),Ln(e,"ADD_URI_SAFE_ATTR")&&xn(e.ADD_URI_SAFE_ATTR)&&Vn(ke,e.ADD_URI_SAFE_ATTR,Ve),Ln(e,"FORBID_CONTENTS")&&xn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.FORBID_CONTENTS,Ve)),Ln(e,"ADD_FORBID_CONTENTS")&&xn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Vn($,["html","head","body"]),$.table&&(Vn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));pn&&pn(e),ze=e},We=Vn({},[...Wn,...$n,...Kn]),$e=Vn({},[...Gn,...Jn]),Ke=function(e){On(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Rn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];vn(t,t=>{On(e,t)}),vn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{On(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){On(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=En(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=Cn(e,R," "),e=Cn(e,F," "),Cn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&vn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&vn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Un(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&Dn(hr,e.textContent)&&Dn(hr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!Dn(pr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=kn(e.tagName),r=kn(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&Dn(dr,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(On(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in Ue))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&Dn(V,t));else if(ee&&Dn(z,t));else if(i){if(ke[t]);else if(Dn(W,Cn(n,q,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Pn(n,"data:")||!Te[e])if(ne&&!Dn(U,Cn(n,q,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Dn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Vn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[kn(e)]&&Dn(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):wn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:An(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Pn(h,ye)||(Je(a,e),h=ye+h),oe&&Dn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&En(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&Dn(fr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return jn(e);case"boolean":return _n(e);case"bigint":return Mn?Mn(e):"0";case"symbol":return In?In(e):"Symbol()";case"undefined":default:return Nn(e);case"function":case"object":{if(null===e)return Nn(e);const t=e,n=qn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Nn(e)}return Nn(e)}}}(e)))throw Rn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Un($)),D.uponSanitizeAttribute.length>0&&(G=Un(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&Dn(pr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Rn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Rn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),vn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return vn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Dn(cr,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ln(D,e)&&On(D[e],t)},n.removeHook=function(e,t){if(Ln(D,e)){if(void 0!==t){const n=bn(D[e],t);return-1===n?void 0:Tn(D[e],n,1)[0]}return wn(D[e])}},n.removeHooks=function(e){Ln(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),vr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},br={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function wr(e,t){var n=gr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function Or(e,t){e.replaceChildren(function(e){return wr(e,vr)}(t))}function Tr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xr(e,t,n){return(t=Er(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Sr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,jr,{value:Mr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ai.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ai.business.features.white_label||this.element.prepend(rn.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){kr(o,r,i,a,s,"next",e)}function s(e){kr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=Cr(this,jr)[jr]("[data-form-header]","header");Or(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=Cr(this,jr)[jr]("[data-form-inputs]","main");e.map(e=>Xt.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)}},{key:"buildButton",value:function(e){var t=Cr(this,jr)[jr]("[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)}},{key:"buildFooter",value:function(e){var t=Cr(this,jr)[jr]("[data-form-footer]","footer");Or(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ai.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Sr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Mr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function Ir(e){var t="function"==typeof Map?new Map:void 0;return Ir=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(Lr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Nr(i,n.prototype),i}(e,arguments,Dr(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Nr(n,e)},Ir(e)}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Lr=function(){return!!e})()}function Nr(e,t){return Nr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Nr(e,t)}function Dr(e){return Dr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Dr(e)}var Rr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Dr(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Lr()?Reflect.construct(t,n||[],Dr(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Ir(Error));function Fr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Br(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ai.notInitialized)throw new Rr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,qr)[qr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ai.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Fr(o,r,i,a,s,"next",e)}function s(e){Fr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ai.business.data||(Ai.business.setData(e.business),Ai.business.setLocale(j.toString())),Ai.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 _r(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Br(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Wr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function $r(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Kr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$r(o,r,i,a,s,"next",e)}function s(e){$r(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gr(e,t){for(var n=0;nyi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=yi(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function gi(e,t){var n=yi(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function vi(){return(vi=pi(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var bi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=pi(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return vi.apply(this,arguments)}(gi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&ui(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function wi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new At(e),this.page=new Bt,Z.assign(t),Gt.initialize(this.page),this.forms=new Hr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Yr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield ti.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ai.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=Ti({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return wi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Si(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Rr;var n=Ti(Ti({},t&&t.headers||{}),this.headers),r=Ti(Ti({},ci.identificationData),t.user_parameters||{}),i=t&&t.url?new Bt(t.url):this.page,o=Ti(Ti({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield xt.events.create({headers:n,body:o,keepalive:Tt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Si(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield bi.generate(this.session,e,n);if(bi.matches(ci.fingerprint,r))return new ke(!0,{json:(t=Si(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield xt.identifications.create(Ti({user_id:e},n));return i.succeeded&&ci.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ci.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Gt.session}},{key:"isInitialized",get:function(){return void 0!==Gt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Rr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&Ei(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Pi.eventEmitter=new ce,Pi.forms=void 0,Pi.business=void 0,Pi.popup=void 0,Pi.webchat=void 0,Pi.whatsapp=void 0;const Ai=Pi;function ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function _i(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ai.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){ji(o,n,r,a,s,"next",e)}function s(e){ji(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ai.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&_i(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Bi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Vi(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Ui(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function Ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Yi(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ji(o,r,i,a,s,"next",e)}function s(e){Ji(o,r,i,a,s,"throw",e)}a(void 0)})}}function Xi(e,t){for(var n=0;n{e.disabled=!0});var t=yield xt.popups.submit(this.idValue,this.submissionPayload());this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed?yield this.handleSubmissionError(t):this.showCompleted()}else this.showErrorMessages(this.currentStepInputs)}),function(e){return o.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.identityInputs.map(e=>({kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value);if(e){var t={destination:e.value,channel:e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Yi(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Xi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a}(g.xI);ro.targets=["bubble","dialog","step","completed","input","submitButton"],ro.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const io=["start","end"],oo=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+io[0],t+"-"+io[1]),[]),ao=Math.min,so=Math.max,lo=Math.round,co=Math.floor,uo=e=>({x:e,y:e}),ho={left:"right",right:"left",bottom:"top",top:"bottom"};function po(e,t){return"function"==typeof e?e(t):e}function fo(e){return e.split("-")[0]}function mo(e){return e.split("-")[1]}function yo(e){return"x"===e?"y":"x"}function go(e){return"y"===e?"height":"width"}function vo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function bo(e){return yo(vo(e))}function wo(e,t,n){void 0===n&&(n=!1);const r=mo(e),i=bo(e),o=go(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Eo(a)),[a,Eo(a)]}function Oo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const To=["left","right"],xo=["right","left"],ko=["top","bottom"],So=["bottom","top"];function Eo(e){const t=fo(e);return ho[t]+e.slice(t.length)}function Co(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Po(e,t,n){let{reference:r,floating:i}=e;const o=vo(t),a=bo(t),s=go(a),l=fo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=mo(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Ao(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=po(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=Co(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Co(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const jo=new Set(["left","top"]);function _o(){return"undefined"!=typeof window}function Mo(e){return No(e)?(e.nodeName||"").toLowerCase():"#document"}function Io(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Lo(e){var t;return null==(t=(No(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function No(e){return!!_o()&&(e instanceof Node||e instanceof Io(e).Node)}function Do(e){return!!_o()&&(e instanceof Element||e instanceof Io(e).Element)}function Ro(e){return!!_o()&&(e instanceof HTMLElement||e instanceof Io(e).HTMLElement)}function Fo(e){return!(!_o()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Io(e).ShadowRoot)}function Bo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Jo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Vo(e){return/^(table|td|th)$/.test(Mo(e))}function zo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Uo=/transform|translate|scale|rotate|perspective|filter/,qo=/paint|layout|strict|content/,Ho=e=>!!e&&"none"!==e;let Wo;function $o(e){const t=Do(e)?Jo(e):e;return Ho(t.transform)||Ho(t.translate)||Ho(t.scale)||Ho(t.rotate)||Ho(t.perspective)||!Ko()&&(Ho(t.backdropFilter)||Ho(t.filter))||Uo.test(t.willChange||"")||qo.test(t.contain||"")}function Ko(){return null==Wo&&(Wo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Wo}function Go(e){return/^(html|body|#document)$/.test(Mo(e))}function Jo(e){return Io(e).getComputedStyle(e)}function Yo(e){return Do(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xo(e){if("html"===Mo(e))return e;const t=e.assignedSlot||e.parentNode||Fo(e)&&e.host||Lo(e);return Fo(t)?t.host:t}function Zo(e){const t=Xo(e);return Go(t)?(e.ownerDocument||e).body:Ro(t)&&Bo(t)?t:Zo(t)}function Qo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Zo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Io(i);if(o){const e=ea(a);return t.concat(a,a.visualViewport||[],Bo(i)?i:[],e&&n?Qo(e):[])}return t.concat(i,Qo(i,[],n))}function ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ta(e){const t=Jo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ro(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=lo(n)!==o||lo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function na(e){return Do(e)?e:e.contextElement}function ra(e){const t=na(e);if(!Ro(t))return uo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=ta(t);let a=(o?lo(n.width):n.width)/r,s=(o?lo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ia=uo(0);function oa(e){const t=Io(e);return Ko()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ia}function aa(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=na(e);let a=uo(1);t&&(r?Do(r)&&(a=ra(r)):a=ra(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===Io(e)}(o,n,r)?oa(o):uo(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=Io(o),t=Do(r)?Io(r):r;let n=e,i=ea(n);for(;i&&t!==n;){const e=ra(i),t=i.getBoundingClientRect(),r=Jo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=Io(i),i=ea(n)}}return Co({width:u,height:h,x:l,y:c})}function sa(e,t){const n=Yo(e).scrollLeft;return t?t.left+n:aa(Lo(e)).left+n}function la(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-sa(e,n),y:n.top+t.scrollTop}}function ca(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=Io(e),o=Lo(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ko()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(sa(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Yo(e),n=e.ownerDocument.body,r=so(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=so(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+sa(e);const a=-t.scrollTop;return"rtl"===Jo(n).direction&&(o+=so(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(Lo(e));else if(Do(t))r=function(e,t){const n=aa(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ra(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=oa(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Co(r)}function ua(e,t,n){const r=Ro(t),i=Lo(t),o="fixed"===n,a=aa(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=uo(0);if((r||!o)&&(("body"!==Mo(t)||Bo(i))&&(s=Yo(t)),r)){const e=aa(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=sa(i));const c=!i||r||o?uo(0):la(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function ha(e){return"static"===Jo(e).position}function pa(e,t){if(!Ro(e)||"fixed"===Jo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Lo(e)===n&&(n=n.ownerDocument.body),n}function da(e,t){const n=Io(e);if(zo(e))return n;if(!Ro(e)){let t=Xo(e);for(;t&&!Go(t);){if(Do(t)&&!ha(t))return t;t=Xo(t)}return n}let r=pa(e,t);for(;r&&Vo(r)&&ha(r);)r=pa(r,t);return r&&Go(r)&&ha(r)&&!$o(r)?n:r||function(e){let t=Xo(e);for(;Ro(t)&&!Go(t);){if($o(t))return t;if(zo(t))return null;t=Xo(t)}return null}(e)||n}const fa={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Lo(r),s=!!t&&zo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=uo(1);const u=uo(0),h=Ro(r);if((h||!o)&&(("body"!==Mo(r)||Bo(a))&&(l=Yo(r)),h)){const e=aa(r);c=ra(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?uo(0):la(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:Lo,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?zo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Qo(e,[],!1).filter(e=>Do(e)&&"body"!==Mo(e)),i=null;const o="fixed"===Jo(e).position;let a=o?Xo(e):e;for(;Do(a)&&!Go(a);){const e=Jo(a),t=$o(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Xo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=ca(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;emo(t)===e),...n.filter(t=>mo(t)!==e)]:n.filter(e=>fo(e)===e)).filter(n=>!e||mo(n)===e||!!t&&Oo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=wo(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[fo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=mo(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,mo(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},va=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=po(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=vo(i),d=yo(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],so(n,ao(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ba=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=po(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=fo(i),v=vo(s),b=fo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[Eo(s)]:function(e){const t=Eo(e);return[Oo(e),t,Oo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=mo(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?xo:To:t?To:xo;case"left":case"right":return t?ko:So;default:return[]}}(fo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(Oo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=wo(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===vo(t)||E.every(e=>vo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=vo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var wa=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=na(e),u=i||o?[...c?Qo(c):[],...t?Qo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=Lo(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-co(h)+"px "+-co(o.clientWidth-(u+p))+"px "+-co(o.clientHeight-(h+d))+"px "+-co(u)+"px",threshold:so(0,ao(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!ma(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=Io(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?aa(e):null;return l&&function t(){const r=aa(e);m&&!ma(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...fa,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Ao},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=Po(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Oa(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ia(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ia(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ai.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ai.session})}},{key:"create",value:(i=Na(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ai.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ai.headers,body:JSON.stringify({session:Ai.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Da(t.prototype,n),r&&Da(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Ba=Fa;function Va(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Va(t.prototype,n),r&&Va(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function qa(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ya(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ka(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ka(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ka(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&qa(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ua);const Za=Xa;var Qa=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},es=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ts=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function ns(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=as(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ai.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),Or(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){U.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ai.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ai.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",Or(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=as(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return wr(e,br)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=as(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ai.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ai.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=as(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ai.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=as(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ai.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=as(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=as(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[ya(this.offsetValue),va({padding:this.paddingValue}),ba()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ys.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ms)}catch(e){return new Intl.DateTimeFormat(void 0,ms)}}}],r&&ss(n.prototype,r),i&&ss(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);vs.messageTimestampFormatters={},vs.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},vs.classes=["fadeOut"],vs.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"];var bs=g.lg.start();bs.register("hellotext--form",Fi),bs.register("hellotext--popup",ro),bs.register("hellotext--webchat",vs),bs.register("hellotext--webchat--emoji",Ma),bs.register("hellotext--message",Gi),window.Hellotext=Ai;const ws=Ai},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c Date: Mon, 24 Aug 2026 17:26:07 -0400 Subject: [PATCH 06/11] popups: style runtime completion buttons --- styles/index.css | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/styles/index.css b/styles/index.css index 608cd522..1eb1a0d0 100644 --- a/styles/index.css +++ b/styles/index.css @@ -634,7 +634,40 @@ form[data-hello-form] [data-logo-container] [data-hello-brand] { width: 100%; margin-top: 16px; font-size: 12px; - opacity: 0.72; +} + +.hellotext--popup__completion-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 0 4px; + text-align: center; +} + +.hellotext--popup__completion-footer > span, +.hellotext--popup__completion-action:disabled { + opacity: 0.5; +} + +.hellotext--popup__completion-action { + appearance: none; + margin: 0; + padding: 0; + border: 0; + background: transparent; + color: inherit; + cursor: pointer; + font: inherit; + font-weight: 500; + line-height: inherit; + text-decoration: underline; + text-underline-offset: 2px; +} + +.hellotext--popup__completion-action:disabled { + cursor: default; + text-decoration: none; } .hellotext--popup__completed { width: 100%; text-align: center; } From 9e29c5eaf027cea4d97f67ecd14b9388c787a133 Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Mon, 24 Aug 2026 21:08:52 -0400 Subject: [PATCH 07/11] popups: add resend verification flow to runtime sdk --- __tests__/api/popups_test.js | 30 ++++ .../controllers/popup_controller_test.js | 118 +++++++++++++- dist/hellotext.js | 2 +- lib/api/popups.cjs | 25 +++ lib/api/popups.js | 41 ++++- lib/controllers/popup_controller.cjs | 128 ++++++++++++++- lib/controllers/popup_controller.js | 150 +++++++++++++++-- src/api/popups.js | 20 +++ src/controllers/popup_controller.js | 152 +++++++++++++++++- 9 files changed, 632 insertions(+), 34 deletions(-) diff --git a/__tests__/api/popups_test.js b/__tests__/api/popups_test.js index 11b3bc15..82918ce3 100644 --- a/__tests__/api/popups_test.js +++ b/__tests__/api/popups_test.js @@ -126,4 +126,34 @@ describe('PopupsAPI', () => { expect(keys[1]).toBeTruthy() expect(keys[0]).not.toBe(keys[1]) }) + + it('resends verification for the selected popup identity', async () => { + const response = await PopupsAPI.resend('popup-id', 'submission-id', 'email', 'action-token') + const request = global.fetch.mock.calls[0] + + expect(request[0]).toBe( + 'https://api.hellotext.test/v1/public/popups/popup-id/submissions/submission-id/resend', + ) + expect(request[1]).toEqual({ + method: 'POST', + headers: Hellotext.headers, + body: JSON.stringify({ identity: 'email', token: 'action-token' }), + }) + expect(response.succeeded).toBe(true) + }) + + it('cancels the previous submission before changing its destination', async () => { + const response = await PopupsAPI.cancel('popup-id', 'submission-id', 'action-token') + const request = global.fetch.mock.calls[0] + + expect(request[0]).toBe( + 'https://api.hellotext.test/v1/public/popups/popup-id/submissions/submission-id/cancel', + ) + expect(request[1]).toEqual({ + method: 'POST', + headers: Hellotext.headers, + body: JSON.stringify({ token: 'action-token' }), + }) + expect(response.succeeded).toBe(true) + }) }) diff --git a/__tests__/controllers/popup_controller_test.js b/__tests__/controllers/popup_controller_test.js index a5f3e36d..ff60fb11 100644 --- a/__tests__/controllers/popup_controller_test.js +++ b/__tests__/controllers/popup_controller_test.js @@ -20,6 +20,8 @@ describe('PopupController', () => { const phoneInput = document.createElement('input') const stepOneButton = document.createElement('button') const stepTwoButton = document.createElement('button') + const resendButton = document.createElement('button') + const changeDestinationButton = document.createElement('button') bubble.textContent = '10% OFF' emailInput.type = 'email' @@ -42,6 +44,13 @@ describe('PopupController', () => { '

We sent it to {destination}', ' via {channel}. It may take a minute to arrive.

', ].join('') + resendButton.textContent = 'Resend' + resendButton.hidden = true + resendButton.dataset.countdownLabel = 'Resend in %{time}' + changeDestinationButton.hidden = true + changeDestinationButton.dataset.emailLabel = 'Change email' + changeDestinationButton.dataset.phoneLabel = 'Change number' + completed.append(resendButton, changeDestinationButton) stepOne.appendChild(emailInput) stepTwo.appendChild(phoneInput) @@ -62,6 +71,12 @@ describe('PopupController', () => { controller.stepTargets = [stepOne, stepTwo] controller.inputTargets = [emailInput, phoneInput] controller.submitButtonTargets = [stepOneButton, stepTwoButton] + Object.defineProperties(controller, { + resendButtonTarget: { value: resendButton, configurable: true }, + changeDestinationButtonTarget: { value: changeDestinationButton, configurable: true }, + hasResendButtonTarget: { value: true, configurable: true }, + hasChangeDestinationButtonTarget: { value: true, configurable: true }, + }) controller.hasBubbleTarget = hasBubble controller.hasBubbleValue = hasBubble controller.captureValue = { capture_id: 'capture-id' } @@ -69,15 +84,39 @@ describe('PopupController', () => { controller.idValue = 'popup-id' controller.rulesValue = rules - return { element, bubble, dialog, completed, stepOne, stepTwo, emailInput, phoneInput } + return { + element, + bubble, + dialog, + completed, + stepOne, + stepTwo, + emailInput, + phoneInput, + resendButton, + changeDestinationButton, + } } beforeEach(() => { originalLocalStorage = window.localStorage - jest.spyOn(API.popups, 'submit').mockResolvedValue({ failed: false }) + jest.spyOn(API.popups, 'submit').mockResolvedValue({ + failed: false, + json: jest.fn().mockResolvedValue({ + id: 'submission-id', + verification_state: 'unverified', + action_token: 'action-token', + }), + }) + jest.spyOn(API.popups, 'resend').mockResolvedValue({ + succeeded: true, + data: { headers: new Headers({ 'Retry-After': '60' }), status: 202 }, + }) + jest.spyOn(API.popups, 'cancel').mockResolvedValue({ failed: false, succeeded: true }) }) afterEach(() => { + jest.useRealTimers() jest.restoreAllMocks() Object.defineProperty(window, 'localStorage', { value: originalLocalStorage, @@ -180,12 +219,77 @@ describe('PopupController', () => { expect(stepOne.hidden).toBe(true) expect(stepTwo.hidden).toBe(true) expect(completed.hidden).toBe(false) - expect(completed.textContent).toBe( + expect(completed.querySelector('p').textContent).toBe( 'We sent it to customer@example.com via email. It may take a minute to arrive.', ) expect(completed.querySelector('strong').textContent).toBe('customer@example.com') }) + it('shows a one-minute resend cooldown and the change action for the submitted identity', async () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-08-24T12:00:00Z')) + const { emailInput, phoneInput, resendButton, changeDestinationButton } = buildController({ hasBubble: false }) + + controller.connect() + phoneInput.required = false + emailInput.value = 'customer@example.com' + await controller.next() + await controller.submit() + + expect(resendButton.hidden).toBe(false) + expect(resendButton.disabled).toBe(true) + expect(resendButton.textContent).toBe('Resend in 1:00') + expect(changeDestinationButton.hidden).toBe(false) + expect(changeDestinationButton.textContent).toBe('Change email') + + jest.advanceTimersByTime(60000) + + expect(resendButton.disabled).toBe(false) + expect(resendButton.textContent).toBe('Resend') + }) + + it('resends only the identity shown in the completed step and restarts the cooldown', async () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-08-24T12:00:00Z')) + const { emailInput, phoneInput, resendButton } = buildController({ hasBubble: false }) + + controller.connect() + phoneInput.required = false + emailInput.value = 'customer@example.com' + await controller.next() + await controller.submit() + jest.advanceTimersByTime(60000) + + await controller.resend({ preventDefault: jest.fn() }) + + expect(API.popups.resend).toHaveBeenCalledWith( + 'popup-id', + 'submission-id', + 'email', + 'action-token', + ) + expect(resendButton.disabled).toBe(true) + expect(resendButton.textContent).toBe('Resend in 1:00') + }) + + it('returns to and focuses the step that owns the completed identity', async () => { + const { completed, emailInput, phoneInput, stepOne, changeDestinationButton } = buildController({ hasBubble: false }) + jest.spyOn(emailInput, 'focus') + + controller.connect() + phoneInput.required = false + emailInput.value = 'customer@example.com' + await controller.next() + await controller.submit() + await controller.changeDestination({ preventDefault: jest.fn() }) + + expect(API.popups.cancel).toHaveBeenCalledWith('popup-id', 'submission-id', 'action-token') + expect(completed.hidden).toBe(true) + expect(stepOne.hidden).toBe(false) + expect(emailInput.focus).toHaveBeenCalled() + expect(changeDestinationButton.textContent).toBe('Change email') + }) + it('uses a readable channel when the popup only requires one identity field', () => { const { completed, emailInput, phoneInput } = buildController({ hasBubble: false }) @@ -194,14 +298,14 @@ describe('PopupController', () => { controller.showCompleted() - expect(completed.textContent).toBe( + expect(completed.querySelector('p').textContent).toBe( 'We sent it to customer@example.com via email. It may take a minute to arrive.', ) emailInput.value = 'updated@example.com' controller.showCompleted() - expect(completed.textContent).toBe( + expect(completed.querySelector('p').textContent).toBe( 'We sent it to updated@example.com via email. It may take a minute to arrive.', ) }) @@ -215,7 +319,7 @@ describe('PopupController', () => { controller.showCompleted() - expect(completed.textContent).toBe( + expect(completed.querySelector('p').textContent).toBe( 'We sent it to customer@example.com via email. It may take a minute to arrive.', ) }) @@ -229,7 +333,7 @@ describe('PopupController', () => { controller.showCompleted() - expect(completed.textContent).toBe( + expect(completed.querySelector('p').textContent).toBe( 'We sent it to +584126625353 via phone. It may take a minute to arrive.', ) }) diff --git a/dist/hellotext.js b/dist/hellotext.js index 54139c8e..fd25fa43 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,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class U{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class q{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new U(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 q(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new q(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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>ws});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function q(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=q(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=q(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=q(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=U.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=U,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(Fe({session:Ai.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=qe;function We(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $e(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return et(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ai.headers}),r=yield n.json();return Ai.business.data||(Ai.business.setData(r.business),Ai.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){tt(o,r,i,a,s,"next",e)}function s(e){tt(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&nt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ot=it;function at(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function st(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){at(o,r,i,a,s,"next",e)}function s(e){at(o,r,i,a,s,"throw",e)}a(void 0)})}}function lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ai.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){mt(o,r,i,a,s,"next",e)}function s(e){mt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&yt(e.prototype,null),t&&yt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const bt=vt;function wt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(Pt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(Pt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&Et(e.prototype,t),n&&Et(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return It(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),Mt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(Mt.get("hello_utm"))||{}}catch(e){return{}}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new Dt,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Rt(t.prototype,n),r&&Rt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Vt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Bt;Ut(this,Kt)[Kt]=e,Ut(this,$t)[$t]=new ye,this.session=Ut(this,$t)[$t].session||Z.session||Mt.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Vt(e.prototype,null),t&&Vt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ai.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const sn=Object.entries,ln=Object.setPrototypeOf,cn=Object.isFrozen,un=Object.getPrototypeOf,hn=Object.getOwnPropertyDescriptor;let pn=Object.freeze,dn=Object.seal,fn=Object.create,mn="undefined"!=typeof Reflect&&Reflect,yn=mn.apply,gn=mn.construct;pn||(pn=function(e){return e}),dn||(dn=function(e){return e}),yn||(yn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:kn;if(ln&&ln(e,null),!xn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(cn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function zn(e){for(let t=0;t/g),rr=dn(/\${[\w\W]*/g),ir=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),or=dn(/^aria-[\-\w]+$/),ar=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sr=dn(/^(?:\w+script|data):/i),lr=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cr=dn(/^html$/i),ur=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),hr=dn(/<[/\w!]/g),pr=dn(/<[/\w]/g),dr=dn(/<\/no(script|embed|frames)/i),fr=dn(/\/>/i),mr=function(){return"undefined"==typeof window?null:window},yr=function(e,t,n,r){return Ln(e,t)&&xn(e[t])?Vn(r.base?Un(r.base):{},e[t],r.transform):n};var gr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=qn(p,"cloneNode"),f=qn(p,"remove"),m=qn(p,"nextSibling"),y=qn(p,"childNodes"),g=qn(p,"parentNode"),v=qn(p,"shadowRoot"),b=qn(p,"attributes"),w=s&&s.prototype?qn(s.prototype,"nodeType"):null,O=s&&s.prototype?qn(s.prototype,"nodeName"):null,T=s&&s.prototype?qn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Rn('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof sn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=tr,F=nr,B=rr,V=ir,z=or,U=sr,q=lr,H=ur;let W=ar,$=null;const K=Vn({},[...Hn,...Wn,...$n,...Gn,...Yn]);let G=null;const J=Vn({},[...Xn,...Zn,...Qn,...er]);let Y=Object.seal(fn(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}})),X=null,Z=null;const Q=Object.seal(fn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Vn({},["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 Te=null;const xe=Vn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Vn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Vn({},[Ee,Ce,Pe],Sn),Ie=pn(["mi","mo","mn","ms","mtext"]);let Le=Vn({},Ie);const Ne=pn(["annotation-xml"]);let De=Vn({},Ne);const Re=Vn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const Ue=r.createElement("form"),qe=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Un(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Sn:kn,$=yr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=yr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=yr(e,"ALLOWED_NAMESPACES",Me,{transform:Sn}),ke=yr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=yr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=yr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=yr(e,"FORBID_TAGS",Un({}),{transform:Ve}),Z=yr(e,"FORBID_ATTR",Un({}),{transform:Ve}),be=!!Ln(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Un(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return Dn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:ar,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=Ln(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Un(e.MATHML_TEXT_INTEGRATION_POINTS):Vn({},Ie),De=Ln(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Un(e.HTML_INTEGRATION_POINTS):Vn({},Ne);const t=Ln(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Un(e.CUSTOM_ELEMENT_HANDLING):fn(null);if(Y=fn(null),Ln(t,"tagNameCheck")&&qe(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Ln(t,"attributeNameCheck")&&qe(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Ln(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),dn(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Vn({},Yn),G=fn(null),!0===be.html&&(Vn($,Hn),Vn(G,Xn)),!0===be.svg&&(Vn($,Wn),Vn(G,Zn),Vn(G,er)),!0===be.svgFilters&&(Vn($,$n),Vn(G,Zn),Vn(G,er)),!0===be.mathMl&&(Vn($,Gn),Vn(G,Qn),Vn(G,er))),Q.tagCheck=null,Q.attributeCheck=null,Ln(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:xn(e.ADD_TAGS)&&($===K&&($=Un($)),Vn($,e.ADD_TAGS,Ve))),Ln(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:xn(e.ADD_ATTR)&&(G===J&&(G=Un(G)),Vn(G,e.ADD_ATTR,Ve))),Ln(e,"ADD_URI_SAFE_ATTR")&&xn(e.ADD_URI_SAFE_ATTR)&&Vn(ke,e.ADD_URI_SAFE_ATTR,Ve),Ln(e,"FORBID_CONTENTS")&&xn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.FORBID_CONTENTS,Ve)),Ln(e,"ADD_FORBID_CONTENTS")&&xn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Vn($,["html","head","body"]),$.table&&(Vn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));pn&&pn(e),ze=e},We=Vn({},[...Wn,...$n,...Kn]),$e=Vn({},[...Gn,...Jn]),Ke=function(e){On(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Rn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];vn(t,t=>{On(e,t)}),vn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{On(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){On(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=En(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=Cn(e,R," "),e=Cn(e,F," "),Cn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&vn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&vn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Un(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&Dn(hr,e.textContent)&&Dn(hr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!Dn(pr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=kn(e.tagName),r=kn(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&Dn(dr,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(On(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in Ue))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&Dn(V,t));else if(ee&&Dn(z,t));else if(i){if(ke[t]);else if(Dn(W,Cn(n,q,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Pn(n,"data:")||!Te[e])if(ne&&!Dn(U,Cn(n,q,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Dn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Vn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[kn(e)]&&Dn(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):wn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:An(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Pn(h,ye)||(Je(a,e),h=ye+h),oe&&Dn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&En(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&Dn(fr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return jn(e);case"boolean":return _n(e);case"bigint":return Mn?Mn(e):"0";case"symbol":return In?In(e):"Symbol()";case"undefined":default:return Nn(e);case"function":case"object":{if(null===e)return Nn(e);const t=e,n=qn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Nn(e)}return Nn(e)}}}(e)))throw Rn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Un($)),D.uponSanitizeAttribute.length>0&&(G=Un(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&Dn(pr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Rn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Rn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),vn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return vn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Dn(cr,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ln(D,e)&&On(D[e],t)},n.removeHook=function(e,t){if(Ln(D,e)){if(void 0!==t){const n=bn(D[e],t);return-1===n?void 0:Tn(D[e],n,1)[0]}return wn(D[e])}},n.removeHooks=function(e){Ln(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),vr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},br={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function wr(e,t){var n=gr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function Or(e,t){e.replaceChildren(function(e){return wr(e,vr)}(t))}function Tr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xr(e,t,n){return(t=Er(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Sr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,jr,{value:Mr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ai.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ai.business.features.white_label||this.element.prepend(rn.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){kr(o,r,i,a,s,"next",e)}function s(e){kr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=Cr(this,jr)[jr]("[data-form-header]","header");Or(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=Cr(this,jr)[jr]("[data-form-inputs]","main");e.map(e=>Xt.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)}},{key:"buildButton",value:function(e){var t=Cr(this,jr)[jr]("[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)}},{key:"buildFooter",value:function(e){var t=Cr(this,jr)[jr]("[data-form-footer]","footer");Or(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ai.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Sr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Mr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function Ir(e){var t="function"==typeof Map?new Map:void 0;return Ir=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(Lr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Nr(i,n.prototype),i}(e,arguments,Dr(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Nr(n,e)},Ir(e)}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Lr=function(){return!!e})()}function Nr(e,t){return Nr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Nr(e,t)}function Dr(e){return Dr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Dr(e)}var Rr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Dr(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Lr()?Reflect.construct(t,n||[],Dr(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Ir(Error));function Fr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Br(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ai.notInitialized)throw new Rr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,qr)[qr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ai.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Fr(o,r,i,a,s,"next",e)}function s(e){Fr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ai.business.data||(Ai.business.setData(e.business),Ai.business.setLocale(j.toString())),Ai.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 _r(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Br(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Wr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function $r(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Kr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$r(o,r,i,a,s,"next",e)}function s(e){$r(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gr(e,t){for(var n=0;nyi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=yi(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function gi(e,t){var n=yi(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function vi(){return(vi=pi(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var bi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=pi(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return vi.apply(this,arguments)}(gi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&ui(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function wi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new At(e),this.page=new Bt,Z.assign(t),Gt.initialize(this.page),this.forms=new Hr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Yr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield ti.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ai.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=Ti({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return wi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Si(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Rr;var n=Ti(Ti({},t&&t.headers||{}),this.headers),r=Ti(Ti({},ci.identificationData),t.user_parameters||{}),i=t&&t.url?new Bt(t.url):this.page,o=Ti(Ti({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield xt.events.create({headers:n,body:o,keepalive:Tt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Si(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield bi.generate(this.session,e,n);if(bi.matches(ci.fingerprint,r))return new ke(!0,{json:(t=Si(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield xt.identifications.create(Ti({user_id:e},n));return i.succeeded&&ci.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ci.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Gt.session}},{key:"isInitialized",get:function(){return void 0!==Gt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Rr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&Ei(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Pi.eventEmitter=new ce,Pi.forms=void 0,Pi.business=void 0,Pi.popup=void 0,Pi.webchat=void 0,Pi.whatsapp=void 0;const Ai=Pi;function ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function _i(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ai.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){ji(o,n,r,a,s,"next",e)}function s(e){ji(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ai.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&_i(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Bi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Vi(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Ui(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function Ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Yi(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ji(o,r,i,a,s,"next",e)}function s(e){Ji(o,r,i,a,s,"throw",e)}a(void 0)})}}function Xi(e,t){for(var n=0;n{e.disabled=!0});var t=yield xt.popups.submit(this.idValue,this.submissionPayload());this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed?yield this.handleSubmissionError(t):this.showCompleted()}else this.showErrorMessages(this.currentStepInputs)}),function(e){return o.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.identityInputs.map(e=>({kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value);if(e){var t={destination:e.value,channel:e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Yi(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Xi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a}(g.xI);ro.targets=["bubble","dialog","step","completed","input","submitButton"],ro.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const io=["start","end"],oo=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+io[0],t+"-"+io[1]),[]),ao=Math.min,so=Math.max,lo=Math.round,co=Math.floor,uo=e=>({x:e,y:e}),ho={left:"right",right:"left",bottom:"top",top:"bottom"};function po(e,t){return"function"==typeof e?e(t):e}function fo(e){return e.split("-")[0]}function mo(e){return e.split("-")[1]}function yo(e){return"x"===e?"y":"x"}function go(e){return"y"===e?"height":"width"}function vo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function bo(e){return yo(vo(e))}function wo(e,t,n){void 0===n&&(n=!1);const r=mo(e),i=bo(e),o=go(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Eo(a)),[a,Eo(a)]}function Oo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const To=["left","right"],xo=["right","left"],ko=["top","bottom"],So=["bottom","top"];function Eo(e){const t=fo(e);return ho[t]+e.slice(t.length)}function Co(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Po(e,t,n){let{reference:r,floating:i}=e;const o=vo(t),a=bo(t),s=go(a),l=fo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=mo(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Ao(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=po(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=Co(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Co(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const jo=new Set(["left","top"]);function _o(){return"undefined"!=typeof window}function Mo(e){return No(e)?(e.nodeName||"").toLowerCase():"#document"}function Io(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Lo(e){var t;return null==(t=(No(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function No(e){return!!_o()&&(e instanceof Node||e instanceof Io(e).Node)}function Do(e){return!!_o()&&(e instanceof Element||e instanceof Io(e).Element)}function Ro(e){return!!_o()&&(e instanceof HTMLElement||e instanceof Io(e).HTMLElement)}function Fo(e){return!(!_o()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Io(e).ShadowRoot)}function Bo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Jo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Vo(e){return/^(table|td|th)$/.test(Mo(e))}function zo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Uo=/transform|translate|scale|rotate|perspective|filter/,qo=/paint|layout|strict|content/,Ho=e=>!!e&&"none"!==e;let Wo;function $o(e){const t=Do(e)?Jo(e):e;return Ho(t.transform)||Ho(t.translate)||Ho(t.scale)||Ho(t.rotate)||Ho(t.perspective)||!Ko()&&(Ho(t.backdropFilter)||Ho(t.filter))||Uo.test(t.willChange||"")||qo.test(t.contain||"")}function Ko(){return null==Wo&&(Wo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Wo}function Go(e){return/^(html|body|#document)$/.test(Mo(e))}function Jo(e){return Io(e).getComputedStyle(e)}function Yo(e){return Do(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xo(e){if("html"===Mo(e))return e;const t=e.assignedSlot||e.parentNode||Fo(e)&&e.host||Lo(e);return Fo(t)?t.host:t}function Zo(e){const t=Xo(e);return Go(t)?(e.ownerDocument||e).body:Ro(t)&&Bo(t)?t:Zo(t)}function Qo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Zo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Io(i);if(o){const e=ea(a);return t.concat(a,a.visualViewport||[],Bo(i)?i:[],e&&n?Qo(e):[])}return t.concat(i,Qo(i,[],n))}function ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ta(e){const t=Jo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ro(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=lo(n)!==o||lo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function na(e){return Do(e)?e:e.contextElement}function ra(e){const t=na(e);if(!Ro(t))return uo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=ta(t);let a=(o?lo(n.width):n.width)/r,s=(o?lo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ia=uo(0);function oa(e){const t=Io(e);return Ko()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ia}function aa(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=na(e);let a=uo(1);t&&(r?Do(r)&&(a=ra(r)):a=ra(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===Io(e)}(o,n,r)?oa(o):uo(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=Io(o),t=Do(r)?Io(r):r;let n=e,i=ea(n);for(;i&&t!==n;){const e=ra(i),t=i.getBoundingClientRect(),r=Jo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=Io(i),i=ea(n)}}return Co({width:u,height:h,x:l,y:c})}function sa(e,t){const n=Yo(e).scrollLeft;return t?t.left+n:aa(Lo(e)).left+n}function la(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-sa(e,n),y:n.top+t.scrollTop}}function ca(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=Io(e),o=Lo(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ko()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(sa(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Yo(e),n=e.ownerDocument.body,r=so(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=so(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+sa(e);const a=-t.scrollTop;return"rtl"===Jo(n).direction&&(o+=so(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(Lo(e));else if(Do(t))r=function(e,t){const n=aa(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ra(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=oa(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Co(r)}function ua(e,t,n){const r=Ro(t),i=Lo(t),o="fixed"===n,a=aa(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=uo(0);if((r||!o)&&(("body"!==Mo(t)||Bo(i))&&(s=Yo(t)),r)){const e=aa(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=sa(i));const c=!i||r||o?uo(0):la(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function ha(e){return"static"===Jo(e).position}function pa(e,t){if(!Ro(e)||"fixed"===Jo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Lo(e)===n&&(n=n.ownerDocument.body),n}function da(e,t){const n=Io(e);if(zo(e))return n;if(!Ro(e)){let t=Xo(e);for(;t&&!Go(t);){if(Do(t)&&!ha(t))return t;t=Xo(t)}return n}let r=pa(e,t);for(;r&&Vo(r)&&ha(r);)r=pa(r,t);return r&&Go(r)&&ha(r)&&!$o(r)?n:r||function(e){let t=Xo(e);for(;Ro(t)&&!Go(t);){if($o(t))return t;if(zo(t))return null;t=Xo(t)}return null}(e)||n}const fa={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Lo(r),s=!!t&&zo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=uo(1);const u=uo(0),h=Ro(r);if((h||!o)&&(("body"!==Mo(r)||Bo(a))&&(l=Yo(r)),h)){const e=aa(r);c=ra(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?uo(0):la(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:Lo,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?zo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Qo(e,[],!1).filter(e=>Do(e)&&"body"!==Mo(e)),i=null;const o="fixed"===Jo(e).position;let a=o?Xo(e):e;for(;Do(a)&&!Go(a);){const e=Jo(a),t=$o(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Xo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=ca(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;emo(t)===e),...n.filter(t=>mo(t)!==e)]:n.filter(e=>fo(e)===e)).filter(n=>!e||mo(n)===e||!!t&&Oo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=wo(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[fo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=mo(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,mo(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},va=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=po(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=vo(i),d=yo(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],so(n,ao(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ba=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=po(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=fo(i),v=vo(s),b=fo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[Eo(s)]:function(e){const t=Eo(e);return[Oo(e),t,Oo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=mo(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?xo:To:t?To:xo;case"left":case"right":return t?ko:So;default:return[]}}(fo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(Oo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=wo(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===vo(t)||E.every(e=>vo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=vo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var wa=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=na(e),u=i||o?[...c?Qo(c):[],...t?Qo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=Lo(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-co(h)+"px "+-co(o.clientWidth-(u+p))+"px "+-co(o.clientHeight-(h+d))+"px "+-co(u)+"px",threshold:so(0,ao(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!ma(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=Io(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?aa(e):null;return l&&function t(){const r=aa(e);m&&!ma(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...fa,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Ao},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=Po(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Oa(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ia(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ia(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ai.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ai.session})}},{key:"create",value:(i=Na(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ai.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ai.headers,body:JSON.stringify({session:Ai.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Da(t.prototype,n),r&&Da(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Ba=Fa;function Va(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Va(t.prototype,n),r&&Va(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function qa(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ya(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ka(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ka(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ka(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&qa(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ua);const Za=Xa;var Qa=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},es=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ts=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function ns(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=as(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ai.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),Or(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){U.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ai.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ai.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",Or(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=as(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return wr(e,br)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=as(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ai.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ai.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=as(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ai.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=as(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ai.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=as(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=as(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[ya(this.offsetValue),va({padding:this.paddingValue}),ba()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ys.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ms)}catch(e){return new Intl.DateTimeFormat(void 0,ms)}}}],r&&ss(n.prototype,r),i&&ss(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);vs.messageTimestampFormatters={},vs.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},vs.classes=["fadeOut"],vs.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"];var bs=g.lg.start();bs.register("hellotext--form",Fi),bs.register("hellotext--popup",ro),bs.register("hellotext--webchat",vs),bs.register("hellotext--webchat--emoji",Ma),bs.register("hellotext--message",Gi),window.Hellotext=Ai;const ws=Ai},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c(()=>{"use strict";var e={891(e,t,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class U{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class q{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new U(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 q(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new q(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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>ws});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function q(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=q(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=q(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=q(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=U.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=U,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(Fe({session:Ai.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=qe;function We(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $e(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return et(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ai.headers}),r=yield n.json();return Ai.business.data||(Ai.business.setData(r.business),Ai.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){tt(o,r,i,a,s,"next",e)}function s(e){tt(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&nt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ot=it;function at(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function st(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){at(o,r,i,a,s,"next",e)}function s(e){at(o,r,i,a,s,"throw",e)}a(void 0)})}}function lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ai.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){mt(o,r,i,a,s,"next",e)}function s(e){mt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&yt(e.prototype,null),t&&yt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const bt=vt;function wt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(Pt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(Pt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&Et(e.prototype,t),n&&Et(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return It(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),Mt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(Mt.get("hello_utm"))||{}}catch(e){return{}}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new Dt,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Rt(t.prototype,n),r&&Rt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Vt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Bt;Ut(this,Kt)[Kt]=e,Ut(this,$t)[$t]=new ye,this.session=Ut(this,$t)[$t].session||Z.session||Mt.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Vt(e.prototype,null),t&&Vt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ai.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const sn=Object.entries,ln=Object.setPrototypeOf,cn=Object.isFrozen,un=Object.getPrototypeOf,hn=Object.getOwnPropertyDescriptor;let pn=Object.freeze,dn=Object.seal,fn=Object.create,mn="undefined"!=typeof Reflect&&Reflect,yn=mn.apply,gn=mn.construct;pn||(pn=function(e){return e}),dn||(dn=function(e){return e}),yn||(yn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:kn;if(ln&&ln(e,null),!xn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(cn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function zn(e){for(let t=0;t/g),rr=dn(/\${[\w\W]*/g),ir=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),or=dn(/^aria-[\-\w]+$/),ar=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sr=dn(/^(?:\w+script|data):/i),lr=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cr=dn(/^html$/i),ur=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),hr=dn(/<[/\w!]/g),pr=dn(/<[/\w]/g),dr=dn(/<\/no(script|embed|frames)/i),fr=dn(/\/>/i),mr=function(){return"undefined"==typeof window?null:window},yr=function(e,t,n,r){return Ln(e,t)&&xn(e[t])?Vn(r.base?Un(r.base):{},e[t],r.transform):n};var gr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=qn(p,"cloneNode"),f=qn(p,"remove"),m=qn(p,"nextSibling"),y=qn(p,"childNodes"),g=qn(p,"parentNode"),v=qn(p,"shadowRoot"),b=qn(p,"attributes"),w=s&&s.prototype?qn(s.prototype,"nodeType"):null,O=s&&s.prototype?qn(s.prototype,"nodeName"):null,T=s&&s.prototype?qn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Rn('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof sn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=tr,F=nr,B=rr,V=ir,z=or,U=sr,q=lr,H=ur;let W=ar,$=null;const K=Vn({},[...Hn,...Wn,...$n,...Gn,...Yn]);let G=null;const J=Vn({},[...Xn,...Zn,...Qn,...er]);let Y=Object.seal(fn(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}})),X=null,Z=null;const Q=Object.seal(fn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Vn({},["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 Te=null;const xe=Vn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Vn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Vn({},[Ee,Ce,Pe],Sn),Ie=pn(["mi","mo","mn","ms","mtext"]);let Le=Vn({},Ie);const Ne=pn(["annotation-xml"]);let De=Vn({},Ne);const Re=Vn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const Ue=r.createElement("form"),qe=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Un(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Sn:kn,$=yr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=yr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=yr(e,"ALLOWED_NAMESPACES",Me,{transform:Sn}),ke=yr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=yr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=yr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=yr(e,"FORBID_TAGS",Un({}),{transform:Ve}),Z=yr(e,"FORBID_ATTR",Un({}),{transform:Ve}),be=!!Ln(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Un(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return Dn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:ar,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=Ln(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Un(e.MATHML_TEXT_INTEGRATION_POINTS):Vn({},Ie),De=Ln(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Un(e.HTML_INTEGRATION_POINTS):Vn({},Ne);const t=Ln(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Un(e.CUSTOM_ELEMENT_HANDLING):fn(null);if(Y=fn(null),Ln(t,"tagNameCheck")&&qe(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Ln(t,"attributeNameCheck")&&qe(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Ln(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),dn(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Vn({},Yn),G=fn(null),!0===be.html&&(Vn($,Hn),Vn(G,Xn)),!0===be.svg&&(Vn($,Wn),Vn(G,Zn),Vn(G,er)),!0===be.svgFilters&&(Vn($,$n),Vn(G,Zn),Vn(G,er)),!0===be.mathMl&&(Vn($,Gn),Vn(G,Qn),Vn(G,er))),Q.tagCheck=null,Q.attributeCheck=null,Ln(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:xn(e.ADD_TAGS)&&($===K&&($=Un($)),Vn($,e.ADD_TAGS,Ve))),Ln(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:xn(e.ADD_ATTR)&&(G===J&&(G=Un(G)),Vn(G,e.ADD_ATTR,Ve))),Ln(e,"ADD_URI_SAFE_ATTR")&&xn(e.ADD_URI_SAFE_ATTR)&&Vn(ke,e.ADD_URI_SAFE_ATTR,Ve),Ln(e,"FORBID_CONTENTS")&&xn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.FORBID_CONTENTS,Ve)),Ln(e,"ADD_FORBID_CONTENTS")&&xn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Vn($,["html","head","body"]),$.table&&(Vn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));pn&&pn(e),ze=e},We=Vn({},[...Wn,...$n,...Kn]),$e=Vn({},[...Gn,...Jn]),Ke=function(e){On(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Rn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];vn(t,t=>{On(e,t)}),vn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{On(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){On(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=En(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=Cn(e,R," "),e=Cn(e,F," "),Cn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&vn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&vn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Un(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&Dn(hr,e.textContent)&&Dn(hr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!Dn(pr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=kn(e.tagName),r=kn(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&Dn(dr,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(On(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in Ue))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&Dn(V,t));else if(ee&&Dn(z,t));else if(i){if(ke[t]);else if(Dn(W,Cn(n,q,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Pn(n,"data:")||!Te[e])if(ne&&!Dn(U,Cn(n,q,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Dn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Vn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[kn(e)]&&Dn(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):wn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:An(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Pn(h,ye)||(Je(a,e),h=ye+h),oe&&Dn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&En(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&Dn(fr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return jn(e);case"boolean":return _n(e);case"bigint":return Mn?Mn(e):"0";case"symbol":return In?In(e):"Symbol()";case"undefined":default:return Nn(e);case"function":case"object":{if(null===e)return Nn(e);const t=e,n=qn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Nn(e)}return Nn(e)}}}(e)))throw Rn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Un($)),D.uponSanitizeAttribute.length>0&&(G=Un(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&Dn(pr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Rn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Rn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),vn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return vn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Dn(cr,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ln(D,e)&&On(D[e],t)},n.removeHook=function(e,t){if(Ln(D,e)){if(void 0!==t){const n=bn(D[e],t);return-1===n?void 0:Tn(D[e],n,1)[0]}return wn(D[e])}},n.removeHooks=function(e){Ln(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),vr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},br={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function wr(e,t){var n=gr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function Or(e,t){e.replaceChildren(function(e){return wr(e,vr)}(t))}function Tr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xr(e,t,n){return(t=Er(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Sr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,jr,{value:Mr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ai.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ai.business.features.white_label||this.element.prepend(rn.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){kr(o,r,i,a,s,"next",e)}function s(e){kr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=Cr(this,jr)[jr]("[data-form-header]","header");Or(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=Cr(this,jr)[jr]("[data-form-inputs]","main");e.map(e=>Xt.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)}},{key:"buildButton",value:function(e){var t=Cr(this,jr)[jr]("[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)}},{key:"buildFooter",value:function(e){var t=Cr(this,jr)[jr]("[data-form-footer]","footer");Or(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ai.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Sr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Mr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function Ir(e){var t="function"==typeof Map?new Map:void 0;return Ir=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(Lr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Nr(i,n.prototype),i}(e,arguments,Dr(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Nr(n,e)},Ir(e)}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Lr=function(){return!!e})()}function Nr(e,t){return Nr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Nr(e,t)}function Dr(e){return Dr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Dr(e)}var Rr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Dr(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Lr()?Reflect.construct(t,n||[],Dr(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Ir(Error));function Fr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Br(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ai.notInitialized)throw new Rr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,qr)[qr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ai.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Fr(o,r,i,a,s,"next",e)}function s(e){Fr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ai.business.data||(Ai.business.setData(e.business),Ai.business.setLocale(j.toString())),Ai.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 _r(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Br(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Wr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function $r(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Kr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$r(o,r,i,a,s,"next",e)}function s(e){$r(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gr(e,t){for(var n=0;nyi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=yi(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function gi(e,t){var n=yi(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function vi(){return(vi=pi(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var bi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=pi(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return vi.apply(this,arguments)}(gi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&ui(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function wi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new At(e),this.page=new Bt,Z.assign(t),Gt.initialize(this.page),this.forms=new Hr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Yr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield ti.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ai.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=Ti({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return wi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Si(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Rr;var n=Ti(Ti({},t&&t.headers||{}),this.headers),r=Ti(Ti({},ci.identificationData),t.user_parameters||{}),i=t&&t.url?new Bt(t.url):this.page,o=Ti(Ti({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield xt.events.create({headers:n,body:o,keepalive:Tt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Si(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield bi.generate(this.session,e,n);if(bi.matches(ci.fingerprint,r))return new ke(!0,{json:(t=Si(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield xt.identifications.create(Ti({user_id:e},n));return i.succeeded&&ci.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ci.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Gt.session}},{key:"isInitialized",get:function(){return void 0!==Gt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Rr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&Ei(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Pi.eventEmitter=new ce,Pi.forms=void 0,Pi.business=void 0,Pi.popup=void 0,Pi.webchat=void 0,Pi.whatsapp=void 0;const Ai=Pi;function ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function _i(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ai.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){ji(o,n,r,a,s,"next",e)}function s(e){ji(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ai.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&_i(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Bi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Vi(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Ui(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function Ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Yi(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ji(o,r,i,a,s,"next",e)}function s(e){Ji(o,r,i,a,s,"throw",e)}a(void 0)})}}function Xi(e,t){for(var n=0;n{e.disabled=!0});var t=yield xt.popups.submit(this.idValue,this.submissionPayload());if(this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed)yield this.handleSubmissionError(t);else{try{var n=yield t.json();this.submissionId=n.id,this.submissionVerificationState=n.verification_state,this.submissionActionToken=n.action_token}catch(e){this.submissionId=null}this.showCompleted()}}else this.showErrorMessages(this.currentStepInputs)}),function(e){return s.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.configureCompletionActions(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.completionIdentity;if(e){var t={destination:e.value,channel:e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"configureCompletionActions",value:function(){var e=this.completionIdentity;e&&(this.hasChangeDestinationButtonTarget&&(this.changeDestinationButtonTarget.textContent=this.changeDestinationButtonTarget.dataset["".concat(e.kind,"Label")],this.showElement(this.changeDestinationButtonTarget)),this.submissionId&&this.submissionActionToken&&"unverified"===this.submissionVerificationState&&this.hasResendButtonTarget&&(this.showElement(this.resendButtonTarget),this.startResendCooldown(60)))}},{key:"resend",value:(a=Yi(function*(e){if(e&&e.preventDefault(),this.submissionId&&this.submissionActionToken&&!this.resendPending&&!this.resendCooldownActive){var t=this.completionIdentity;if(t){this.resendPending=!0,this.resendButtonTarget.disabled=!0;try{var n,r=yield xt.popups.resend(this.idValue,this.submissionId,t.kind,this.submissionActionToken),i=Number(null===(n=r.data.headers)||void 0===n?void 0:n.get("Retry-After"))||60;r.succeeded||429===r.data.status?this.startResendCooldown(i):this.resendButtonTarget.disabled=!1}catch(e){this.resendButtonTarget.disabled=!1}finally{this.resendPending=!1}}}}),function(e){return a.apply(this,arguments)})},{key:"changeDestination",value:(o=Yi(function*(e){var t;e&&e.preventDefault();var n=null===(t=this.completionIdentity)||void 0===t?void 0:t.input;if(n){var r=this.stepTargets.findIndex(e=>e.dataset.stepId===n.dataset.popupStepId);if(!(r<0)){this.changeDestinationButtonTarget.disabled=!0;try{if((yield xt.popups.cancel(this.idValue,this.submissionId,this.submissionActionToken)).failed)return}catch(e){return}finally{this.changeDestinationButtonTarget.disabled=!1}this.stopResendCooldown(),this.submissionId=null,this.submissionActionToken=null,this.showStep(r),n.focus()}}}),function(e){return o.apply(this,arguments)})},{key:"startResendCooldown",value:function(e){this.stopResendCooldown(),this.resendCooldownEndsAt=Date.now()+1e3*Math.max(e,1),this.updateResendCountdown(),this.resendTimer=window.setInterval(()=>this.updateResendCountdown(),1e3)}},{key:"stopResendCooldown",value:function(){this.resendTimer&&window.clearInterval(this.resendTimer),this.resendTimer=null,this.resendCooldownEndsAt=null}},{key:"updateResendCountdown",value:function(){var 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);var t="".concat(Math.floor(e/60),":").concat(String(e%60).padStart(2,"0")),n=this.resendButtonTarget.dataset.countdownLabel||"".concat(this.resendLabel," %{time}");this.resendButtonTarget.textContent=n.replace("%{time}",t),this.resendButtonTarget.disabled=!0}},{key:"resendCooldownActive",get:function(){return this.resendCooldownEndsAt>Date.now()}},{key:"completionIdentity",get:function(){return this.identityInputs.map(e=>({input:e,kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value)}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Yi(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Xi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l}(g.xI);ro.targets=["bubble","dialog","step","completed","input","submitButton","resendButton","changeDestinationButton"],ro.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const io=["start","end"],oo=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+io[0],t+"-"+io[1]),[]),ao=Math.min,so=Math.max,lo=Math.round,co=Math.floor,uo=e=>({x:e,y:e}),ho={left:"right",right:"left",bottom:"top",top:"bottom"};function po(e,t){return"function"==typeof e?e(t):e}function fo(e){return e.split("-")[0]}function mo(e){return e.split("-")[1]}function yo(e){return"x"===e?"y":"x"}function go(e){return"y"===e?"height":"width"}function vo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function bo(e){return yo(vo(e))}function wo(e,t,n){void 0===n&&(n=!1);const r=mo(e),i=bo(e),o=go(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Eo(a)),[a,Eo(a)]}function Oo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const To=["left","right"],xo=["right","left"],ko=["top","bottom"],So=["bottom","top"];function Eo(e){const t=fo(e);return ho[t]+e.slice(t.length)}function Co(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Po(e,t,n){let{reference:r,floating:i}=e;const o=vo(t),a=bo(t),s=go(a),l=fo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=mo(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Ao(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=po(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=Co(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Co(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const jo=new Set(["left","top"]);function _o(){return"undefined"!=typeof window}function Mo(e){return No(e)?(e.nodeName||"").toLowerCase():"#document"}function Io(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Lo(e){var t;return null==(t=(No(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function No(e){return!!_o()&&(e instanceof Node||e instanceof Io(e).Node)}function Do(e){return!!_o()&&(e instanceof Element||e instanceof Io(e).Element)}function Ro(e){return!!_o()&&(e instanceof HTMLElement||e instanceof Io(e).HTMLElement)}function Fo(e){return!(!_o()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Io(e).ShadowRoot)}function Bo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Jo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Vo(e){return/^(table|td|th)$/.test(Mo(e))}function zo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Uo=/transform|translate|scale|rotate|perspective|filter/,qo=/paint|layout|strict|content/,Ho=e=>!!e&&"none"!==e;let Wo;function $o(e){const t=Do(e)?Jo(e):e;return Ho(t.transform)||Ho(t.translate)||Ho(t.scale)||Ho(t.rotate)||Ho(t.perspective)||!Ko()&&(Ho(t.backdropFilter)||Ho(t.filter))||Uo.test(t.willChange||"")||qo.test(t.contain||"")}function Ko(){return null==Wo&&(Wo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Wo}function Go(e){return/^(html|body|#document)$/.test(Mo(e))}function Jo(e){return Io(e).getComputedStyle(e)}function Yo(e){return Do(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xo(e){if("html"===Mo(e))return e;const t=e.assignedSlot||e.parentNode||Fo(e)&&e.host||Lo(e);return Fo(t)?t.host:t}function Zo(e){const t=Xo(e);return Go(t)?(e.ownerDocument||e).body:Ro(t)&&Bo(t)?t:Zo(t)}function Qo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Zo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Io(i);if(o){const e=ea(a);return t.concat(a,a.visualViewport||[],Bo(i)?i:[],e&&n?Qo(e):[])}return t.concat(i,Qo(i,[],n))}function ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ta(e){const t=Jo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ro(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=lo(n)!==o||lo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function na(e){return Do(e)?e:e.contextElement}function ra(e){const t=na(e);if(!Ro(t))return uo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=ta(t);let a=(o?lo(n.width):n.width)/r,s=(o?lo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ia=uo(0);function oa(e){const t=Io(e);return Ko()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ia}function aa(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=na(e);let a=uo(1);t&&(r?Do(r)&&(a=ra(r)):a=ra(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===Io(e)}(o,n,r)?oa(o):uo(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=Io(o),t=Do(r)?Io(r):r;let n=e,i=ea(n);for(;i&&t!==n;){const e=ra(i),t=i.getBoundingClientRect(),r=Jo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=Io(i),i=ea(n)}}return Co({width:u,height:h,x:l,y:c})}function sa(e,t){const n=Yo(e).scrollLeft;return t?t.left+n:aa(Lo(e)).left+n}function la(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-sa(e,n),y:n.top+t.scrollTop}}function ca(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=Io(e),o=Lo(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ko()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(sa(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Yo(e),n=e.ownerDocument.body,r=so(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=so(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+sa(e);const a=-t.scrollTop;return"rtl"===Jo(n).direction&&(o+=so(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(Lo(e));else if(Do(t))r=function(e,t){const n=aa(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ra(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=oa(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Co(r)}function ua(e,t,n){const r=Ro(t),i=Lo(t),o="fixed"===n,a=aa(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=uo(0);if((r||!o)&&(("body"!==Mo(t)||Bo(i))&&(s=Yo(t)),r)){const e=aa(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=sa(i));const c=!i||r||o?uo(0):la(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function ha(e){return"static"===Jo(e).position}function pa(e,t){if(!Ro(e)||"fixed"===Jo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Lo(e)===n&&(n=n.ownerDocument.body),n}function da(e,t){const n=Io(e);if(zo(e))return n;if(!Ro(e)){let t=Xo(e);for(;t&&!Go(t);){if(Do(t)&&!ha(t))return t;t=Xo(t)}return n}let r=pa(e,t);for(;r&&Vo(r)&&ha(r);)r=pa(r,t);return r&&Go(r)&&ha(r)&&!$o(r)?n:r||function(e){let t=Xo(e);for(;Ro(t)&&!Go(t);){if($o(t))return t;if(zo(t))return null;t=Xo(t)}return null}(e)||n}const fa={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Lo(r),s=!!t&&zo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=uo(1);const u=uo(0),h=Ro(r);if((h||!o)&&(("body"!==Mo(r)||Bo(a))&&(l=Yo(r)),h)){const e=aa(r);c=ra(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?uo(0):la(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:Lo,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?zo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Qo(e,[],!1).filter(e=>Do(e)&&"body"!==Mo(e)),i=null;const o="fixed"===Jo(e).position;let a=o?Xo(e):e;for(;Do(a)&&!Go(a);){const e=Jo(a),t=$o(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Xo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=ca(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;emo(t)===e),...n.filter(t=>mo(t)!==e)]:n.filter(e=>fo(e)===e)).filter(n=>!e||mo(n)===e||!!t&&Oo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=wo(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[fo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=mo(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,mo(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},va=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=po(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=vo(i),d=yo(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],so(n,ao(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ba=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=po(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=fo(i),v=vo(s),b=fo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[Eo(s)]:function(e){const t=Eo(e);return[Oo(e),t,Oo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=mo(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?xo:To:t?To:xo;case"left":case"right":return t?ko:So;default:return[]}}(fo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(Oo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=wo(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===vo(t)||E.every(e=>vo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=vo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var wa=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=na(e),u=i||o?[...c?Qo(c):[],...t?Qo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=Lo(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-co(h)+"px "+-co(o.clientWidth-(u+p))+"px "+-co(o.clientHeight-(h+d))+"px "+-co(u)+"px",threshold:so(0,ao(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!ma(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=Io(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?aa(e):null;return l&&function t(){const r=aa(e);m&&!ma(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...fa,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Ao},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=Po(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Oa(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ia(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ia(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ai.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ai.session})}},{key:"create",value:(i=Na(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ai.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ai.headers,body:JSON.stringify({session:Ai.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Da(t.prototype,n),r&&Da(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Ba=Fa;function Va(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Va(t.prototype,n),r&&Va(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function qa(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ya(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ka(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ka(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ka(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&qa(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ua);const Za=Xa;var Qa=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},es=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ts=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function ns(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=as(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ai.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),Or(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){U.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ai.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ai.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",Or(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=as(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return wr(e,br)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=as(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ai.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ai.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=as(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ai.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=as(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ai.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=as(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=as(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[ya(this.offsetValue),va({padding:this.paddingValue}),ba()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ys.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ms)}catch(e){return new Intl.DateTimeFormat(void 0,ms)}}}],r&&ss(n.prototype,r),i&&ss(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);vs.messageTimestampFormatters={},vs.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},vs.classes=["fadeOut"],vs.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"];var bs=g.lg.start();bs.register("hellotext--form",Fi),bs.register("hellotext--popup",ro),bs.register("hellotext--webchat",vs),bs.register("hellotext--webchat--emoji",Ma),bs.register("hellotext--message",Gi),window.Hellotext=Ai;const ws=Ai},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n}\n\n.hellotext--popup__completion-footer {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n justify-content: center;\n gap: 0 4px;\n text-align: center;\n}\n\n.hellotext--popup__completion-footer > span,\n.hellotext--popup__completion-action:disabled {\n opacity: 0.5;\n}\n\n.hellotext--popup__completion-action {\n appearance: none;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent;\n color: inherit;\n cursor: pointer;\n font: inherit;\n font-weight: 500;\n line-height: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n\n.hellotext--popup__completion-action:disabled {\n cursor: default;\n text-decoration: none;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c this.hideElement(step)); this.interpolateCompletionCopy(); + this.configureCompletionActions(); this.showElement(this.completedTarget); } }, { key: "interpolateCompletionCopy", value: function interpolateCompletionCopy() { - const identity = this.identityInputs.map(input => ({ - kind: input.dataset.popupFieldKind, - value: this.identityValue(input) - })).find(({ - value - }) => value); + const identity = this.completionIdentity; if (!identity) return; const replacements = { destination: identity.value, @@ -195,6 +201,114 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { const prefix = input.dataset.popupPhonePrefix; return prefix ? `${prefix}${value.replace(/^0+/, '')}` : value; } + }, { + key: "configureCompletionActions", + value: function configureCompletionActions() { + const identity = this.completionIdentity; + if (!identity) return; + if (this.hasChangeDestinationButtonTarget) { + this.changeDestinationButtonTarget.textContent = this.changeDestinationButtonTarget.dataset[`${identity.kind}Label`]; + this.showElement(this.changeDestinationButtonTarget); + } + if (this.submissionId && this.submissionActionToken && this.submissionVerificationState === 'unverified' && this.hasResendButtonTarget) { + this.showElement(this.resendButtonTarget); + this.startResendCooldown(60); + } + } + }, { + key: "resend", + value: async function resend(event) { + if (event) event.preventDefault(); + if (!this.submissionId || !this.submissionActionToken || this.resendPending || this.resendCooldownActive) return; + const identity = this.completionIdentity; + if (!identity) return; + this.resendPending = true; + this.resendButtonTarget.disabled = true; + try { + var _response$data$header; + const response = await _api.default.popups.resend(this.idValue, this.submissionId, identity.kind, this.submissionActionToken); + const retryAfter = Number((_response$data$header = response.data.headers) === null || _response$data$header === void 0 ? void 0 : _response$data$header.get('Retry-After')) || 60; + if (response.succeeded || response.data.status === 429) { + this.startResendCooldown(retryAfter); + } else { + this.resendButtonTarget.disabled = false; + } + } catch (_) { + this.resendButtonTarget.disabled = false; + } finally { + this.resendPending = false; + } + } + }, { + key: "changeDestination", + value: async function changeDestination(event) { + var _this$completionIdent; + if (event) event.preventDefault(); + const input = (_this$completionIdent = this.completionIdentity) === null || _this$completionIdent === void 0 ? void 0 : _this$completionIdent.input; + if (!input) return; + const stepIndex = this.stepTargets.findIndex(step => step.dataset.stepId === input.dataset.popupStepId); + if (stepIndex < 0) return; + this.changeDestinationButtonTarget.disabled = true; + try { + const response = await _api.default.popups.cancel(this.idValue, this.submissionId, this.submissionActionToken); + if (response.failed) return; + } catch (_) { + return; + } finally { + this.changeDestinationButtonTarget.disabled = false; + } + this.stopResendCooldown(); + this.submissionId = null; + this.submissionActionToken = null; + this.showStep(stepIndex); + input.focus(); + } + }, { + key: "startResendCooldown", + value: function startResendCooldown(seconds) { + this.stopResendCooldown(); + this.resendCooldownEndsAt = Date.now() + Math.max(seconds, 1) * 1000; + this.updateResendCountdown(); + this.resendTimer = window.setInterval(() => this.updateResendCountdown(), 1000); + } + }, { + key: "stopResendCooldown", + value: function stopResendCooldown() { + if (this.resendTimer) window.clearInterval(this.resendTimer); + this.resendTimer = null; + this.resendCooldownEndsAt = null; + } + }, { + key: "updateResendCountdown", + value: function updateResendCountdown() { + const seconds = Math.max(0, Math.ceil((this.resendCooldownEndsAt - Date.now()) / 1000)); + if (seconds === 0) { + this.stopResendCooldown(); + this.resendButtonTarget.textContent = this.resendLabel; + this.resendButtonTarget.disabled = false; + return; + } + const time = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; + const template = this.resendButtonTarget.dataset.countdownLabel || `${this.resendLabel} %{time}`; + this.resendButtonTarget.textContent = template.replace('%{time}', time); + this.resendButtonTarget.disabled = true; + } + }, { + key: "resendCooldownActive", + get: function () { + return this.resendCooldownEndsAt > Date.now(); + } + }, { + key: "completionIdentity", + get: function () { + return this.identityInputs.map(input => ({ + input, + kind: input.dataset.popupFieldKind, + value: this.identityValue(input) + })).find(({ + value + }) => value); + } }, { key: "currentStepValid", value: function currentStepValid() { @@ -433,7 +547,7 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { } }]); }(_stimulus.Controller); -_default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton']; +_default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton', 'resendButton', 'changeDestinationButton']; _default.values = { capture: Object, device: String, diff --git a/lib/controllers/popup_controller.js b/lib/controllers/popup_controller.js index 36871efb..8f67d282 100644 --- a/lib/controllers/popup_controller.js +++ b/lib/controllers/popup_controller.js @@ -48,6 +48,7 @@ var _default = /*#__PURE__*/function (_Controller) { value: function connect() { this.stepIndex = 0; this.onScroll = this.evaluateDisplay.bind(this); + this.resendLabel = this.hasResendButtonTarget ? this.resendButtonTarget.textContent.trim() : ''; this.hideElement(this.element); this.hideElement(this.dialogTarget); if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget); @@ -57,6 +58,7 @@ var _default = /*#__PURE__*/function (_Controller) { key: "disconnect", value: function disconnect() { window.removeEventListener('scroll', this.onScroll); + this.stopResendCooldown(); } }, { key: "open", @@ -126,6 +128,14 @@ var _default = /*#__PURE__*/function (_Controller) { yield this.handleSubmissionError(response); return; } + try { + var submission = yield response.json(); + this.submissionId = submission.id; + this.submissionVerificationState = submission.verification_state; + this.submissionActionToken = submission.action_token; + } catch (_) { + this.submissionId = null; + } this.showCompleted(); }); function submit(_x2) { @@ -172,26 +182,21 @@ var _default = /*#__PURE__*/function (_Controller) { value: function showCompleted() { this.stepTargets.forEach(step => this.hideElement(step)); this.interpolateCompletionCopy(); + this.configureCompletionActions(); this.showElement(this.completedTarget); } }, { key: "interpolateCompletionCopy", value: function interpolateCompletionCopy() { - var identity = this.identityInputs.map(input => ({ - kind: input.dataset.popupFieldKind, - value: this.identityValue(input) - })).find(_ref => { - var value = _ref.value; - return value; - }); + var identity = this.completionIdentity; if (!identity) return; var replacements = { destination: identity.value, channel: identity.kind }; - this.completionTextTemplates.forEach(_ref2 => { - var node = _ref2.node, - template = _ref2.template; + this.completionTextTemplates.forEach(_ref => { + var node = _ref.node, + template = _ref.template; node.nodeValue = template.replace(/\{(destination|channel)\}/g, (placeholder, key) => replacements[key] || placeholder); }); } @@ -203,6 +208,127 @@ var _default = /*#__PURE__*/function (_Controller) { var prefix = input.dataset.popupPhonePrefix; return prefix ? "".concat(prefix).concat(value.replace(/^0+/, '')) : value; } + }, { + key: "configureCompletionActions", + value: function configureCompletionActions() { + var identity = this.completionIdentity; + if (!identity) return; + if (this.hasChangeDestinationButtonTarget) { + this.changeDestinationButtonTarget.textContent = this.changeDestinationButtonTarget.dataset["".concat(identity.kind, "Label")]; + this.showElement(this.changeDestinationButtonTarget); + } + if (this.submissionId && this.submissionActionToken && this.submissionVerificationState === 'unverified' && this.hasResendButtonTarget) { + this.showElement(this.resendButtonTarget); + this.startResendCooldown(60); + } + } + }, { + key: "resend", + value: function () { + var _resend = _asyncToGenerator(function* (event) { + if (event) event.preventDefault(); + if (!this.submissionId || !this.submissionActionToken || this.resendPending || this.resendCooldownActive) return; + var identity = this.completionIdentity; + if (!identity) return; + this.resendPending = true; + this.resendButtonTarget.disabled = true; + try { + var _response$data$header; + var response = yield API.popups.resend(this.idValue, this.submissionId, identity.kind, this.submissionActionToken); + var retryAfter = Number((_response$data$header = response.data.headers) === null || _response$data$header === void 0 ? void 0 : _response$data$header.get('Retry-After')) || 60; + if (response.succeeded || response.data.status === 429) { + this.startResendCooldown(retryAfter); + } else { + this.resendButtonTarget.disabled = false; + } + } catch (_) { + this.resendButtonTarget.disabled = false; + } finally { + this.resendPending = false; + } + }); + function resend(_x3) { + return _resend.apply(this, arguments); + } + return resend; + }() + }, { + key: "changeDestination", + value: function () { + var _changeDestination = _asyncToGenerator(function* (event) { + var _this$completionIdent; + if (event) event.preventDefault(); + var input = (_this$completionIdent = this.completionIdentity) === null || _this$completionIdent === void 0 ? void 0 : _this$completionIdent.input; + if (!input) return; + var stepIndex = this.stepTargets.findIndex(step => step.dataset.stepId === input.dataset.popupStepId); + if (stepIndex < 0) return; + this.changeDestinationButtonTarget.disabled = true; + try { + var response = yield API.popups.cancel(this.idValue, this.submissionId, this.submissionActionToken); + if (response.failed) return; + } catch (_) { + return; + } finally { + this.changeDestinationButtonTarget.disabled = false; + } + this.stopResendCooldown(); + this.submissionId = null; + this.submissionActionToken = null; + this.showStep(stepIndex); + input.focus(); + }); + function changeDestination(_x4) { + return _changeDestination.apply(this, arguments); + } + return changeDestination; + }() + }, { + key: "startResendCooldown", + value: function startResendCooldown(seconds) { + this.stopResendCooldown(); + this.resendCooldownEndsAt = Date.now() + Math.max(seconds, 1) * 1000; + this.updateResendCountdown(); + this.resendTimer = window.setInterval(() => this.updateResendCountdown(), 1000); + } + }, { + key: "stopResendCooldown", + value: function stopResendCooldown() { + if (this.resendTimer) window.clearInterval(this.resendTimer); + this.resendTimer = null; + this.resendCooldownEndsAt = null; + } + }, { + key: "updateResendCountdown", + value: function updateResendCountdown() { + var seconds = Math.max(0, Math.ceil((this.resendCooldownEndsAt - Date.now()) / 1000)); + if (seconds === 0) { + this.stopResendCooldown(); + this.resendButtonTarget.textContent = this.resendLabel; + this.resendButtonTarget.disabled = false; + return; + } + var time = "".concat(Math.floor(seconds / 60), ":").concat(String(seconds % 60).padStart(2, '0')); + var template = this.resendButtonTarget.dataset.countdownLabel || "".concat(this.resendLabel, " %{time}"); + this.resendButtonTarget.textContent = template.replace('%{time}', time); + this.resendButtonTarget.disabled = true; + } + }, { + key: "resendCooldownActive", + get: function get() { + return this.resendCooldownEndsAt > Date.now(); + } + }, { + key: "completionIdentity", + get: function get() { + return this.identityInputs.map(input => ({ + input, + kind: input.dataset.popupFieldKind, + value: this.identityValue(input) + })).find(_ref2 => { + var value = _ref2.value; + return value; + }); + } }, { key: "currentStepValid", value: function currentStepValid() { @@ -252,7 +378,7 @@ var _default = /*#__PURE__*/function (_Controller) { }); this.showErrorMessages(this.inputTargets); }); - function handleSubmissionError(_x3) { + function handleSubmissionError(_x5) { return _handleSubmissionError.apply(this, arguments); } return handleSubmissionError; @@ -448,7 +574,7 @@ var _default = /*#__PURE__*/function (_Controller) { } }]); }(Controller); -_default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton']; +_default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton', 'resendButton', 'changeDestinationButton']; _default.values = { capture: Object, device: String, diff --git a/src/api/popups.js b/src/api/popups.js index 2a912388..a9f19933 100644 --- a/src/api/popups.js +++ b/src/api/popups.js @@ -47,6 +47,26 @@ class PopupsAPI { return new Response(response.ok, response) } + static async resend(id, submissionId, identity, token) { + const response = await fetch(`${this.endpoint}/${id}/submissions/${submissionId}/resend`, { + method: 'POST', + headers: Hellotext.headers, + body: JSON.stringify({ identity, token }), + }) + + return new Response(response.ok, response) + } + + static async cancel(id, submissionId, token) { + const response = await fetch(`${this.endpoint}/${id}/submissions/${submissionId}/cancel`, { + method: 'POST', + headers: Hellotext.headers, + body: JSON.stringify({ token }), + }) + + return new Response(response.ok, response) + } + static idempotencyKey() { if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { return crypto.randomUUID() diff --git a/src/controllers/popup_controller.js b/src/controllers/popup_controller.js index a4ade526..973d2c38 100644 --- a/src/controllers/popup_controller.js +++ b/src/controllers/popup_controller.js @@ -25,7 +25,16 @@ import API from '../api' * - rules: Persisted AND display rules. */ export default class extends Controller { - static targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton'] + static targets = [ + 'bubble', + 'dialog', + 'step', + 'completed', + 'input', + 'submitButton', + 'resendButton', + 'changeDestinationButton', + ] static values = { capture: Object, device: String, @@ -37,6 +46,7 @@ export default class extends Controller { connect() { this.stepIndex = 0 this.onScroll = this.evaluateDisplay.bind(this) + this.resendLabel = this.hasResendButtonTarget ? this.resendButtonTarget.textContent.trim() : '' this.hideElement(this.element) this.hideElement(this.dialogTarget) @@ -47,6 +57,7 @@ export default class extends Controller { disconnect() { window.removeEventListener('scroll', this.onScroll) + this.stopResendCooldown() } open(event) { @@ -122,6 +133,15 @@ export default class extends Controller { return } + try { + const submission = await response.json() + this.submissionId = submission.id + this.submissionVerificationState = submission.verification_state + this.submissionActionToken = submission.action_token + } catch (_) { + this.submissionId = null + } + this.showCompleted() } @@ -163,14 +183,12 @@ export default class extends Controller { showCompleted() { this.stepTargets.forEach(step => this.hideElement(step)) this.interpolateCompletionCopy() + this.configureCompletionActions() this.showElement(this.completedTarget) } interpolateCompletionCopy() { - const identity = this.identityInputs.map(input => ({ - kind: input.dataset.popupFieldKind, - value: this.identityValue(input), - })).find(({ value }) => value) + const identity = this.completionIdentity if (!identity) return @@ -196,6 +214,130 @@ export default class extends Controller { return prefix ? `${prefix}${value.replace(/^0+/, '')}` : value } + configureCompletionActions() { + const identity = this.completionIdentity + if (!identity) return + + if (this.hasChangeDestinationButtonTarget) { + this.changeDestinationButtonTarget.textContent = + this.changeDestinationButtonTarget.dataset[`${identity.kind}Label`] + this.showElement(this.changeDestinationButtonTarget) + } + + if ( + this.submissionId && + this.submissionActionToken && + this.submissionVerificationState === 'unverified' && + this.hasResendButtonTarget + ) { + this.showElement(this.resendButtonTarget) + this.startResendCooldown(60) + } + } + + async resend(event) { + if (event) event.preventDefault() + if (!this.submissionId || !this.submissionActionToken || this.resendPending || this.resendCooldownActive) return + + const identity = this.completionIdentity + if (!identity) return + + this.resendPending = true + this.resendButtonTarget.disabled = true + + try { + const response = await API.popups.resend( + this.idValue, + this.submissionId, + identity.kind, + this.submissionActionToken, + ) + const retryAfter = Number(response.data.headers?.get('Retry-After')) || 60 + + if (response.succeeded || response.data.status === 429) { + this.startResendCooldown(retryAfter) + } else { + this.resendButtonTarget.disabled = false + } + } catch (_) { + this.resendButtonTarget.disabled = false + } finally { + this.resendPending = false + } + } + + async changeDestination(event) { + if (event) event.preventDefault() + + const input = this.completionIdentity?.input + if (!input) return + + const stepIndex = this.stepTargets.findIndex(step => step.dataset.stepId === input.dataset.popupStepId) + if (stepIndex < 0) return + + this.changeDestinationButtonTarget.disabled = true + + try { + const response = await API.popups.cancel( + this.idValue, + this.submissionId, + this.submissionActionToken, + ) + if (response.failed) return + } catch (_) { + return + } finally { + this.changeDestinationButtonTarget.disabled = false + } + + this.stopResendCooldown() + this.submissionId = null + this.submissionActionToken = null + this.showStep(stepIndex) + input.focus() + } + + startResendCooldown(seconds) { + this.stopResendCooldown() + this.resendCooldownEndsAt = Date.now() + Math.max(seconds, 1) * 1000 + this.updateResendCountdown() + this.resendTimer = window.setInterval(() => this.updateResendCountdown(), 1000) + } + + stopResendCooldown() { + if (this.resendTimer) window.clearInterval(this.resendTimer) + this.resendTimer = null + this.resendCooldownEndsAt = null + } + + updateResendCountdown() { + const seconds = Math.max(0, Math.ceil((this.resendCooldownEndsAt - Date.now()) / 1000)) + + if (seconds === 0) { + this.stopResendCooldown() + this.resendButtonTarget.textContent = this.resendLabel + this.resendButtonTarget.disabled = false + return + } + + const time = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}` + const template = this.resendButtonTarget.dataset.countdownLabel || `${this.resendLabel} %{time}` + this.resendButtonTarget.textContent = template.replace('%{time}', time) + this.resendButtonTarget.disabled = true + } + + get resendCooldownActive() { + return this.resendCooldownEndsAt > Date.now() + } + + get completionIdentity() { + return this.identityInputs.map(input => ({ + input, + kind: input.dataset.popupFieldKind, + value: this.identityValue(input), + })).find(({ value }) => value) + } + currentStepValid() { return this.currentStepInputs.every(input => input.checkValidity()) } From 6aa0f93043343328492255d79cdb82e9eb8c0b0f Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Thu, 27 Aug 2026 19:05:07 -0400 Subject: [PATCH 08/11] popups: sync runtime delivery state --- __tests__/api/popups_test.js | 6 +- .../controllers/popup_controller_test.js | 64 +++++++++++++++++- dist/hellotext.js | 2 +- lib/api/popups.cjs | 3 +- lib/api/popups.js | 11 ++- lib/controllers/popup_controller.cjs | 67 ++++++++++++++----- lib/controllers/popup_controller.js | 67 ++++++++++++++----- src/api/popups.js | 4 +- src/controllers/popup_controller.js | 67 +++++++++++++------ 9 files changed, 220 insertions(+), 71 deletions(-) diff --git a/__tests__/api/popups_test.js b/__tests__/api/popups_test.js index 82918ce3..d252dfeb 100644 --- a/__tests__/api/popups_test.js +++ b/__tests__/api/popups_test.js @@ -127,8 +127,8 @@ describe('PopupsAPI', () => { expect(keys[0]).not.toBe(keys[1]) }) - it('resends verification for the selected popup identity', async () => { - const response = await PopupsAPI.resend('popup-id', 'submission-id', 'email', 'action-token') + it('resends verification through the route stored by the backend', async () => { + const response = await PopupsAPI.resend('popup-id', 'submission-id', 'action-token') const request = global.fetch.mock.calls[0] expect(request[0]).toBe( @@ -137,7 +137,7 @@ describe('PopupsAPI', () => { expect(request[1]).toEqual({ method: 'POST', headers: Hellotext.headers, - body: JSON.stringify({ identity: 'email', token: 'action-token' }), + body: JSON.stringify({ token: 'action-token' }), }) expect(response.succeeded).toBe(true) }) diff --git a/__tests__/controllers/popup_controller_test.js b/__tests__/controllers/popup_controller_test.js index ff60fb11..0857e2ec 100644 --- a/__tests__/controllers/popup_controller_test.js +++ b/__tests__/controllers/popup_controller_test.js @@ -106,6 +106,9 @@ describe('PopupController', () => { id: 'submission-id', verification_state: 'unverified', action_token: 'action-token', + delivery_status: 'queued', + delivery_channel: 'email', + destination: 'customer@example.com', }), }) jest.spyOn(API.popups, 'resend').mockResolvedValue({ @@ -265,7 +268,6 @@ describe('PopupController', () => { expect(API.popups.resend).toHaveBeenCalledWith( 'popup-id', 'submission-id', - 'email', 'action-token', ) expect(resendButton.disabled).toBe(true) @@ -283,11 +285,30 @@ describe('PopupController', () => { await controller.submit() await controller.changeDestination({ preventDefault: jest.fn() }) - expect(API.popups.cancel).toHaveBeenCalledWith('popup-id', 'submission-id', 'action-token') + expect(API.popups.cancel).not.toHaveBeenCalled() expect(completed.hidden).toBe(true) expect(stepOne.hidden).toBe(false) expect(emailInput.focus).toHaveBeenCalled() expect(changeDestinationButton.textContent).toBe('Change email') + expect(controller.submissionDeliveryStatus).toBeNull() + expect(controller.submissionDeliveryChannel).toBeNull() + expect(controller.submissionDestination).toBeNull() + }) + + it('returns to the identity selected by the backend fallback route', async () => { + const { emailInput, phoneInput, stepOne } = buildController({ hasBubble: false }) + jest.spyOn(emailInput, 'focus') + controller.inputTargets = [phoneInput, emailInput] + controller.submissionDeliveryChannel = 'email' + controller.submissionDestination = 'customer@example.com' + emailInput.value = 'customer@example.com' + phoneInput.value = '+15551234567' + + controller.showCompleted() + await controller.changeDestination({ preventDefault: jest.fn() }) + + expect(stepOne.hidden).toBe(false) + expect(emailInput.focus).toHaveBeenCalled() }) it('uses a readable channel when the popup only requires one identity field', () => { @@ -338,6 +359,45 @@ describe('PopupController', () => { ) }) + it('uses the backend delivery channel and destination in the completed step', () => { + const { completed, emailInput, phoneInput } = buildController({ hasBubble: false }) + + emailInput.value = 'customer@example.com' + phoneInput.value = '+15551234567' + controller.submissionDeliveryChannel = 'sms' + controller.submissionDestination = '+15551234567' + + controller.showCompleted() + + expect(completed.querySelector('p').textContent).toBe( + 'We sent it to +15551234567 via sms. It may take a minute to arrive.', + ) + }) + + it('shows contact-only completion copy and no delivery actions when delivery is not required', () => { + const { completed, emailInput, resendButton, changeDestinationButton } = buildController({ hasBubble: false }) + const headline = document.createElement('header') + const description = document.createElement('div') + const actions = document.createElement('footer') + + emailInput.value = 'customer@example.com' + headline.className = 'hellotext--popup__completion-headline' + description.className = 'hellotext--popup__completion-description' + actions.dataset.deliveryActions = '' + completed.dataset.notRequiredHeadline = 'Thanks for signing up' + completed.dataset.notRequiredDescription = 'Your details were saved.' + completed.append(headline, description, actions) + controller.submissionDeliveryStatus = 'not_required' + + controller.showCompleted() + + expect(headline.textContent).toBe('Thanks for signing up') + expect(description.textContent).toBe('Your details were saved.') + expect(actions.hidden).toBe(true) + expect(resendButton.hidden).toBe(true) + expect(changeDestinationButton.hidden).toBe(true) + }) + it('validates the last step before submitting', async () => { const { completed, emailInput, phoneInput, stepTwo } = buildController({ hasBubble: false }) diff --git a/dist/hellotext.js b/dist/hellotext.js index fd25fa43..ac4e3451 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,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class U{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class q{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new U(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 q(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new T,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new q(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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>ws});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function q(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=q(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=q(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=q(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=U.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=U,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(Fe({session:Ai.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=qe;function We(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $e(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return et(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ai.headers}),r=yield n.json();return Ai.business.data||(Ai.business.setData(r.business),Ai.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){tt(o,r,i,a,s,"next",e)}function s(e){tt(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&nt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ot=it;function at(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function st(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){at(o,r,i,a,s,"next",e)}function s(e){at(o,r,i,a,s,"throw",e)}a(void 0)})}}function lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ai.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){mt(o,r,i,a,s,"next",e)}function s(e){mt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&yt(e.prototype,null),t&&yt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const bt=vt;function wt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(Pt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(Pt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&Et(e.prototype,t),n&&Et(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return It(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),Mt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(Mt.get("hello_utm"))||{}}catch(e){return{}}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new Dt,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Rt(t.prototype,n),r&&Rt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Vt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Bt;Ut(this,Kt)[Kt]=e,Ut(this,$t)[$t]=new ye,this.session=Ut(this,$t)[$t].session||Z.session||Mt.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Vt(e.prototype,null),t&&Vt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ai.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const sn=Object.entries,ln=Object.setPrototypeOf,cn=Object.isFrozen,un=Object.getPrototypeOf,hn=Object.getOwnPropertyDescriptor;let pn=Object.freeze,dn=Object.seal,fn=Object.create,mn="undefined"!=typeof Reflect&&Reflect,yn=mn.apply,gn=mn.construct;pn||(pn=function(e){return e}),dn||(dn=function(e){return e}),yn||(yn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:kn;if(ln&&ln(e,null),!xn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(cn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function zn(e){for(let t=0;t/g),rr=dn(/\${[\w\W]*/g),ir=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),or=dn(/^aria-[\-\w]+$/),ar=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sr=dn(/^(?:\w+script|data):/i),lr=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cr=dn(/^html$/i),ur=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),hr=dn(/<[/\w!]/g),pr=dn(/<[/\w]/g),dr=dn(/<\/no(script|embed|frames)/i),fr=dn(/\/>/i),mr=function(){return"undefined"==typeof window?null:window},yr=function(e,t,n,r){return Ln(e,t)&&xn(e[t])?Vn(r.base?Un(r.base):{},e[t],r.transform):n};var gr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=qn(p,"cloneNode"),f=qn(p,"remove"),m=qn(p,"nextSibling"),y=qn(p,"childNodes"),g=qn(p,"parentNode"),v=qn(p,"shadowRoot"),b=qn(p,"attributes"),w=s&&s.prototype?qn(s.prototype,"nodeType"):null,O=s&&s.prototype?qn(s.prototype,"nodeName"):null,T=s&&s.prototype?qn(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Rn('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof sn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=tr,F=nr,B=rr,V=ir,z=or,U=sr,q=lr,H=ur;let W=ar,$=null;const K=Vn({},[...Hn,...Wn,...$n,...Gn,...Yn]);let G=null;const J=Vn({},[...Xn,...Zn,...Qn,...er]);let Y=Object.seal(fn(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}})),X=null,Z=null;const Q=Object.seal(fn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Vn({},["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 Te=null;const xe=Vn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Vn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Vn({},[Ee,Ce,Pe],Sn),Ie=pn(["mi","mo","mn","ms","mtext"]);let Le=Vn({},Ie);const Ne=pn(["annotation-xml"]);let De=Vn({},Ne);const Re=Vn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const Ue=r.createElement("form"),qe=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=Un(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Sn:kn,$=yr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=yr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=yr(e,"ALLOWED_NAMESPACES",Me,{transform:Sn}),ke=yr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Te=yr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=yr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=yr(e,"FORBID_TAGS",Un({}),{transform:Ve}),Z=yr(e,"FORBID_ATTR",Un({}),{transform:Ve}),be=!!Ln(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Un(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return Dn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:ar,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=Ln(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Un(e.MATHML_TEXT_INTEGRATION_POINTS):Vn({},Ie),De=Ln(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Un(e.HTML_INTEGRATION_POINTS):Vn({},Ne);const t=Ln(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Un(e.CUSTOM_ELEMENT_HANDLING):fn(null);if(Y=fn(null),Ln(t,"tagNameCheck")&&qe(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Ln(t,"attributeNameCheck")&&qe(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Ln(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),dn(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Vn({},Yn),G=fn(null),!0===be.html&&(Vn($,Hn),Vn(G,Xn)),!0===be.svg&&(Vn($,Wn),Vn(G,Zn),Vn(G,er)),!0===be.svgFilters&&(Vn($,$n),Vn(G,Zn),Vn(G,er)),!0===be.mathMl&&(Vn($,Gn),Vn(G,Qn),Vn(G,er))),Q.tagCheck=null,Q.attributeCheck=null,Ln(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:xn(e.ADD_TAGS)&&($===K&&($=Un($)),Vn($,e.ADD_TAGS,Ve))),Ln(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:xn(e.ADD_ATTR)&&(G===J&&(G=Un(G)),Vn(G,e.ADD_ATTR,Ve))),Ln(e,"ADD_URI_SAFE_ATTR")&&xn(e.ADD_URI_SAFE_ATTR)&&Vn(ke,e.ADD_URI_SAFE_ATTR,Ve),Ln(e,"FORBID_CONTENTS")&&xn(e.FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.FORBID_CONTENTS,Ve)),Ln(e,"ADD_FORBID_CONTENTS")&&xn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=Un(we)),Vn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Vn($,["html","head","body"]),$.table&&(Vn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));pn&&pn(e),ze=e},We=Vn({},[...Wn,...$n,...Kn]),$e=Vn({},[...Gn,...Jn]),Ke=function(e){On(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Rn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];vn(t,t=>{On(e,t)}),vn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{On(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){On(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=En(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=Cn(e,R," "),e=Cn(e,F," "),Cn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&vn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&vn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?Un(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&Dn(hr,e.textContent)&&Dn(hr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!Dn(pr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=kn(e.tagName),r=kn(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&Dn(dr,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(On(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in Ue))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&Dn(V,t));else if(ee&&Dn(z,t));else if(i){if(ke[t]);else if(Dn(W,Cn(n,q,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Pn(n,"data:")||!Te[e])if(ne&&!Dn(U,Cn(n,q,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Dn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Vn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[kn(e)]&&Dn(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):wn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:An(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Pn(h,ye)||(Je(a,e),h=ye+h),oe&&Dn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&En(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&Dn(fr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return jn(e);case"boolean":return _n(e);case"bigint":return Mn?Mn(e):"0";case"symbol":return In?In(e):"Symbol()";case"undefined":default:return Nn(e);case"function":case"object":{if(null===e)return Nn(e);const t=e,n=qn(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Nn(e)}return Nn(e)}}}(e)))throw Rn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=Un($)),D.uponSanitizeAttribute.length>0&&(G=Un(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&Dn(pr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Rn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Rn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),vn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return vn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Dn(cr,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){ze||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ln(D,e)&&On(D[e],t)},n.removeHook=function(e,t){if(Ln(D,e)){if(void 0!==t){const n=bn(D[e],t);return-1===n?void 0:Tn(D[e],n,1)[0]}return wn(D[e])}},n.removeHooks=function(e){Ln(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),vr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},br={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function wr(e,t){var n=gr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function Or(e,t){e.replaceChildren(function(e){return wr(e,vr)}(t))}function Tr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xr(e,t,n){return(t=Er(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Sr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,jr,{value:Mr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ai.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ai.business.features.white_label||this.element.prepend(rn.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){kr(o,r,i,a,s,"next",e)}function s(e){kr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=Cr(this,jr)[jr]("[data-form-header]","header");Or(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=Cr(this,jr)[jr]("[data-form-inputs]","main");e.map(e=>Xt.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)}},{key:"buildButton",value:function(e){var t=Cr(this,jr)[jr]("[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)}},{key:"buildFooter",value:function(e){var t=Cr(this,jr)[jr]("[data-form-footer]","footer");Or(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ai.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Sr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Mr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function Ir(e){var t="function"==typeof Map?new Map:void 0;return Ir=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(Lr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Nr(i,n.prototype),i}(e,arguments,Dr(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Nr(n,e)},Ir(e)}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Lr=function(){return!!e})()}function Nr(e,t){return Nr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Nr(e,t)}function Dr(e){return Dr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Dr(e)}var Rr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Dr(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Lr()?Reflect.construct(t,n||[],Dr(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Ir(Error));function Fr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Br(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ai.notInitialized)throw new Rr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,qr)[qr];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ai.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Fr(o,r,i,a,s,"next",e)}function s(e){Fr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ai.business.data||(Ai.business.setData(e.business),Ai.business.setLocale(j.toString())),Ai.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 _r(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Br(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Wr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function $r(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Kr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$r(o,r,i,a,s,"next",e)}function s(e){$r(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gr(e,t){for(var n=0;nyi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=yi(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function gi(e,t){var n=yi(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function vi(){return(vi=pi(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var bi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=pi(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return vi.apply(this,arguments)}(gi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&ui(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function wi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new At(e),this.page=new Bt,Z.assign(t),Gt.initialize(this.page),this.forms=new Hr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Yr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield ti.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ai.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=Ti({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return wi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Si(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Rr;var n=Ti(Ti({},t&&t.headers||{}),this.headers),r=Ti(Ti({},ci.identificationData),t.user_parameters||{}),i=t&&t.url?new Bt(t.url):this.page,o=Ti(Ti({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield xt.events.create({headers:n,body:o,keepalive:Tt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Si(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield bi.generate(this.session,e,n);if(bi.matches(ci.fingerprint,r))return new ke(!0,{json:(t=Si(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield xt.identifications.create(Ti({user_id:e},n));return i.succeeded&&ci.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ci.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Gt.session}},{key:"isInitialized",get:function(){return void 0!==Gt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Rr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&Ei(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Pi.eventEmitter=new ce,Pi.forms=void 0,Pi.business=void 0,Pi.popup=void 0,Pi.webchat=void 0,Pi.whatsapp=void 0;const Ai=Pi;function ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function _i(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ai.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){ji(o,n,r,a,s,"next",e)}function s(e){ji(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ai.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&_i(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Bi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Vi(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Ui(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function Ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Yi(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ji(o,r,i,a,s,"next",e)}function s(e){Ji(o,r,i,a,s,"throw",e)}a(void 0)})}}function Xi(e,t){for(var n=0;n{e.disabled=!0});var t=yield xt.popups.submit(this.idValue,this.submissionPayload());if(this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed)yield this.handleSubmissionError(t);else{try{var n=yield t.json();this.submissionId=n.id,this.submissionVerificationState=n.verification_state,this.submissionActionToken=n.action_token}catch(e){this.submissionId=null}this.showCompleted()}}else this.showErrorMessages(this.currentStepInputs)}),function(e){return s.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.configureCompletionActions(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.completionIdentity;if(e){var t={destination:e.value,channel:e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"configureCompletionActions",value:function(){var e=this.completionIdentity;e&&(this.hasChangeDestinationButtonTarget&&(this.changeDestinationButtonTarget.textContent=this.changeDestinationButtonTarget.dataset["".concat(e.kind,"Label")],this.showElement(this.changeDestinationButtonTarget)),this.submissionId&&this.submissionActionToken&&"unverified"===this.submissionVerificationState&&this.hasResendButtonTarget&&(this.showElement(this.resendButtonTarget),this.startResendCooldown(60)))}},{key:"resend",value:(a=Yi(function*(e){if(e&&e.preventDefault(),this.submissionId&&this.submissionActionToken&&!this.resendPending&&!this.resendCooldownActive){var t=this.completionIdentity;if(t){this.resendPending=!0,this.resendButtonTarget.disabled=!0;try{var n,r=yield xt.popups.resend(this.idValue,this.submissionId,t.kind,this.submissionActionToken),i=Number(null===(n=r.data.headers)||void 0===n?void 0:n.get("Retry-After"))||60;r.succeeded||429===r.data.status?this.startResendCooldown(i):this.resendButtonTarget.disabled=!1}catch(e){this.resendButtonTarget.disabled=!1}finally{this.resendPending=!1}}}}),function(e){return a.apply(this,arguments)})},{key:"changeDestination",value:(o=Yi(function*(e){var t;e&&e.preventDefault();var n=null===(t=this.completionIdentity)||void 0===t?void 0:t.input;if(n){var r=this.stepTargets.findIndex(e=>e.dataset.stepId===n.dataset.popupStepId);if(!(r<0)){this.changeDestinationButtonTarget.disabled=!0;try{if((yield xt.popups.cancel(this.idValue,this.submissionId,this.submissionActionToken)).failed)return}catch(e){return}finally{this.changeDestinationButtonTarget.disabled=!1}this.stopResendCooldown(),this.submissionId=null,this.submissionActionToken=null,this.showStep(r),n.focus()}}}),function(e){return o.apply(this,arguments)})},{key:"startResendCooldown",value:function(e){this.stopResendCooldown(),this.resendCooldownEndsAt=Date.now()+1e3*Math.max(e,1),this.updateResendCountdown(),this.resendTimer=window.setInterval(()=>this.updateResendCountdown(),1e3)}},{key:"stopResendCooldown",value:function(){this.resendTimer&&window.clearInterval(this.resendTimer),this.resendTimer=null,this.resendCooldownEndsAt=null}},{key:"updateResendCountdown",value:function(){var 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);var t="".concat(Math.floor(e/60),":").concat(String(e%60).padStart(2,"0")),n=this.resendButtonTarget.dataset.countdownLabel||"".concat(this.resendLabel," %{time}");this.resendButtonTarget.textContent=n.replace("%{time}",t),this.resendButtonTarget.disabled=!0}},{key:"resendCooldownActive",get:function(){return this.resendCooldownEndsAt>Date.now()}},{key:"completionIdentity",get:function(){return this.identityInputs.map(e=>({input:e,kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value)}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Yi(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Xi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l}(g.xI);ro.targets=["bubble","dialog","step","completed","input","submitButton","resendButton","changeDestinationButton"],ro.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const io=["start","end"],oo=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+io[0],t+"-"+io[1]),[]),ao=Math.min,so=Math.max,lo=Math.round,co=Math.floor,uo=e=>({x:e,y:e}),ho={left:"right",right:"left",bottom:"top",top:"bottom"};function po(e,t){return"function"==typeof e?e(t):e}function fo(e){return e.split("-")[0]}function mo(e){return e.split("-")[1]}function yo(e){return"x"===e?"y":"x"}function go(e){return"y"===e?"height":"width"}function vo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function bo(e){return yo(vo(e))}function wo(e,t,n){void 0===n&&(n=!1);const r=mo(e),i=bo(e),o=go(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Eo(a)),[a,Eo(a)]}function Oo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const To=["left","right"],xo=["right","left"],ko=["top","bottom"],So=["bottom","top"];function Eo(e){const t=fo(e);return ho[t]+e.slice(t.length)}function Co(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Po(e,t,n){let{reference:r,floating:i}=e;const o=vo(t),a=bo(t),s=go(a),l=fo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=mo(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Ao(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=po(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=Co(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Co(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const jo=new Set(["left","top"]);function _o(){return"undefined"!=typeof window}function Mo(e){return No(e)?(e.nodeName||"").toLowerCase():"#document"}function Io(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Lo(e){var t;return null==(t=(No(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function No(e){return!!_o()&&(e instanceof Node||e instanceof Io(e).Node)}function Do(e){return!!_o()&&(e instanceof Element||e instanceof Io(e).Element)}function Ro(e){return!!_o()&&(e instanceof HTMLElement||e instanceof Io(e).HTMLElement)}function Fo(e){return!(!_o()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Io(e).ShadowRoot)}function Bo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Jo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Vo(e){return/^(table|td|th)$/.test(Mo(e))}function zo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Uo=/transform|translate|scale|rotate|perspective|filter/,qo=/paint|layout|strict|content/,Ho=e=>!!e&&"none"!==e;let Wo;function $o(e){const t=Do(e)?Jo(e):e;return Ho(t.transform)||Ho(t.translate)||Ho(t.scale)||Ho(t.rotate)||Ho(t.perspective)||!Ko()&&(Ho(t.backdropFilter)||Ho(t.filter))||Uo.test(t.willChange||"")||qo.test(t.contain||"")}function Ko(){return null==Wo&&(Wo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Wo}function Go(e){return/^(html|body|#document)$/.test(Mo(e))}function Jo(e){return Io(e).getComputedStyle(e)}function Yo(e){return Do(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xo(e){if("html"===Mo(e))return e;const t=e.assignedSlot||e.parentNode||Fo(e)&&e.host||Lo(e);return Fo(t)?t.host:t}function Zo(e){const t=Xo(e);return Go(t)?(e.ownerDocument||e).body:Ro(t)&&Bo(t)?t:Zo(t)}function Qo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Zo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Io(i);if(o){const e=ea(a);return t.concat(a,a.visualViewport||[],Bo(i)?i:[],e&&n?Qo(e):[])}return t.concat(i,Qo(i,[],n))}function ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ta(e){const t=Jo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ro(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=lo(n)!==o||lo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function na(e){return Do(e)?e:e.contextElement}function ra(e){const t=na(e);if(!Ro(t))return uo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=ta(t);let a=(o?lo(n.width):n.width)/r,s=(o?lo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ia=uo(0);function oa(e){const t=Io(e);return Ko()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ia}function aa(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=na(e);let a=uo(1);t&&(r?Do(r)&&(a=ra(r)):a=ra(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===Io(e)}(o,n,r)?oa(o):uo(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=Io(o),t=Do(r)?Io(r):r;let n=e,i=ea(n);for(;i&&t!==n;){const e=ra(i),t=i.getBoundingClientRect(),r=Jo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=Io(i),i=ea(n)}}return Co({width:u,height:h,x:l,y:c})}function sa(e,t){const n=Yo(e).scrollLeft;return t?t.left+n:aa(Lo(e)).left+n}function la(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-sa(e,n),y:n.top+t.scrollTop}}function ca(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=Io(e),o=Lo(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ko()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(sa(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Yo(e),n=e.ownerDocument.body,r=so(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=so(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+sa(e);const a=-t.scrollTop;return"rtl"===Jo(n).direction&&(o+=so(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(Lo(e));else if(Do(t))r=function(e,t){const n=aa(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ra(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=oa(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Co(r)}function ua(e,t,n){const r=Ro(t),i=Lo(t),o="fixed"===n,a=aa(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=uo(0);if((r||!o)&&(("body"!==Mo(t)||Bo(i))&&(s=Yo(t)),r)){const e=aa(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=sa(i));const c=!i||r||o?uo(0):la(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function ha(e){return"static"===Jo(e).position}function pa(e,t){if(!Ro(e)||"fixed"===Jo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Lo(e)===n&&(n=n.ownerDocument.body),n}function da(e,t){const n=Io(e);if(zo(e))return n;if(!Ro(e)){let t=Xo(e);for(;t&&!Go(t);){if(Do(t)&&!ha(t))return t;t=Xo(t)}return n}let r=pa(e,t);for(;r&&Vo(r)&&ha(r);)r=pa(r,t);return r&&Go(r)&&ha(r)&&!$o(r)?n:r||function(e){let t=Xo(e);for(;Ro(t)&&!Go(t);){if($o(t))return t;if(zo(t))return null;t=Xo(t)}return null}(e)||n}const fa={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Lo(r),s=!!t&&zo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=uo(1);const u=uo(0),h=Ro(r);if((h||!o)&&(("body"!==Mo(r)||Bo(a))&&(l=Yo(r)),h)){const e=aa(r);c=ra(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?uo(0):la(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:Lo,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?zo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Qo(e,[],!1).filter(e=>Do(e)&&"body"!==Mo(e)),i=null;const o="fixed"===Jo(e).position;let a=o?Xo(e):e;for(;Do(a)&&!Go(a);){const e=Jo(a),t=$o(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Xo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=ca(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;emo(t)===e),...n.filter(t=>mo(t)!==e)]:n.filter(e=>fo(e)===e)).filter(n=>!e||mo(n)===e||!!t&&Oo(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=wo(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[fo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=mo(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,mo(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:O},reset:{placement:k}}:{}}}},va=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=po(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=vo(i),d=yo(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],so(n,ao(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ba=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=po(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=fo(i),v=vo(s),b=fo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[Eo(s)]:function(e){const t=Eo(e);return[Oo(e),t,Oo(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=mo(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?xo:To:t?To:xo;case"left":case"right":return t?ko:So;default:return[]}}(fo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(Oo)))),o}(s,m,f,w));const x=[s,...O],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=wo(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===vo(t)||E.every(e=>vo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=vo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var wa=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=na(e),u=i||o?[...c?Qo(c):[],...t?Qo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=Lo(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-co(h)+"px "+-co(o.clientWidth-(u+p))+"px "+-co(o.clientHeight-(h+d))+"px "+-co(u)+"px",threshold:so(0,ao(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!ma(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=Io(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?aa(e):null;return l&&function t(){const r=aa(e);m&&!ma(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...fa,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Ao},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=Po(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Oa(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ia(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ia(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ai.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ai.session})}},{key:"create",value:(i=Na(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ai.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ai.headers,body:JSON.stringify({session:Ai.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Da(t.prototype,n),r&&Da(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Ba=Fa;function Va(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Va(t.prototype,n),r&&Va(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function qa(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ya(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ka(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ka(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ka(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&qa(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ua);const Za=Xa;var Qa=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},es=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ts=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function ns(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=as(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ai.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),Or(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){U.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ai.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ai.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",Or(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=as(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return wr(e,br)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=as(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ai.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ai.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=as(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ai.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=as(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ai.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=as(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=as(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[ya(this.offsetValue),va({padding:this.paddingValue}),ba()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ys.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ms)}catch(e){return new Intl.DateTimeFormat(void 0,ms)}}}],r&&ss(n.prototype,r),i&&ss(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);vs.messageTimestampFormatters={},vs.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},vs.classes=["fadeOut"],vs.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"];var bs=g.lg.start();bs.register("hellotext--form",Fi),bs.register("hellotext--popup",ro),bs.register("hellotext--webchat",vs),bs.register("hellotext--webchat--emoji",Ma),bs.register("hellotext--message",Gi),window.Hellotext=Ai;const ws=Ai},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header,\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3,\n.hellotext--popup__completion-headline h1,\n.hellotext--popup__completion-headline h2,\n.hellotext--popup__completion-headline h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n}\n\n.hellotext--popup__completion-footer {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n justify-content: center;\n gap: 0 4px;\n text-align: center;\n}\n\n.hellotext--popup__completion-footer > span,\n.hellotext--popup__completion-action:disabled {\n opacity: 0.5;\n}\n\n.hellotext--popup__completion-action {\n appearance: none;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent;\n color: inherit;\n cursor: pointer;\n font: inherit;\n font-weight: 500;\n line-height: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n\n.hellotext--popup__completion-action:disabled {\n cursor: default;\n text-decoration: none;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c(()=>{"use strict";var e={891(e,t,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class O{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,n){T(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){T(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new O}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new O}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new O}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new O,this.outletElementsByName=new O,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 O;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class q{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class z{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class U{constructor(e,t,n,r){this.targets=new q(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new z(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 H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new O,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>ws});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function O(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(q).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function U(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=U(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=U(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=U(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=T.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=z.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=T,Z.popup=L,Z.webchat=z,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(Fe({session:Ai.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&qe(e.prototype,null),t&&qe(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=Ue;function We(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $e(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return et(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ai.headers}),r=yield n.json();return Ai.business.data||(Ai.business.setData(r.business),Ai.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){tt(o,r,i,a,s,"next",e)}function s(e){tt(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&nt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ot=it;function at(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function st(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){at(o,r,i,a,s,"next",e)}function s(e){at(o,r,i,a,s,"throw",e)}a(void 0)})}}function lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ai.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){mt(o,r,i,a,s,"next",e)}function s(e){mt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&yt(e.prototype,null),t&&yt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const bt=vt;function wt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(Pt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(Pt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&Et(e.prototype,t),n&&Et(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return It(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),Mt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(Mt.get("hello_utm"))||{}}catch(e){return{}}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new Dt,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Rt(t.prototype,n),r&&Rt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Vt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Bt;zt(this,Kt)[Kt]=e,zt(this,$t)[$t]=new ye,this.session=zt(this,$t)[$t].session||Z.session||Mt.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Vt(e.prototype,null),t&&Vt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ai.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const sn=Object.entries,ln=Object.setPrototypeOf,cn=Object.isFrozen,un=Object.getPrototypeOf,hn=Object.getOwnPropertyDescriptor;let pn=Object.freeze,dn=Object.seal,fn=Object.create,mn="undefined"!=typeof Reflect&&Reflect,yn=mn.apply,gn=mn.construct;pn||(pn=function(e){return e}),dn||(dn=function(e){return e}),yn||(yn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:kn;if(ln&&ln(e,null),!xn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(cn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function qn(e){for(let t=0;t/g),rr=dn(/\${[\w\W]*/g),ir=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),or=dn(/^aria-[\-\w]+$/),ar=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sr=dn(/^(?:\w+script|data):/i),lr=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cr=dn(/^html$/i),ur=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),hr=dn(/<[/\w!]/g),pr=dn(/<[/\w]/g),dr=dn(/<\/no(script|embed|frames)/i),fr=dn(/\/>/i),mr=function(){return"undefined"==typeof window?null:window},yr=function(e,t,n,r){return Ln(e,t)&&xn(e[t])?Vn(r.base?zn(r.base):{},e[t],r.transform):n};var gr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=Un(p,"cloneNode"),f=Un(p,"remove"),m=Un(p,"nextSibling"),y=Un(p,"childNodes"),g=Un(p,"parentNode"),v=Un(p,"shadowRoot"),b=Un(p,"attributes"),w=s&&s.prototype?Un(s.prototype,"nodeType"):null,T=s&&s.prototype?Un(s.prototype,"nodeName"):null,O=s&&s.prototype?Un(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Rn('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof sn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=tr,F=nr,B=rr,V=ir,q=or,z=sr,U=lr,H=ur;let W=ar,$=null;const K=Vn({},[...Hn,...Wn,...$n,...Gn,...Yn]);let G=null;const J=Vn({},[...Xn,...Zn,...Qn,...er]);let Y=Object.seal(fn(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}})),X=null,Z=null;const Q=Object.seal(fn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Te=Vn({},["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 Oe=null;const xe=Vn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Vn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Vn({},[Ee,Ce,Pe],Sn),Ie=pn(["mi","mo","mn","ms","mtext"]);let Le=Vn({},Ie);const Ne=pn(["annotation-xml"]);let De=Vn({},Ne);const Re=Vn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,qe=null;const ze=r.createElement("form"),Ue=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(qe&&qe===e)return;e&&"object"==typeof e||(e={}),e=zn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Sn:kn,$=yr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=yr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=yr(e,"ALLOWED_NAMESPACES",Me,{transform:Sn}),ke=yr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Oe=yr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=yr(e,"FORBID_CONTENTS",Te,{transform:Ve}),X=yr(e,"FORBID_TAGS",zn({}),{transform:Ve}),Z=yr(e,"FORBID_ATTR",zn({}),{transform:Ve}),be=!!Ln(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?zn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return Dn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:ar,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=Ln(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?zn(e.MATHML_TEXT_INTEGRATION_POINTS):Vn({},Ie),De=Ln(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?zn(e.HTML_INTEGRATION_POINTS):Vn({},Ne);const t=Ln(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?zn(e.CUSTOM_ELEMENT_HANDLING):fn(null);if(Y=fn(null),Ln(t,"tagNameCheck")&&Ue(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Ln(t,"attributeNameCheck")&&Ue(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Ln(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),dn(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Vn({},Yn),G=fn(null),!0===be.html&&(Vn($,Hn),Vn(G,Xn)),!0===be.svg&&(Vn($,Wn),Vn(G,Zn),Vn(G,er)),!0===be.svgFilters&&(Vn($,$n),Vn(G,Zn),Vn(G,er)),!0===be.mathMl&&(Vn($,Gn),Vn(G,Qn),Vn(G,er))),Q.tagCheck=null,Q.attributeCheck=null,Ln(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:xn(e.ADD_TAGS)&&($===K&&($=zn($)),Vn($,e.ADD_TAGS,Ve))),Ln(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:xn(e.ADD_ATTR)&&(G===J&&(G=zn(G)),Vn(G,e.ADD_ATTR,Ve))),Ln(e,"ADD_URI_SAFE_ATTR")&&xn(e.ADD_URI_SAFE_ATTR)&&Vn(ke,e.ADD_URI_SAFE_ATTR,Ve),Ln(e,"FORBID_CONTENTS")&&xn(e.FORBID_CONTENTS)&&(we===Te&&(we=zn(we)),Vn(we,e.FORBID_CONTENTS,Ve)),Ln(e,"ADD_FORBID_CONTENTS")&&xn(e.ADD_FORBID_CONTENTS)&&(we===Te&&(we=zn(we)),Vn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Vn($,["html","head","body"]),$.table&&(Vn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));pn&&pn(e),qe=e},We=Vn({},[...Wn,...$n,...Kn]),$e=Vn({},[...Gn,...Jn]),Ke=function(e){Tn(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Rn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];vn(t,t=>{Tn(e,t)}),vn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{Tn(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Tn(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=En(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=O?O(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=Cn(e,R," "),e=Cn(e,F," "),Cn(e,B," ")},tt=function(e){var t;e.normalize();const n=O?O(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&vn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=T?T(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&vn(e,e=>{e.call(n,t,r,qe)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?zn(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(T?T(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&Dn(hr,e.textContent)&&Dn(hr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!Dn(pr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=kn(e.tagName),r=kn(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&Dn(dr,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(Tn(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in ze))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&Dn(V,t));else if(ee&&Dn(q,t));else if(i){if(ke[t]);else if(Dn(W,Cn(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Pn(n,"data:")||!Oe[e])if(ne&&!Dn(z,Cn(n,U,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Dn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Vn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[kn(e)]&&Dn(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):wn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:An(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Pn(h,ye)||(Je(a,e),h=ye+h),oe&&Dn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&En(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&Dn(fr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=T?T(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return jn(e);case"boolean":return _n(e);case"bigint":return Mn?Mn(e):"0";case"symbol":return In?In(e):"Symbol()";case"undefined":default:return Nn(e);case"function":case"object":{if(null===e)return Nn(e);const t=e,n=Un(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Nn(e)}return Nn(e)}}}(e)))throw Rn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=zn($)),D.uponSanitizeAttribute.length>0&&(G=zn(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&Dn(pr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(T?T(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=T?T(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Rn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Rn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),vn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return vn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Dn(cr,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){qe=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){qe||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ln(D,e)&&Tn(D[e],t)},n.removeHook=function(e,t){if(Ln(D,e)){if(void 0!==t){const n=bn(D[e],t);return-1===n?void 0:On(D[e],n,1)[0]}return wn(D[e])}},n.removeHooks=function(e){Ln(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),vr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},br={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function wr(e,t){var n=gr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function Tr(e,t){e.replaceChildren(function(e){return wr(e,vr)}(t))}function Or(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xr(e,t,n){return(t=Er(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Sr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,jr,{value:Mr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ai.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ai.business.features.white_label||this.element.prepend(rn.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){kr(o,r,i,a,s,"next",e)}function s(e){kr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=Cr(this,jr)[jr]("[data-form-header]","header");Tr(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=Cr(this,jr)[jr]("[data-form-inputs]","main");e.map(e=>Xt.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)}},{key:"buildButton",value:function(e){var t=Cr(this,jr)[jr]("[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)}},{key:"buildFooter",value:function(e){var t=Cr(this,jr)[jr]("[data-form-footer]","footer");Tr(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ai.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Sr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Mr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function Ir(e){var t="function"==typeof Map?new Map:void 0;return Ir=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(Lr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Nr(i,n.prototype),i}(e,arguments,Dr(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Nr(n,e)},Ir(e)}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Lr=function(){return!!e})()}function Nr(e,t){return Nr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Nr(e,t)}function Dr(e){return Dr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Dr(e)}var Rr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Dr(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Lr()?Reflect.construct(t,n||[],Dr(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Ir(Error));function Fr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Br(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ai.notInitialized)throw new Rr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,Ur)[Ur];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ai.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Fr(o,r,i,a,s,"next",e)}function s(e){Fr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ai.business.data||(Ai.business.setData(e.business),Ai.business.setLocale(j.toString())),Ai.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 _r(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Br(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Wr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function $r(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Kr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$r(o,r,i,a,s,"next",e)}function s(e){$r(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gr(e,t){for(var n=0;nyi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=yi(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function gi(e,t){var n=yi(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function vi(){return(vi=pi(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var bi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=pi(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return vi.apply(this,arguments)}(gi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&ui(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function wi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new At(e),this.page=new Bt,Z.assign(t),Gt.initialize(this.page),this.forms=new Hr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Yr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield ti.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ai.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=Oi({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return wi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Si(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Rr;var n=Oi(Oi({},t&&t.headers||{}),this.headers),r=Oi(Oi({},ci.identificationData),t.user_parameters||{}),i=t&&t.url?new Bt(t.url):this.page,o=Oi(Oi({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield xt.events.create({headers:n,body:o,keepalive:Ot(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Si(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield bi.generate(this.session,e,n);if(bi.matches(ci.fingerprint,r))return new ke(!0,{json:(t=Si(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield xt.identifications.create(Oi({user_id:e},n));return i.succeeded&&ci.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ci.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Gt.session}},{key:"isInitialized",get:function(){return void 0!==Gt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Rr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&Ei(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Pi.eventEmitter=new ce,Pi.forms=void 0,Pi.business=void 0,Pi.popup=void 0,Pi.webchat=void 0,Pi.whatsapp=void 0;const Ai=Pi;function ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function _i(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ai.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){ji(o,n,r,a,s,"next",e)}function s(e){ji(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ai.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&_i(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Bi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Vi(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&zi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function Ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Yi(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ji(o,r,i,a,s,"next",e)}function s(e){Ji(o,r,i,a,s,"throw",e)}a(void 0)})}}function Xi(e,t){for(var n=0;n{e.disabled=!0});var t=yield xt.popups.submit(this.idValue,this.submissionPayload());if(this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed)yield this.handleSubmissionError(t);else{try{var n=yield t.json();this.submissionId=n.id,this.submissionVerificationState=n.verification_state,this.submissionActionToken=n.action_token,this.submissionDeliveryStatus=n.delivery_status,this.submissionDeliveryChannel=n.delivery_channel,this.submissionDestination=n.destination}catch(e){this.submissionId=null}this.showCompleted()}}else this.showErrorMessages(this.currentStepInputs)}),function(e){return s.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.configureCompletionActions(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.completedIdentity;if(e){var t={destination:e.value,channel:this.submissionDeliveryChannel||e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"configureCompletionActions",value:function(){var e;if("not_required"===this.submissionDeliveryStatus)return this.renderNoDeliveryCopy(),void(null===(e=this.completedTarget.querySelector("[data-delivery-actions]"))||void 0===e||e.setAttribute("hidden",""));var t=this.completedIdentity;t&&(this.hasChangeDestinationButtonTarget&&(this.changeDestinationButtonTarget.textContent=this.changeDestinationButtonTarget.dataset["".concat(t.kind,"Label")],this.showElement(this.changeDestinationButtonTarget)),this.submissionId&&this.submissionActionToken&&"queued"===this.submissionDeliveryStatus&&"unverified"===this.submissionVerificationState&&this.hasResendButtonTarget&&(this.showElement(this.resendButtonTarget),this.startResendCooldown(60)))}},{key:"resend",value:(a=Yi(function*(e){if(e&&e.preventDefault(),this.submissionId&&this.submissionActionToken&&!this.resendPending&&!this.resendCooldownActive&&this.completedIdentity){this.resendPending=!0,this.resendButtonTarget.disabled=!0;try{var t,n=yield xt.popups.resend(this.idValue,this.submissionId,this.submissionActionToken),r=Number(null===(t=n.data.headers)||void 0===t?void 0:t.get("Retry-After"))||60;n.succeeded||429===n.data.status?this.startResendCooldown(r):this.resendButtonTarget.disabled=!1}catch(e){this.resendButtonTarget.disabled=!1}finally{this.resendPending=!1}}}),function(e){return a.apply(this,arguments)})},{key:"changeDestination",value:(o=Yi(function*(e){var t;e&&e.preventDefault();var n=null===(t=this.completedIdentity)||void 0===t?void 0:t.input;if(n){var r=this.stepTargets.findIndex(e=>e.dataset.stepId===n.dataset.popupStepId);r<0||(this.stopResendCooldown(),this.submissionId=null,this.submissionActionToken=null,this.submissionVerificationState=null,this.submissionDeliveryStatus=null,this.submissionDeliveryChannel=null,this.submissionDestination=null,this.showStep(r),n.focus())}}),function(e){return o.apply(this,arguments)})},{key:"startResendCooldown",value:function(e){this.stopResendCooldown(),this.resendCooldownEndsAt=Date.now()+1e3*Math.max(e,1),this.updateResendCountdown(),this.resendTimer=window.setInterval(()=>this.updateResendCountdown(),1e3)}},{key:"stopResendCooldown",value:function(){this.resendTimer&&window.clearInterval(this.resendTimer),this.resendTimer=null,this.resendCooldownEndsAt=null}},{key:"updateResendCountdown",value:function(){var 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);var t="".concat(Math.floor(e/60),":").concat(String(e%60).padStart(2,"0")),n=this.resendButtonTarget.dataset.countdownLabel||"".concat(this.resendLabel," %{time}");this.resendButtonTarget.textContent=n.replace("%{time}",t),this.resendButtonTarget.disabled=!0}},{key:"resendCooldownActive",get:function(){return this.resendCooldownEndsAt>Date.now()}},{key:"completionIdentity",get:function(){return this.identityInputs.map(e=>({input:e,kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value)}},{key:"completedIdentity",get:function(){if(this.submissionDestination&&this.submissionDeliveryChannel){var e="email"===this.submissionDeliveryChannel?"email":"phone";return{input:this.identityInputs.find(t=>t.dataset.popupFieldKind===e),kind:e,value:this.submissionDestination}}return this.completionIdentity}},{key:"renderNoDeliveryCopy",value:function(){var e=this.completedTarget.querySelector(".hellotext--popup__completion-headline"),t=this.completedTarget.querySelector(".hellotext--popup__completion-description");if(e&&this.completedTarget.dataset.notRequiredHeadline){e.innerHTML="";var n=document.createElement("h4"),r=document.createElement("strong");r.textContent=this.completedTarget.dataset.notRequiredHeadline,n.appendChild(r),e.appendChild(n)}t&&(t.textContent=this.completedTarget.dataset.notRequiredDescription||"")}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Yi(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Xi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l}(g.xI);ro.targets=["bubble","dialog","step","completed","input","submitButton","resendButton","changeDestinationButton"],ro.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const io=["start","end"],oo=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+io[0],t+"-"+io[1]),[]),ao=Math.min,so=Math.max,lo=Math.round,co=Math.floor,uo=e=>({x:e,y:e}),ho={left:"right",right:"left",bottom:"top",top:"bottom"};function po(e,t){return"function"==typeof e?e(t):e}function fo(e){return e.split("-")[0]}function mo(e){return e.split("-")[1]}function yo(e){return"x"===e?"y":"x"}function go(e){return"y"===e?"height":"width"}function vo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function bo(e){return yo(vo(e))}function wo(e,t,n){void 0===n&&(n=!1);const r=mo(e),i=bo(e),o=go(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Eo(a)),[a,Eo(a)]}function To(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Oo=["left","right"],xo=["right","left"],ko=["top","bottom"],So=["bottom","top"];function Eo(e){const t=fo(e);return ho[t]+e.slice(t.length)}function Co(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Po(e,t,n){let{reference:r,floating:i}=e;const o=vo(t),a=bo(t),s=go(a),l=fo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=mo(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Ao(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=po(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=Co(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Co(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const jo=new Set(["left","top"]);function _o(){return"undefined"!=typeof window}function Mo(e){return No(e)?(e.nodeName||"").toLowerCase():"#document"}function Io(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Lo(e){var t;return null==(t=(No(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function No(e){return!!_o()&&(e instanceof Node||e instanceof Io(e).Node)}function Do(e){return!!_o()&&(e instanceof Element||e instanceof Io(e).Element)}function Ro(e){return!!_o()&&(e instanceof HTMLElement||e instanceof Io(e).HTMLElement)}function Fo(e){return!(!_o()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Io(e).ShadowRoot)}function Bo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Jo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Vo(e){return/^(table|td|th)$/.test(Mo(e))}function qo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const zo=/transform|translate|scale|rotate|perspective|filter/,Uo=/paint|layout|strict|content/,Ho=e=>!!e&&"none"!==e;let Wo;function $o(e){const t=Do(e)?Jo(e):e;return Ho(t.transform)||Ho(t.translate)||Ho(t.scale)||Ho(t.rotate)||Ho(t.perspective)||!Ko()&&(Ho(t.backdropFilter)||Ho(t.filter))||zo.test(t.willChange||"")||Uo.test(t.contain||"")}function Ko(){return null==Wo&&(Wo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Wo}function Go(e){return/^(html|body|#document)$/.test(Mo(e))}function Jo(e){return Io(e).getComputedStyle(e)}function Yo(e){return Do(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xo(e){if("html"===Mo(e))return e;const t=e.assignedSlot||e.parentNode||Fo(e)&&e.host||Lo(e);return Fo(t)?t.host:t}function Zo(e){const t=Xo(e);return Go(t)?(e.ownerDocument||e).body:Ro(t)&&Bo(t)?t:Zo(t)}function Qo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Zo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Io(i);if(o){const e=ea(a);return t.concat(a,a.visualViewport||[],Bo(i)?i:[],e&&n?Qo(e):[])}return t.concat(i,Qo(i,[],n))}function ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ta(e){const t=Jo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ro(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=lo(n)!==o||lo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function na(e){return Do(e)?e:e.contextElement}function ra(e){const t=na(e);if(!Ro(t))return uo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=ta(t);let a=(o?lo(n.width):n.width)/r,s=(o?lo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ia=uo(0);function oa(e){const t=Io(e);return Ko()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ia}function aa(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=na(e);let a=uo(1);t&&(r?Do(r)&&(a=ra(r)):a=ra(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===Io(e)}(o,n,r)?oa(o):uo(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=Io(o),t=Do(r)?Io(r):r;let n=e,i=ea(n);for(;i&&t!==n;){const e=ra(i),t=i.getBoundingClientRect(),r=Jo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=Io(i),i=ea(n)}}return Co({width:u,height:h,x:l,y:c})}function sa(e,t){const n=Yo(e).scrollLeft;return t?t.left+n:aa(Lo(e)).left+n}function la(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-sa(e,n),y:n.top+t.scrollTop}}function ca(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=Io(e),o=Lo(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ko()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(sa(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Yo(e),n=e.ownerDocument.body,r=so(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=so(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+sa(e);const a=-t.scrollTop;return"rtl"===Jo(n).direction&&(o+=so(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(Lo(e));else if(Do(t))r=function(e,t){const n=aa(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ra(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=oa(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Co(r)}function ua(e,t,n){const r=Ro(t),i=Lo(t),o="fixed"===n,a=aa(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=uo(0);if((r||!o)&&(("body"!==Mo(t)||Bo(i))&&(s=Yo(t)),r)){const e=aa(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=sa(i));const c=!i||r||o?uo(0):la(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function ha(e){return"static"===Jo(e).position}function pa(e,t){if(!Ro(e)||"fixed"===Jo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Lo(e)===n&&(n=n.ownerDocument.body),n}function da(e,t){const n=Io(e);if(qo(e))return n;if(!Ro(e)){let t=Xo(e);for(;t&&!Go(t);){if(Do(t)&&!ha(t))return t;t=Xo(t)}return n}let r=pa(e,t);for(;r&&Vo(r)&&ha(r);)r=pa(r,t);return r&&Go(r)&&ha(r)&&!$o(r)?n:r||function(e){let t=Xo(e);for(;Ro(t)&&!Go(t);){if($o(t))return t;if(qo(t))return null;t=Xo(t)}return null}(e)||n}const fa={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Lo(r),s=!!t&&qo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=uo(1);const u=uo(0),h=Ro(r);if((h||!o)&&(("body"!==Mo(r)||Bo(a))&&(l=Yo(r)),h)){const e=aa(r);c=ra(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?uo(0):la(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:Lo,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?qo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Qo(e,[],!1).filter(e=>Do(e)&&"body"!==Mo(e)),i=null;const o="fixed"===Jo(e).position;let a=o?Xo(e):e;for(;Do(a)&&!Go(a);){const e=Jo(a),t=$o(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Xo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=ca(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;emo(t)===e),...n.filter(t=>mo(t)!==e)]:n.filter(e=>fo(e)===e)).filter(n=>!e||mo(n)===e||!!t&&To(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=wo(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[fo(g)],v[b[0]],v[b[1]]],T=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],O=m[y+1];if(O)return{data:{index:y+1,overflows:T},reset:{placement:O}};const x=T.map(e=>{const t=mo(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,mo(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:T},reset:{placement:k}}:{}}}},va=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=po(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=vo(i),d=yo(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],so(n,ao(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ba=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=po(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=fo(i),v=vo(s),b=fo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),T=p||(b||!m?[Eo(s)]:function(e){const t=Eo(e);return[To(e),t,To(t)]}(s)),O="none"!==f;!p&&O&&T.push(...function(e,t,n,r){const i=mo(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?xo:Oo:t?Oo:xo;case"left":case"right":return t?ko:So;default:return[]}}(fo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(To)))),o}(s,m,f,w));const x=[s,...T],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=wo(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===vo(t)||E.every(e=>vo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(O){const t=vo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var wa=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=na(e),u=i||o?[...c?Qo(c):[],...t?Qo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=Lo(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-co(h)+"px "+-co(o.clientWidth-(u+p))+"px "+-co(o.clientHeight-(h+d))+"px "+-co(u)+"px",threshold:so(0,ao(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!ma(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=Io(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?aa(e):null;return l&&function t(){const r=aa(e);m&&!ma(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...fa,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Ao},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=Po(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Ta(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ia(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ia(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ai.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ai.session})}},{key:"create",value:(i=Na(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ai.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ai.headers,body:JSON.stringify({session:Ai.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Da(t.prototype,n),r&&Da(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Ba=Fa;function Va(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Va(t.prototype,n),r&&Va(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Ua(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ya(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ka(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ka(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ka(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&Ua(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(za);const Za=Xa;var Qa=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},es=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ts=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function ns(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=as(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ai.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),Tr(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){z.mode===q.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ai.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ai.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",Tr(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=as(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return wr(e,br)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=as(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ai.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ai.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=as(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ai.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=as(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ai.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=as(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=as(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[ya(this.offsetValue),va({padding:this.paddingValue}),ba()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ys.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ms)}catch(e){return new Intl.DateTimeFormat(void 0,ms)}}}],r&&ss(n.prototype,r),i&&ss(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);vs.messageTimestampFormatters={},vs.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},vs.classes=["fadeOut"],vs.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"];var bs=g.lg.start();bs.register("hellotext--form",Fi),bs.register("hellotext--popup",ro),bs.register("hellotext--webchat",vs),bs.register("hellotext--webchat--emoji",Ma),bs.register("hellotext--message",Gi),window.Hellotext=Ai;const ws=Ai},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 1.125em;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__completion-headline h4 {\n margin: 0 0 8px;\n font-size: 1.44444444em;\n line-height: 1.25;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n}\n\n.hellotext--popup__completion-footer {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n justify-content: center;\n gap: 0 4px;\n text-align: center;\n}\n\n.hellotext--popup__completion-footer > span,\n.hellotext--popup__completion-action:disabled {\n opacity: 0.5;\n}\n\n.hellotext--popup__completion-action {\n appearance: none;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent;\n color: inherit;\n cursor: pointer;\n font: inherit;\n font-weight: 500;\n line-height: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n\n.hellotext--popup__completion-action:disabled {\n cursor: default;\n text-decoration: none;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c step.dataset.stepId === input.dataset.popupStepId); if (stepIndex < 0) return; - this.changeDestinationButtonTarget.disabled = true; - try { - const response = await _api.default.popups.cancel(this.idValue, this.submissionId, this.submissionActionToken); - if (response.failed) return; - } catch (_) { - return; - } finally { - this.changeDestinationButtonTarget.disabled = false; - } this.stopResendCooldown(); this.submissionId = null; this.submissionActionToken = null; + this.submissionVerificationState = null; + this.submissionDeliveryStatus = null; + this.submissionDeliveryChannel = null; + this.submissionDestination = null; this.showStep(stepIndex); input.focus(); } @@ -309,6 +313,35 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { value }) => value); } + }, { + key: "completedIdentity", + get: function () { + if (this.submissionDestination && this.submissionDeliveryChannel) { + const kind = this.submissionDeliveryChannel === 'email' ? 'email' : 'phone'; + const input = this.identityInputs.find(candidate => candidate.dataset.popupFieldKind === kind); + return { + input, + kind, + value: this.submissionDestination + }; + } + return this.completionIdentity; + } + }, { + key: "renderNoDeliveryCopy", + value: function renderNoDeliveryCopy() { + const headline = this.completedTarget.querySelector('.hellotext--popup__completion-headline'); + const description = this.completedTarget.querySelector('.hellotext--popup__completion-description'); + if (headline && this.completedTarget.dataset.notRequiredHeadline) { + headline.innerHTML = ''; + const title = document.createElement('h4'); + const strong = document.createElement('strong'); + strong.textContent = this.completedTarget.dataset.notRequiredHeadline; + title.appendChild(strong); + headline.appendChild(title); + } + if (description) description.textContent = this.completedTarget.dataset.notRequiredDescription || ''; + } }, { key: "currentStepValid", value: function currentStepValid() { diff --git a/lib/controllers/popup_controller.js b/lib/controllers/popup_controller.js index 8f67d282..5293752a 100644 --- a/lib/controllers/popup_controller.js +++ b/lib/controllers/popup_controller.js @@ -133,6 +133,9 @@ var _default = /*#__PURE__*/function (_Controller) { this.submissionId = submission.id; this.submissionVerificationState = submission.verification_state; this.submissionActionToken = submission.action_token; + this.submissionDeliveryStatus = submission.delivery_status; + this.submissionDeliveryChannel = submission.delivery_channel; + this.submissionDestination = submission.destination; } catch (_) { this.submissionId = null; } @@ -188,11 +191,11 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "interpolateCompletionCopy", value: function interpolateCompletionCopy() { - var identity = this.completionIdentity; + var identity = this.completedIdentity; if (!identity) return; var replacements = { destination: identity.value, - channel: identity.kind + channel: this.submissionDeliveryChannel || identity.kind }; this.completionTextTemplates.forEach(_ref => { var node = _ref.node, @@ -211,13 +214,19 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "configureCompletionActions", value: function configureCompletionActions() { - var identity = this.completionIdentity; + if (this.submissionDeliveryStatus === 'not_required') { + var _this$completedTarget; + this.renderNoDeliveryCopy(); + (_this$completedTarget = this.completedTarget.querySelector('[data-delivery-actions]')) === null || _this$completedTarget === void 0 || _this$completedTarget.setAttribute('hidden', ''); + return; + } + var identity = this.completedIdentity; if (!identity) return; if (this.hasChangeDestinationButtonTarget) { this.changeDestinationButtonTarget.textContent = this.changeDestinationButtonTarget.dataset["".concat(identity.kind, "Label")]; this.showElement(this.changeDestinationButtonTarget); } - if (this.submissionId && this.submissionActionToken && this.submissionVerificationState === 'unverified' && this.hasResendButtonTarget) { + if (this.submissionId && this.submissionActionToken && this.submissionDeliveryStatus === 'queued' && this.submissionVerificationState === 'unverified' && this.hasResendButtonTarget) { this.showElement(this.resendButtonTarget); this.startResendCooldown(60); } @@ -228,13 +237,13 @@ var _default = /*#__PURE__*/function (_Controller) { var _resend = _asyncToGenerator(function* (event) { if (event) event.preventDefault(); if (!this.submissionId || !this.submissionActionToken || this.resendPending || this.resendCooldownActive) return; - var identity = this.completionIdentity; + var identity = this.completedIdentity; if (!identity) return; this.resendPending = true; this.resendButtonTarget.disabled = true; try { var _response$data$header; - var response = yield API.popups.resend(this.idValue, this.submissionId, identity.kind, this.submissionActionToken); + var response = yield API.popups.resend(this.idValue, this.submissionId, this.submissionActionToken); var retryAfter = Number((_response$data$header = response.data.headers) === null || _response$data$header === void 0 ? void 0 : _response$data$header.get('Retry-After')) || 60; if (response.succeeded || response.data.status === 429) { this.startResendCooldown(retryAfter); @@ -256,24 +265,19 @@ var _default = /*#__PURE__*/function (_Controller) { key: "changeDestination", value: function () { var _changeDestination = _asyncToGenerator(function* (event) { - var _this$completionIdent; + var _this$completedIdenti; if (event) event.preventDefault(); - var input = (_this$completionIdent = this.completionIdentity) === null || _this$completionIdent === void 0 ? void 0 : _this$completionIdent.input; + var input = (_this$completedIdenti = this.completedIdentity) === null || _this$completedIdenti === void 0 ? void 0 : _this$completedIdenti.input; if (!input) return; var stepIndex = this.stepTargets.findIndex(step => step.dataset.stepId === input.dataset.popupStepId); if (stepIndex < 0) return; - this.changeDestinationButtonTarget.disabled = true; - try { - var response = yield API.popups.cancel(this.idValue, this.submissionId, this.submissionActionToken); - if (response.failed) return; - } catch (_) { - return; - } finally { - this.changeDestinationButtonTarget.disabled = false; - } this.stopResendCooldown(); this.submissionId = null; this.submissionActionToken = null; + this.submissionVerificationState = null; + this.submissionDeliveryStatus = null; + this.submissionDeliveryChannel = null; + this.submissionDestination = null; this.showStep(stepIndex); input.focus(); }); @@ -329,6 +333,35 @@ var _default = /*#__PURE__*/function (_Controller) { return value; }); } + }, { + key: "completedIdentity", + get: function get() { + if (this.submissionDestination && this.submissionDeliveryChannel) { + var kind = this.submissionDeliveryChannel === 'email' ? 'email' : 'phone'; + var input = this.identityInputs.find(candidate => candidate.dataset.popupFieldKind === kind); + return { + input, + kind, + value: this.submissionDestination + }; + } + return this.completionIdentity; + } + }, { + key: "renderNoDeliveryCopy", + value: function renderNoDeliveryCopy() { + var headline = this.completedTarget.querySelector('.hellotext--popup__completion-headline'); + var description = this.completedTarget.querySelector('.hellotext--popup__completion-description'); + if (headline && this.completedTarget.dataset.notRequiredHeadline) { + headline.innerHTML = ''; + var title = document.createElement('h4'); + var strong = document.createElement('strong'); + strong.textContent = this.completedTarget.dataset.notRequiredHeadline; + title.appendChild(strong); + headline.appendChild(title); + } + if (description) description.textContent = this.completedTarget.dataset.notRequiredDescription || ''; + } }, { key: "currentStepValid", value: function currentStepValid() { diff --git a/src/api/popups.js b/src/api/popups.js index a9f19933..b51fb0fe 100644 --- a/src/api/popups.js +++ b/src/api/popups.js @@ -47,11 +47,11 @@ class PopupsAPI { return new Response(response.ok, response) } - static async resend(id, submissionId, identity, token) { + static async resend(id, submissionId, token) { const response = await fetch(`${this.endpoint}/${id}/submissions/${submissionId}/resend`, { method: 'POST', headers: Hellotext.headers, - body: JSON.stringify({ identity, token }), + body: JSON.stringify({ token }), }) return new Response(response.ok, response) diff --git a/src/controllers/popup_controller.js b/src/controllers/popup_controller.js index 973d2c38..d05161a5 100644 --- a/src/controllers/popup_controller.js +++ b/src/controllers/popup_controller.js @@ -138,6 +138,9 @@ export default class extends Controller { this.submissionId = submission.id this.submissionVerificationState = submission.verification_state this.submissionActionToken = submission.action_token + this.submissionDeliveryStatus = submission.delivery_status + this.submissionDeliveryChannel = submission.delivery_channel + this.submissionDestination = submission.destination } catch (_) { this.submissionId = null } @@ -188,13 +191,13 @@ export default class extends Controller { } interpolateCompletionCopy() { - const identity = this.completionIdentity + const identity = this.completedIdentity if (!identity) return const replacements = { destination: identity.value, - channel: identity.kind, + channel: this.submissionDeliveryChannel || identity.kind, } this.completionTextTemplates.forEach(({ node, template }) => { @@ -215,7 +218,13 @@ export default class extends Controller { } configureCompletionActions() { - const identity = this.completionIdentity + if (this.submissionDeliveryStatus === 'not_required') { + this.renderNoDeliveryCopy() + this.completedTarget.querySelector('[data-delivery-actions]')?.setAttribute('hidden', '') + return + } + + const identity = this.completedIdentity if (!identity) return if (this.hasChangeDestinationButtonTarget) { @@ -227,6 +236,7 @@ export default class extends Controller { if ( this.submissionId && this.submissionActionToken && + this.submissionDeliveryStatus === 'queued' && this.submissionVerificationState === 'unverified' && this.hasResendButtonTarget ) { @@ -239,7 +249,7 @@ export default class extends Controller { if (event) event.preventDefault() if (!this.submissionId || !this.submissionActionToken || this.resendPending || this.resendCooldownActive) return - const identity = this.completionIdentity + const identity = this.completedIdentity if (!identity) return this.resendPending = true @@ -249,7 +259,6 @@ export default class extends Controller { const response = await API.popups.resend( this.idValue, this.submissionId, - identity.kind, this.submissionActionToken, ) const retryAfter = Number(response.data.headers?.get('Retry-After')) || 60 @@ -269,30 +278,19 @@ export default class extends Controller { async changeDestination(event) { if (event) event.preventDefault() - const input = this.completionIdentity?.input + const input = this.completedIdentity?.input if (!input) return const stepIndex = this.stepTargets.findIndex(step => step.dataset.stepId === input.dataset.popupStepId) if (stepIndex < 0) return - this.changeDestinationButtonTarget.disabled = true - - try { - const response = await API.popups.cancel( - this.idValue, - this.submissionId, - this.submissionActionToken, - ) - if (response.failed) return - } catch (_) { - return - } finally { - this.changeDestinationButtonTarget.disabled = false - } - this.stopResendCooldown() this.submissionId = null this.submissionActionToken = null + this.submissionVerificationState = null + this.submissionDeliveryStatus = null + this.submissionDeliveryChannel = null + this.submissionDestination = null this.showStep(stepIndex) input.focus() } @@ -338,6 +336,33 @@ export default class extends Controller { })).find(({ value }) => value) } + get completedIdentity() { + if (this.submissionDestination && this.submissionDeliveryChannel) { + const kind = this.submissionDeliveryChannel === 'email' ? 'email' : 'phone' + const input = this.identityInputs.find(candidate => candidate.dataset.popupFieldKind === kind) + + return { input, kind, value: this.submissionDestination } + } + + return this.completionIdentity + } + + renderNoDeliveryCopy() { + const headline = this.completedTarget.querySelector('.hellotext--popup__completion-headline') + const description = this.completedTarget.querySelector('.hellotext--popup__completion-description') + + if (headline && this.completedTarget.dataset.notRequiredHeadline) { + headline.innerHTML = '' + const title = document.createElement('h4') + const strong = document.createElement('strong') + strong.textContent = this.completedTarget.dataset.notRequiredHeadline + title.appendChild(strong) + headline.appendChild(title) + } + + if (description) description.textContent = this.completedTarget.dataset.notRequiredDescription || '' + } + currentStepValid() { return this.currentStepInputs.every(input => input.checkValidity()) } From 115c813c46c16dc2cb9f93d42585a250ed3531c8 Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Thu, 27 Aug 2026 19:05:11 -0400 Subject: [PATCH 09/11] popups: adjust completed step typography --- styles/index.css | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/styles/index.css b/styles/index.css index 1eb1a0d0..9c76f765 100644 --- a/styles/index.css +++ b/styles/index.css @@ -528,27 +528,36 @@ form[data-hello-form] [data-logo-container] [data-hello-brand] { gap: 12px 28px; } -.hellotext--popup__step-header, -.hellotext--popup__completion-headline { +.hellotext--popup__step-header { width: 100%; margin: 0; font-size: 18px; line-height: 1.25; } +.hellotext--popup__completion-headline { + width: 100%; + margin: 0; + font-size: 1.125em; + line-height: 1.25; +} + .hellotext--popup__rich-text * { color: inherit; } .hellotext--popup__step-header h1, .hellotext--popup__step-header h2, -.hellotext--popup__step-header h3, -.hellotext--popup__completion-headline h1, -.hellotext--popup__completion-headline h2, -.hellotext--popup__completion-headline h3 { +.hellotext--popup__step-header h3 { margin: 0 0 8px; font-size: clamp(32px, 7vw, 48px); line-height: 0.95; } +.hellotext--popup__completion-headline h4 { + margin: 0 0 8px; + font-size: 1.44444444em; + line-height: 1.25; +} + .hellotext--popup__fields-region { width: 100%; } .hellotext--popup__fields { From e90e86d07105fd789d2c1a6e37854c6f363963af Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Fri, 28 Aug 2026 20:02:49 -0400 Subject: [PATCH 10/11] popups: load active dashboard popups safely --- README.md | 20 +- .../controllers/popup_controller_test.js | 74 ++- __tests__/hellotext_test.js | 465 +++++++++++++++++- __tests__/models/popup_test.js | 13 + __tests__/models/webchat_test.js | 14 + __tests__/models/whatsapp_widget_test.js | 14 + dist/hellotext.js | 2 +- index.d.ts | 2 + lib/api/businesses.cjs | 8 +- lib/api/businesses.js | 11 +- lib/controllers/popup_controller.cjs | 39 +- lib/controllers/popup_controller.js | 39 +- lib/hellotext.cjs | 270 +++++++++- lib/hellotext.js | 281 +++++++++-- lib/models/business.cjs | 50 +- lib/models/business.js | 48 +- lib/models/popup.cjs | 14 +- lib/models/popup.js | 14 +- lib/models/webchat.cjs | 14 +- lib/models/webchat.js | 14 +- lib/models/whatsapp_widget.cjs | 15 +- lib/models/whatsapp_widget.js | 15 +- src/api/businesses.js | 8 +- src/controllers/popup_controller.js | 94 +++- src/hellotext.js | 300 +++++++++-- src/models/business.js | 45 +- src/models/popup.js | 17 +- src/models/webchat.js | 16 +- src/models/whatsapp_widget.js | 26 +- 29 files changed, 1728 insertions(+), 214 deletions(-) diff --git a/README.md b/README.md index b8a91adc..eb4096bb 100644 --- a/README.md +++ b/README.md @@ -118,14 +118,14 @@ Hellotext.initialize('HELLOTEXT_BUSINESS_ID', configurationOptions) #### Configuration Options -| Property | Description | Type | Default | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------- | -| 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 | -| 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 | An object that mounts a dashboard popup by id, or `false` to disable popup mounting. | Object \| false | null | -| 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 | -| whatsappWidget | An object that overrides the dashboard WhatsApp widget configuration, or `false` to disable automatic WhatsApp widget mounting. | Object \| false | Dashboard WhatsApp widget when configured | +| Property | Description | Type | Default | +| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------- | +| 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 | +| 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 | An object that mounts one dashboard popup by id, or `false` to disable automatic popup mounting. | Object \| false | null | +| 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 | +| whatsappWidget | An object that overrides the dashboard WhatsApp widget configuration, or `false` to disable automatic WhatsApp widget mounting. | Object \| false | Dashboard WhatsApp widget when configured | #### Popup @@ -137,6 +137,6 @@ Hellotext.initialize('HELLOTEXT_BUSINESS_ID', { }) ``` -When the popup is installed automatically from the dashboard, `Hellotext.initialize('HELLOTEXT_BUSINESS_ID')` mounts the configured popup without passing `popup.id` manually. +When popups are installed automatically from the dashboard, `Hellotext.initialize('HELLOTEXT_BUSINESS_ID')` mounts every active configured popup without passing `popup.id` manually. Only the first popup whose device and display rules match can be visible at a time; closing it allows the next eligible popup to appear. -The popup is rendered from the dashboard configuration, including steps, layout, bubble, colors, rules, coupon, and journey metadata. +Each popup is rendered from its dashboard configuration, including steps, layout, bubble, colors, rules, coupon, and journey metadata. Passing an explicit `popup.id` mounts only that popup. diff --git a/__tests__/controllers/popup_controller_test.js b/__tests__/controllers/popup_controller_test.js index 0857e2ec..5bbfcb48 100644 --- a/__tests__/controllers/popup_controller_test.js +++ b/__tests__/controllers/popup_controller_test.js @@ -9,7 +9,11 @@ describe('PopupController', () => { let controller let originalLocalStorage - const buildController = ({ hasBubble = true, rules = { operator: 'and', conditions: [] } } = {}) => { + const buildController = ({ + hasBubble = true, + id = 'popup-id', + rules = { operator: 'and', conditions: [] }, + } = {}) => { const element = document.createElement('article') const bubble = document.createElement('button') const dialog = document.createElement('section') @@ -81,7 +85,7 @@ describe('PopupController', () => { controller.hasBubbleValue = hasBubble controller.captureValue = { capture_id: 'capture-id' } controller.deviceValue = 'all' - controller.idValue = 'popup-id' + controller.idValue = id controller.rulesValue = rules return { @@ -121,6 +125,8 @@ describe('PopupController', () => { afterEach(() => { jest.useRealTimers() jest.restoreAllMocks() + PopupController.controllers.clear() + PopupController.displayOwner = undefined Object.defineProperty(window, 'localStorage', { value: originalLocalStorage, configurable: true, @@ -145,6 +151,70 @@ describe('PopupController', () => { expect(localStorage.getItem('hellotext:popup:popup-id:viewed')).toBe('true') }) + it('shows only the first eligible popup and releases the surface when it closes', () => { + const first = buildController({ hasBubble: false, id: 'first-popup' }) + const firstController = controller + const second = buildController({ hasBubble: false, id: 'second-popup' }) + const secondController = controller + + firstController.connect() + secondController.connect() + + expect(first.dialog.hidden).toBe(false) + expect(second.element.hidden).toBe(true) + + firstController.close() + + expect(first.element.hidden).toBe(true) + expect(second.dialog.hidden).toBe(false) + }) + + it('releases the next eligible popup when a bubble popup closes', () => { + const first = buildController({ id: 'first-popup' }) + const firstController = controller + const second = buildController({ hasBubble: false, id: 'second-popup' }) + const secondController = controller + + firstController.connect() + secondController.connect() + + expect(first.bubble.hidden).toBe(false) + expect(second.element.hidden).toBe(true) + + firstController.close() + + expect(first.element.hidden).toBe(true) + expect(second.dialog.hidden).toBe(false) + }) + + it('allows the next popup to display when the first popup does not match the device', () => { + const first = buildController({ hasBubble: false, id: 'mobile-popup' }) + const firstController = controller + firstController.deviceValue = 'mobile' + const second = buildController({ hasBubble: false, id: 'desktop-popup' }) + const secondController = controller + secondController.deviceValue = 'desktop' + + firstController.connect() + secondController.connect() + + expect(first.element.hidden).toBe(true) + expect(second.dialog.hidden).toBe(false) + }) + + it('releases the next eligible popup when the display owner disconnects', () => { + const first = buildController({ hasBubble: false, id: 'first-popup' }) + const firstController = controller + const second = buildController({ hasBubble: false, id: 'second-popup' }) + const secondController = controller + + firstController.connect() + secondController.connect() + firstController.disconnect() + + expect(second.dialog.hidden).toBe(false) + }) + it('validates the current step before moving to the next one', async () => { const { stepOne, stepTwo, emailInput } = buildController({ hasBubble: false }) diff --git a/__tests__/hellotext_test.js b/__tests__/hellotext_test.js index 7a3ce90d..46a345a2 100644 --- a/__tests__/hellotext_test.js +++ b/__tests__/hellotext_test.js @@ -1,7 +1,7 @@ import Hellotext from "../src/hellotext"; import API from "../src/api"; import { Configuration } from "../src/core"; -import { Popup, Session, Webchat, WhatsAppWidget } from "../src/models"; +import { Business, Popup, Session, Webchat, WhatsAppWidget } from "../src/models"; const getCookieValue = name => document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() @@ -30,6 +30,24 @@ const mockBusinessFetch = (business = defaultBusiness()) => { API.businesses.get = jest.fn().mockResolvedValue(businessResponse(business)) } +const deferred = () => { + let resolve + const promise = new Promise(result => { + resolve = result + }) + + return { promise, resolve } +} + +const waitFor = async predicate => { + for (let attempt = 0; attempt < 10; attempt += 1) { + if (predicate()) return + await new Promise(resolve => setTimeout(resolve, 0)) + } + + throw new Error('Timed out waiting for condition') +} + mockBusinessFetch() beforeEach(() => { @@ -75,6 +93,18 @@ describe("when initializing business metadata", () => { Configuration.whatsapp.appearance = {} Configuration.whatsapp.number = null Configuration.whatsapp.body = null + Configuration.apiRoot = 'https://api.hellotext.com/v1' + Configuration.actionCableUrl = 'wss://www.hellotext.com/cable' + Hellotext.popup = undefined + Hellotext.popups = [] + Hellotext.webchat = undefined + Hellotext.whatsapp = undefined + Hellotext.business = undefined + Hellotext.page = undefined + Hellotext.forms = undefined + Hellotext.query = undefined + Hellotext.initializationGeneration = 0 + Hellotext.initializationBaseline = undefined }) it("fetches public business data by default and stores it", async () => { @@ -303,6 +333,38 @@ describe("when initializing business metadata", () => { await Hellotext.initialize("xy76ks") expect(loadPopup).toHaveBeenCalledWith("dashboard-popup") + expect(Hellotext.popups).toHaveLength(1) + expect(Hellotext.popup).toEqual(Hellotext.popups[0]) + }) + + it("loads every unique dashboard popup when automatic popups are configured", async () => { + const firstPopup = { id: "first-popup" } + const secondPopup = { id: "second-popup" } + loadPopup.mockImplementation(async id => ({ id })) + mockBusinessFetch(defaultBusiness({ + popup: { id: "legacy-popup" }, + popups: [firstPopup, secondPopup, firstPopup], + })) + + await Hellotext.initialize("xy76ks") + + expect(loadPopup).toHaveBeenCalledTimes(2) + expect(loadPopup).toHaveBeenNthCalledWith(1, "first-popup") + expect(loadPopup).toHaveBeenNthCalledWith(2, "second-popup") + expect(Hellotext.popups).toEqual([firstPopup, secondPopup]) + expect(Hellotext.popup).toEqual(firstPopup) + }) + + it('falls back to the legacy dashboard popup when the popup list has no valid ids', async () => { + mockBusinessFetch(defaultBusiness({ + popup: { id: 'legacy-popup' }, + popups: [null, {}, { id: '' }], + })) + + await Hellotext.initialize('xy76ks') + + expect(loadPopup).toHaveBeenCalledTimes(1) + expect(loadPopup).toHaveBeenCalledWith('legacy-popup') }) it("uses the dashboard popup id with explicit local options", async () => { @@ -320,8 +382,29 @@ describe("when initializing business metadata", () => { expect(Configuration.popup.device).toEqual("desktop") }) + it("applies local popup options to every dashboard popup", async () => { + mockBusinessFetch(defaultBusiness({ + popups: [{ id: "first-popup" }, { id: "second-popup" }], + })) + + await Hellotext.initialize("xy76ks", { + popup: { + container: "#popup-container", + device: "desktop", + }, + }) + + expect(loadPopup).toHaveBeenCalledWith("first-popup") + expect(loadPopup).toHaveBeenCalledWith("second-popup") + expect(Configuration.popup.container).toEqual("#popup-container") + expect(Configuration.popup.device).toEqual("desktop") + }) + it("lets an explicit popup id override the dashboard popup id", async () => { - mockBusinessFetch(defaultBusiness({ popup: { id: "dashboard-popup" } })) + mockBusinessFetch(defaultBusiness({ + popup: { id: "dashboard-popup" }, + popups: [{ id: "first-dashboard-popup" }, { id: "second-dashboard-popup" }], + })) await Hellotext.initialize("xy76ks", { popup: { @@ -330,6 +413,7 @@ describe("when initializing business metadata", () => { }) expect(loadPopup).toHaveBeenCalledWith("explicit-popup") + expect(loadPopup).toHaveBeenCalledTimes(1) }) it("skips popup loading when popup is false", async () => { @@ -338,6 +422,383 @@ describe("when initializing business metadata", () => { await Hellotext.initialize("xy76ks", { popup: false }) expect(loadPopup).not.toHaveBeenCalled() + expect(Hellotext.popups).toEqual([]) + expect(Hellotext.popup).toBeUndefined() + }) + + it("clears previously loaded popups before reinitializing", async () => { + mockBusinessFetch(defaultBusiness({ popups: [{ id: "dashboard-popup" }] })) + await Hellotext.initialize("xy76ks") + + mockBusinessFetch(defaultBusiness()) + await Hellotext.initialize("xy76ks") + + expect(Hellotext.popups).toEqual([]) + expect(Hellotext.popup).toBeUndefined() + }) + + it('unmounts previously loaded popups before reinitializing', async () => { + const previousPopup = { unmount: jest.fn() } + Hellotext.popups = [previousPopup] + + await Hellotext.initialize('xy76ks', { popup: false }) + + expect(previousPopup.unmount).toHaveBeenCalledTimes(1) + expect(Hellotext.popups).toEqual([]) + }) + + it('keeps the existing popup mounted when reinitialization cannot hydrate the business', async () => { + const existingPopup = { unmount: jest.fn() } + Hellotext.popup = existingPopup + Hellotext.popups = [existingPopup] + API.businesses.get = jest.fn().mockRejectedValue(new Error('network error')) + + await Hellotext.initialize('xy76ks') + + expect(existingPopup.unmount).not.toHaveBeenCalled() + expect(Hellotext.popup).toBe(existingPopup) + expect(Hellotext.popups).toEqual([existingPopup]) + }) + + it('keeps the existing surfaces and configuration after a failed reinitialization', async () => { + const existingPopup = { unmount: jest.fn() } + const existingWebchat = { unmount: jest.fn() } + const existingWhatsApp = { unmount: jest.fn() } + Hellotext.popup = existingPopup + Hellotext.popups = [existingPopup] + Hellotext.webchat = existingWebchat + Hellotext.whatsapp = existingWhatsApp + Configuration.apiRoot = 'https://current.example/v1' + Configuration.actionCableUrl = 'wss://current.example/cable' + API.businesses.get = jest.fn().mockRejectedValue(new Error('network error')) + + await Hellotext.initialize('xy76ks', { apiRoot: 'https://next.example/v1' }) + + expect(existingPopup.unmount).not.toHaveBeenCalled() + expect(existingWebchat.unmount).not.toHaveBeenCalled() + expect(existingWhatsApp.unmount).not.toHaveBeenCalled() + expect(Hellotext.popups).toEqual([existingPopup]) + expect(Hellotext.webchat).toBe(existingWebchat) + expect(Hellotext.whatsapp).toBe(existingWhatsApp) + expect(Configuration.apiRoot).toBe('https://current.example/v1') + expect(Configuration.actionCableUrl).toBe('wss://current.example/cable') + }) + + it('restores the existing surfaces when loading a replacement surface fails', async () => { + const existingPopup = { unmount: jest.fn() } + const existingWebchat = { unmount: jest.fn() } + const existingWhatsApp = { unmount: jest.fn() } + Hellotext.popup = existingPopup + Hellotext.popups = [existingPopup] + Hellotext.webchat = existingWebchat + Hellotext.whatsapp = existingWhatsApp + mockBusinessFetch(defaultBusiness({ webchat: { id: 'replacement-webchat' } })) + loadWebchat.mockRejectedValueOnce(new Error('network error')) + + await expect(Hellotext.initialize('xy76ks')).rejects.toThrow('network error') + + expect(existingPopup.unmount).not.toHaveBeenCalled() + expect(existingWebchat.unmount).not.toHaveBeenCalled() + expect(existingWhatsApp.unmount).not.toHaveBeenCalled() + expect(Hellotext.popups).toEqual([existingPopup]) + expect(Hellotext.webchat).toBe(existingWebchat) + expect(Hellotext.whatsapp).toBe(existingWhatsApp) + }) + + it.each([ + ['popup', { popup: false }, 'popup'], + ['webchat', { webchat: false }, 'webchat'], + ['WhatsApp widget', { whatsappWidget: false }, 'whatsapp'], + ])('keeps unrelated surfaces mounted when a failed refresh explicitly disables %s', async (_, config, disabledSurface) => { + const existingPopup = { unmount: jest.fn() } + const existingWebchat = { unmount: jest.fn() } + const existingWhatsApp = { unmount: jest.fn() } + Hellotext.popup = existingPopup + Hellotext.popups = [existingPopup] + Hellotext.webchat = existingWebchat + Hellotext.whatsapp = existingWhatsApp + API.businesses.get = jest.fn().mockRejectedValue(new Error('network error')) + + await Hellotext.initialize('xy76ks', config) + + expect(existingPopup.unmount).toHaveBeenCalledTimes(disabledSurface === 'popup' ? 1 : 0) + expect(existingWebchat.unmount).toHaveBeenCalledTimes(disabledSurface === 'webchat' ? 1 : 0) + expect(existingWhatsApp.unmount).toHaveBeenCalledTimes(disabledSurface === 'whatsapp' ? 1 : 0) + expect(Hellotext.popup).toBe(disabledSurface === 'popup' ? undefined : existingPopup) + expect(Hellotext.webchat).toBe(disabledSurface === 'webchat' ? undefined : existingWebchat) + expect(Hellotext.whatsapp).toBe(disabledSurface === 'whatsapp' ? undefined : existingWhatsApp) + }) + + it('restores a disabled stable surface when an explicit replacement fails after hydration', async () => { + const existingPopup = { unmount: jest.fn() } + const existingWebchat = { unmount: jest.fn() } + Hellotext.popup = existingPopup + Hellotext.popups = [existingPopup] + Hellotext.webchat = existingWebchat + API.businesses.get = jest.fn().mockResolvedValue({ ok: false }) + loadWebchat.mockRejectedValueOnce(new Error('network error')) + + await expect( + Hellotext.initialize('xy76ks', { + popup: false, + webchat: { id: 'replacement-webchat' }, + }), + ).rejects.toThrow('network error') + + expect(existingPopup.unmount).not.toHaveBeenCalled() + expect(existingWebchat.unmount).not.toHaveBeenCalled() + expect(Hellotext.popup).toBe(existingPopup) + expect(Hellotext.webchat).toBe(existingWebchat) + }) + + it('keeps the latest initialization when an earlier popup load resolves late', async () => { + const firstPopupLoad = deferred() + const firstPopup = { id: 'first-popup', unmount: jest.fn() } + const secondPopup = { id: 'second-popup', unmount: jest.fn() } + loadPopup + .mockImplementationOnce(() => firstPopupLoad.promise) + .mockResolvedValueOnce(secondPopup) + API.businesses.get = jest + .fn() + .mockResolvedValueOnce(businessResponse(defaultBusiness({ popups: [{ id: 'first-popup' }] }))) + .mockResolvedValueOnce(businessResponse(defaultBusiness({ popups: [{ id: 'second-popup' }] }))) + + const firstInitialization = Hellotext.initialize('first-business') + await waitFor(() => loadPopup.mock.calls.length === 1) + const secondInitialization = Hellotext.initialize('second-business') + await secondInitialization + firstPopupLoad.resolve(firstPopup) + await firstInitialization + + expect(firstPopup.unmount).toHaveBeenCalledTimes(1) + expect(Hellotext.popups).toEqual([secondPopup]) + expect(Hellotext.popup).toBe(secondPopup) + }) + + it('unmounts a stale webchat after a newer initialization completes', async () => { + const firstWebchatLoad = deferred() + const firstWebchat = { unmount: jest.fn() } + const secondWebchat = { unmount: jest.fn() } + loadWebchat + .mockImplementationOnce(() => firstWebchatLoad.promise) + .mockResolvedValueOnce(secondWebchat) + API.businesses.get = jest + .fn() + .mockResolvedValueOnce( + businessResponse(defaultBusiness({ webchat: { id: 'first-webchat' } })), + ) + .mockResolvedValueOnce( + businessResponse(defaultBusiness({ webchat: { id: 'second-webchat' } })), + ) + + const firstInitialization = Hellotext.initialize('first-business') + await waitFor(() => loadWebchat.mock.calls.length === 1) + await Hellotext.initialize('second-business') + firstWebchatLoad.resolve(firstWebchat) + await firstInitialization + + expect(firstWebchat.unmount).toHaveBeenCalledTimes(1) + expect(Hellotext.webchat).toBe(secondWebchat) + }) + + it('unmounts a stale WhatsApp widget after a newer initialization completes', async () => { + const firstWhatsAppLoad = deferred() + const firstWhatsApp = { unmount: jest.fn() } + const secondWhatsApp = { unmount: jest.fn() } + loadWhatsAppWidget + .mockImplementationOnce(() => firstWhatsAppLoad.promise) + .mockResolvedValueOnce(secondWhatsApp) + API.businesses.get = jest + .fn() + .mockResolvedValueOnce( + businessResponse(defaultBusiness({ whatsapp: { id: 'first-whatsapp' } })), + ) + .mockResolvedValueOnce( + businessResponse(defaultBusiness({ whatsapp: { id: 'second-whatsapp' } })), + ) + + const firstInitialization = Hellotext.initialize('first-business') + await waitFor(() => loadWhatsAppWidget.mock.calls.length === 1) + await Hellotext.initialize('second-business') + firstWhatsAppLoad.resolve(firstWhatsApp) + await firstInitialization + + expect(firstWhatsApp.unmount).toHaveBeenCalledTimes(1) + expect(Hellotext.whatsapp).toBe(secondWhatsApp) + }) + + it('recomputes widget coexistence after replacing webchat and WhatsApp together', async () => { + const nextWebchatElement = document.createElement('div') + const nextWhatsAppElement = document.createElement('div') + nextWebchatElement.className = 'hellotext--webchat' + nextWhatsAppElement.className = 'hellotext--whatsapp-widget' + document.body.append(nextWebchatElement, nextWhatsAppElement) + + const markCoexistingWidgets = () => { + nextWebchatElement.classList.add('hellotext--with-whatsapp-widget') + nextWhatsAppElement.classList.add('hellotext--with-webchat') + } + const existingWebchat = { + unmount: jest.fn(() => nextWhatsAppElement.classList.remove('hellotext--with-webchat')), + } + const existingWhatsApp = { + unmount: jest.fn(() => + nextWebchatElement.classList.remove('hellotext--with-whatsapp-widget'), + ), + } + const nextWebchat = { unmount: jest.fn(), markCoexistingWidgets: jest.fn(markCoexistingWidgets) } + const nextWhatsApp = { unmount: jest.fn(), markCoexistingWidgets: jest.fn(markCoexistingWidgets) } + Hellotext.webchat = existingWebchat + Hellotext.whatsapp = existingWhatsApp + loadWebchat.mockResolvedValueOnce(nextWebchat) + loadWhatsAppWidget.mockResolvedValueOnce(nextWhatsApp) + mockBusinessFetch( + defaultBusiness({ + webchat: { id: 'replacement-webchat' }, + whatsapp: { id: 'replacement-whatsapp' }, + }), + ) + + await Hellotext.initialize('xy76ks') + + expect(existingWebchat.unmount).toHaveBeenCalledTimes(1) + expect(existingWhatsApp.unmount).toHaveBeenCalledTimes(1) + expect(nextWebchat.markCoexistingWidgets).toHaveBeenCalledTimes(1) + expect(nextWhatsApp.markCoexistingWidgets).toHaveBeenCalledTimes(1) + expect(nextWebchatElement.classList.contains('hellotext--with-whatsapp-widget')).toBe(true) + expect(nextWhatsAppElement.classList.contains('hellotext--with-webchat')).toBe(true) + + nextWebchatElement.remove() + nextWhatsAppElement.remove() + }) + + it('restores the stable runtime when a newer initialization fails during an older refresh', async () => { + const firstBusinessFetch = deferred() + const stableBusiness = { id: 'stable-business' } + const stablePopup = { unmount: jest.fn() } + Hellotext.business = stableBusiness + Hellotext.popup = stablePopup + Hellotext.popups = [stablePopup] + Configuration.apiRoot = 'https://stable.example/v1' + Configuration.actionCableUrl = 'wss://stable.example/cable' + API.businesses.get = jest + .fn() + .mockImplementationOnce(() => firstBusinessFetch.promise) + .mockResolvedValueOnce({ ok: false }) + + const firstInitialization = Hellotext.initialize('first-business', { + apiRoot: 'https://first.example/v1', + }) + await waitFor(() => API.businesses.get.mock.calls.length === 1) + expect(Configuration.apiRoot).toBe('https://stable.example/v1') + + await Hellotext.initialize('second-business', { apiRoot: 'https://second.example/v1' }) + firstBusinessFetch.resolve(businessResponse(defaultBusiness({ id: 'first-business' }))) + await firstInitialization + + expect(stablePopup.unmount).not.toHaveBeenCalled() + expect(Hellotext.business).toBe(stableBusiness) + expect(Hellotext.popups).toEqual([stablePopup]) + expect(Configuration.apiRoot).toBe('https://stable.example/v1') + expect(Configuration.actionCableUrl).toBe('wss://stable.example/cable') + }) + + it('does not leave a stylesheet from a stale business hydration', async () => { + const firstBusinessFetch = deferred() + API.businesses.get = jest + .fn() + .mockImplementationOnce(() => firstBusinessFetch.promise) + .mockResolvedValueOnce( + businessResponse( + defaultBusiness({ + id: 'second-business', + style_url: 'https://example.com/second.css', + }), + ), + ) + + const firstInitialization = Hellotext.initialize('first-business', { + apiRoot: 'https://first.example/v1', + }) + await waitFor(() => API.businesses.get.mock.calls.length === 1) + await Hellotext.initialize('second-business', { apiRoot: 'https://second.example/v1' }) + firstBusinessFetch.resolve( + businessResponse( + defaultBusiness({ + id: 'first-business', + style_url: 'https://example.com/first.css', + }), + ), + ) + await firstInitialization + + expect(Array.from(document.querySelectorAll('link[data-hellotext-stylesheet]'))).toHaveLength(1) + expect(Business.latestStylesheet.href).toContain('/second.css') + expect(document.head.innerHTML).not.toContain('/first.css') + }) + + it('removes a staged stylesheet when loading a replacement surface fails', async () => { + const stableBusiness = new Business('stable-business') + stableBusiness.setData(defaultBusiness({ style_url: 'https://example.com/stable.css' })) + const stablePopup = { unmount: jest.fn() } + Hellotext.business = stableBusiness + Hellotext.popup = stablePopup + Hellotext.popups = [stablePopup] + mockBusinessFetch( + defaultBusiness({ + style_url: 'https://example.com/staged.css', + webchat: { id: 'replacement-webchat' }, + }), + ) + loadWebchat.mockRejectedValueOnce(new Error('network error')) + + await expect(Hellotext.initialize('xy76ks')).rejects.toThrow('network error') + + expect(Business.latestStylesheet.href).toContain('/stable.css') + expect(document.head.innerHTML).not.toContain('/staged.css') + expect(Hellotext.business).toBe(stableBusiness) + expect(Hellotext.popup).toBe(stablePopup) + }) + + it('removes a stale stylesheet injected before a newer initialization commits', async () => { + const firstWebchatLoad = deferred() + const firstWebchat = { unmount: jest.fn() } + const secondWebchat = { unmount: jest.fn() } + loadWebchat + .mockImplementationOnce(() => firstWebchatLoad.promise) + .mockResolvedValueOnce(secondWebchat) + API.businesses.get = jest + .fn() + .mockResolvedValueOnce( + businessResponse( + defaultBusiness({ + style_url: 'https://example.com/first.css', + webchat: { id: 'first-webchat' }, + }), + ), + ) + .mockResolvedValueOnce( + businessResponse( + defaultBusiness({ + style_url: 'https://example.com/second.css', + webchat: { id: 'second-webchat' }, + }), + ), + ) + + const firstInitialization = Hellotext.initialize('first-business') + await waitFor(() => loadWebchat.mock.calls.length === 1) + expect(Business.latestStylesheet.href).toContain('/first.css') + + await Hellotext.initialize('second-business') + expect(Business.latestStylesheet.href).toContain('/second.css') + + firstWebchatLoad.resolve(firstWebchat) + await firstInitialization + + expect(firstWebchat.unmount).toHaveBeenCalledTimes(1) + expect(Business.latestStylesheet.href).toContain('/second.css') + expect(document.head.innerHTML).not.toContain('/first.css') }) it("does not break initialization when business fetch rejects", async () => { diff --git a/__tests__/models/popup_test.js b/__tests__/models/popup_test.js index 59df8c1a..dd9a129f 100644 --- a/__tests__/models/popup_test.js +++ b/__tests__/models/popup_test.js @@ -103,4 +103,17 @@ describe('Popup', () => { }) }) }) + + it('removes its mounted popup HTML when unmounted', async () => { + createStylesheet() + const article = document.createElement('article') + API.popups.get.mockResolvedValue(article) + + const popup = await Popup.load('popup-id') + await popup.rendered + popup.unmount() + + expect(document.querySelector('#popup-container article')).toBeNull() + expect(popup.mounted).toBe(false) + }) }) diff --git a/__tests__/models/webchat_test.js b/__tests__/models/webchat_test.js index f958a4b7..cdba145e 100644 --- a/__tests__/models/webchat_test.js +++ b/__tests__/models/webchat_test.js @@ -122,6 +122,20 @@ describe('Webchat', () => { expect(webchat.mounted).toBe(true) }) + it('does not append its HTML after it is unmounted during stylesheet loading', async () => { + const linkTag = createStylesheet({ loaded: false }) + const article = document.createElement('article') + API.webchats.get.mockResolvedValue(article) + + const webchat = await Webchat.load('webchat-id') + webchat.unmount() + markStylesheetLoaded(linkTag) + await webchat.rendered + + expect(document.querySelector('#webchat-container article')).toBeNull() + expect(webchat.mounted).toBe(false) + }) + it('does not append the webchat HTML when the stylesheet fails', async () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}) const linkTag = createStylesheet({ loaded: false }) diff --git a/__tests__/models/whatsapp_widget_test.js b/__tests__/models/whatsapp_widget_test.js index b78a1477..cfcf355a 100644 --- a/__tests__/models/whatsapp_widget_test.js +++ b/__tests__/models/whatsapp_widget_test.js @@ -63,6 +63,20 @@ describe('WhatsAppWidget', () => { }) }) + it('does not append its HTML after it is unmounted during stylesheet loading', async () => { + const linkTag = createStylesheet({ loaded: false }) + const article = document.createElement('article') + API.whatsappWidgets.get.mockResolvedValue(article) + + const widget = await WhatsAppWidget.load('widget-id') + widget.unmount() + markStylesheetLoaded(linkTag) + await widget.rendered + + expect(document.querySelector('#whatsapp-container article')).toBeNull() + expect(widget.mounted).toBe(false) + }) + it('marks itself when webchat is already mounted', () => { createStylesheet() document.body.insertAdjacentHTML('beforeend', '
') diff --git a/dist/hellotext.js b/dist/hellotext.js index ac4e3451..faee250d 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,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class O{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,n){T(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){T(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new O}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 k{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 S{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new O}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new S(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new k(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new O}start(){this.tokenListObserver||(this.tokenListObserver=new S(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new O,this.outletElementsByName=new O,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 O;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,N=(()=>{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 D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=N(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class q{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class z{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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class U{constructor(e,t,n,r){this.targets=new q(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),this.outlets=new z(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 H{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&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 H(this.element,this.schema,this),this.scopesByIdentifier=new O,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 D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new W(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>ws});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function O(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function N(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=N(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=N(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(q).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=N(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function U(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=U(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=U(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=U(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&W(e.prototype,null),t&&W(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=T.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=z.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=T,Z.popup=L,Z.webchat=z,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(Fe({session:Ai.session},e))});return new ke(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&qe(e.prototype,null),t&&qe(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const He=Ue;function We(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $e(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return et(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:Ai.headers}),r=yield n.json();return Ai.business.data||(Ai.business.setData(r.business),Ai.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){tt(o,r,i,a,s,"next",e)}function s(e){tt(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&nt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ot=it;function at(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function st(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){at(o,r,i,a,s,"next",e)}function s(e){at(o,r,i,a,s,"throw",e)}a(void 0)})}}function lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:Ai.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:Ai.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){mt(o,r,i,a,s,"next",e)}function s(e){mt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&yt(e.prototype,null),t&&yt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const bt=vt;function wt(e,t){for(var n=0;ne.href===t);if(n)return n.setAttribute(Pt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(Pt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&Et(e.prototype,t),n&&Et(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return It(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),Mt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(Mt.get("hello_utm"))||{}}catch(e){return{}}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new Dt,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Rt(t.prototype,n),r&&Rt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Vt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Bt;zt(this,Kt)[Kt]=e,zt(this,$t)[$t]=new ye,this.session=zt(this,$t)[$t].session||Z.session||Mt.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Vt(e.prototype,null),t&&Vt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(Ai.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const sn=Object.entries,ln=Object.setPrototypeOf,cn=Object.isFrozen,un=Object.getPrototypeOf,hn=Object.getOwnPropertyDescriptor;let pn=Object.freeze,dn=Object.seal,fn=Object.create,mn="undefined"!=typeof Reflect&&Reflect,yn=mn.apply,gn=mn.construct;pn||(pn=function(e){return e}),dn||(dn=function(e){return e}),yn||(yn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:kn;if(ln&&ln(e,null),!xn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(cn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function qn(e){for(let t=0;t/g),rr=dn(/\${[\w\W]*/g),ir=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),or=dn(/^aria-[\-\w]+$/),ar=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sr=dn(/^(?:\w+script|data):/i),lr=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cr=dn(/^html$/i),ur=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),hr=dn(/<[/\w!]/g),pr=dn(/<[/\w]/g),dr=dn(/<\/no(script|embed|frames)/i),fr=dn(/\/>/i),mr=function(){return"undefined"==typeof window?null:window},yr=function(e,t,n,r){return Ln(e,t)&&xn(e[t])?Vn(r.base?zn(r.base):{},e[t],r.transform):n};var gr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=Un(p,"cloneNode"),f=Un(p,"remove"),m=Un(p,"nextSibling"),y=Un(p,"childNodes"),g=Un(p,"parentNode"),v=Un(p,"shadowRoot"),b=Un(p,"attributes"),w=s&&s.prototype?Un(s.prototype,"nodeType"):null,T=s&&s.prototype?Un(s.prototype,"nodeName"):null,O=s&&s.prototype?Un(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,k,S="",E=!1,C=0;const P=function(){if(C>0)throw Rn('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,N=i.importNode;let D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof sn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=tr,F=nr,B=rr,V=ir,q=or,z=sr,U=lr,H=ur;let W=ar,$=null;const K=Vn({},[...Hn,...Wn,...$n,...Gn,...Yn]);let G=null;const J=Vn({},[...Xn,...Zn,...Qn,...er]);let Y=Object.seal(fn(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}})),X=null,Z=null;const Q=Object.seal(fn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Te=Vn({},["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 Oe=null;const xe=Vn({},["audio","video","img","source","image","track"]);let ke=null;const Se=Vn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Vn({},[Ee,Ce,Pe],Sn),Ie=pn(["mi","mo","mn","ms","mtext"]);let Le=Vn({},Ie);const Ne=pn(["annotation-xml"]);let De=Vn({},Ne);const Re=Vn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,qe=null;const ze=r.createElement("form"),Ue=function(e){return e instanceof RegExp||e instanceof Function},He=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(qe&&qe===e)return;e&&"object"==typeof e||(e={}),e=zn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?Sn:kn,$=yr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=yr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=yr(e,"ALLOWED_NAMESPACES",Me,{transform:Sn}),ke=yr(e,"ADD_URI_SAFE_ATTR",Se,{transform:Ve,base:Se}),Oe=yr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=yr(e,"FORBID_CONTENTS",Te,{transform:Ve}),X=yr(e,"FORBID_TAGS",zn({}),{transform:Ve}),Z=yr(e,"FORBID_ATTR",zn({}),{transform:Ve}),be=!!Ln(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?zn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,W=function(e){try{return Dn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:ar,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=Ln(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?zn(e.MATHML_TEXT_INTEGRATION_POINTS):Vn({},Ie),De=Ln(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?zn(e.HTML_INTEGRATION_POINTS):Vn({},Ne);const t=Ln(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?zn(e.CUSTOM_ELEMENT_HANDLING):fn(null);if(Y=fn(null),Ln(t,"tagNameCheck")&&Ue(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Ln(t,"attributeNameCheck")&&Ue(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Ln(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),dn(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Vn({},Yn),G=fn(null),!0===be.html&&(Vn($,Hn),Vn(G,Xn)),!0===be.svg&&(Vn($,Wn),Vn(G,Zn),Vn(G,er)),!0===be.svgFilters&&(Vn($,$n),Vn(G,Zn),Vn(G,er)),!0===be.mathMl&&(Vn($,Gn),Vn(G,Qn),Vn(G,er))),Q.tagCheck=null,Q.attributeCheck=null,Ln(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:xn(e.ADD_TAGS)&&($===K&&($=zn($)),Vn($,e.ADD_TAGS,Ve))),Ln(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:xn(e.ADD_ATTR)&&(G===J&&(G=zn(G)),Vn(G,e.ADD_ATTR,Ve))),Ln(e,"ADD_URI_SAFE_ATTR")&&xn(e.ADD_URI_SAFE_ATTR)&&Vn(ke,e.ADD_URI_SAFE_ATTR,Ve),Ln(e,"FORBID_CONTENTS")&&xn(e.FORBID_CONTENTS)&&(we===Te&&(we=zn(we)),Vn(we,e.FORBID_CONTENTS,Ve)),Ln(e,"ADD_FORBID_CONTENTS")&&xn(e.ADD_FORBID_CONTENTS)&&(we===Te&&(we=zn(we)),Vn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Vn($,["html","head","body"]),$.table&&(Vn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{S=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,S=""):(void 0===x&&(E||(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=k),x&&"string"==typeof S&&(S=A("")));pn&&pn(e),qe=e},We=Vn({},[...Wn,...$n,...Kn]),$e=Vn({},[...Gn,...Jn]),Ke=function(e){Tn(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Rn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];vn(t,t=>{Tn(e,t)}),vn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{Tn(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Tn(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=En(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?S:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=O?O(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=Cn(e,R," "),e=Cn(e,F," "),Cn(e,B," ")},tt=function(e){var t;e.normalize();const n=O?O(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&vn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=T?T(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&vn(e,e=>{e.call(n,t,r,qe)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?zn(t):t},st=function(e,t){if(ot(D.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(T?T(e):e.nodeName);if($=at(D.uponSanitizeElement,$,K,le),ot(D.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&Dn(hr,e.textContent)&&Dn(hr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!Dn(pr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(D.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=kn(e.tagName),r=kn(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(We[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&De[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!De[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!We[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&Dn(dr,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(Tn(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(D.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in ze))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&Dn(V,t));else if(ee&&Dn(q,t));else if(i){if(ke[t]);else if(Dn(W,Cn(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Pn(n,"data:")||!Oe[e])if(ne&&!Dn(z,Cn(n,U,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Dn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Dn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Vn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[kn(e)]&&Dn(H,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):wn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(D.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(D.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:An(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(D.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Pn(h,ye)||(Je(a,e),h=ye+h),oe&&Dn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&En(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&Dn(fr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(D.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(D.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(D.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=T?T(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return jn(e);case"boolean":return _n(e);case"bigint":return Mn?Mn(e):"0";case"symbol":return In?In(e):"Symbol()";case"undefined":default:return Nn(e);case"function":case"object":{if(null===e)return Nn(e);const t=e,n=Un(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Nn(e)}return Nn(e)}}}(e)))throw Rn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):He(t),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&($=zn($)),D.uponSanitizeAttribute.length>0&&(G=zn(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&Dn(pr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(T?T(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=T?T(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Rn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Rn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?S:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),vn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return vn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=N.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Dn(cr,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){He(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){qe=null,se=!1,le=null,ce=null,x=k,S=""},n.isValidAttribute=function(e,t,n){qe||He({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ln(D,e)&&Tn(D[e],t)},n.removeHook=function(e,t){if(Ln(D,e)){if(void 0!==t){const n=bn(D[e],t);return-1===n?void 0:On(D[e],n,1)[0]}return wn(D[e])}},n.removeHooks=function(e){Ln(D,e)&&(D[e]=[])},n.removeAllHooks=function(){D={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),vr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},br={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function wr(e,t){var n=gr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function Tr(e,t){e.replaceChildren(function(e){return wr(e,vr)}(t))}function Or(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xr(e,t,n){return(t=Er(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Sr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,jr,{value:Mr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),Ai.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),Ai.business.features.white_label||this.element.prepend(rn.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){kr(o,r,i,a,s,"next",e)}function s(e){kr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=Cr(this,jr)[jr]("[data-form-header]","header");Tr(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=Cr(this,jr)[jr]("[data-form-inputs]","main");e.map(e=>Xt.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)}},{key:"buildButton",value:function(e){var t=Cr(this,jr)[jr]("[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)}},{key:"buildFooter",value:function(e){var t=Cr(this,jr)[jr]("[data-form-footer]","footer");Tr(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),Ai.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&Sr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Mr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function Ir(e){var t="function"==typeof Map?new Map:void 0;return Ir=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(Lr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Nr(i,n.prototype),i}(e,arguments,Dr(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Nr(n,e)},Ir(e)}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Lr=function(){return!!e})()}function Nr(e,t){return Nr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Nr(e,t)}function Dr(e){return Dr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Dr(e)}var Rr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Dr(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Lr()?Reflect.construct(t,n||[],Dr(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Ir(Error));function Fr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Br(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(Ai.notInitialized)throw new Rr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,Ur)[Ur];if(0!==e.length){var t=e.map(e=>De.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>Ai.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Fr(o,r,i,a,s,"next",e)}function s(e){Fr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(Ai.business.data||(Ai.business.setData(e.business),Ai.business.setLocale(j.toString())),Ai.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 _r(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Br(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Wr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function $r(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Kr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$r(o,r,i,a,s,"next",e)}function s(e){$r(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gr(e,t){for(var n=0;nyi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=yi(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function gi(e,t){var n=yi(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function vi(){return(vi=pi(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var bi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=pi(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return vi.apply(this,arguments)}(gi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&ui(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function wi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{};this.business=new At(e),this.page=new Bt,Z.assign(t),Gt.initialize(this.page),this.forms=new Hr,this.query=new ye;var n=yield this.business.hydrate(),r=!1!==t.popup&&this.mergePopupConfig(n&&n.popup||{},t.popup||{}),i=!1!==t.webchat&&this.mergeWebchatConfig(n&&n.webchat||{},t.webchat||{}),o=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(n&&n.whatsapp||{},t.whatsappWidget||{}),a=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");Z.webchat.behaviourOverride=a,i&&i.id&&(Z.webchat.assign(i),this.webchat=yield Yr.load(i.id)),o&&o.id&&(Z.whatsapp.assign(o),this.whatsapp=yield ti.load(o.id)),r&&r.id&&(Z.popup.assign(r),this.popup=yield ai.load(r.id)),"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}),function(e){return i.apply(this,arguments)})},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=Oi({},e);return Object.entries(t).forEach(e=>{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return wi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Si(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Rr;var n=Oi(Oi({},t&&t.headers||{}),this.headers),r=Oi(Oi({},ci.identificationData),t.user_parameters||{}),i=t&&t.url?new Bt(t.url):this.page,o=Oi(Oi({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield xt.events.create({headers:n,body:o,keepalive:Ot(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Si(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield bi.generate(this.session,e,n);if(bi.matches(ci.fingerprint,r))return new ke(!0,{json:(t=Si(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield xt.identifications.create(Oi({user_id:e},n));return i.succeeded&&ci.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ci.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Gt.session}},{key:"isInitialized",get:function(){return void 0!==Gt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Rr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&Ei(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Pi.eventEmitter=new ce,Pi.forms=void 0,Pi.business=void 0,Pi.popup=void 0,Pi.webchat=void 0,Pi.whatsapp=void 0;const Ai=Pi;function ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function _i(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(Ai.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){ji(o,n,r,a,s,"next",e)}function s(e){ji(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=Ai.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&_i(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Bi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Vi(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&zi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function Ji(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Yi(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Ji(o,r,i,a,s,"next",e)}function s(e){Ji(o,r,i,a,s,"throw",e)}a(void 0)})}}function Xi(e,t){for(var n=0;n{e.disabled=!0});var t=yield xt.popups.submit(this.idValue,this.submissionPayload());if(this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed)yield this.handleSubmissionError(t);else{try{var n=yield t.json();this.submissionId=n.id,this.submissionVerificationState=n.verification_state,this.submissionActionToken=n.action_token,this.submissionDeliveryStatus=n.delivery_status,this.submissionDeliveryChannel=n.delivery_channel,this.submissionDestination=n.destination}catch(e){this.submissionId=null}this.showCompleted()}}else this.showErrorMessages(this.currentStepInputs)}),function(e){return s.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){this.matchesDevice()&&this.rulesWithoutScrollPass()&&(!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.configureCompletionActions(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.completedIdentity;if(e){var t={destination:e.value,channel:this.submissionDeliveryChannel||e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"configureCompletionActions",value:function(){var e;if("not_required"===this.submissionDeliveryStatus)return this.renderNoDeliveryCopy(),void(null===(e=this.completedTarget.querySelector("[data-delivery-actions]"))||void 0===e||e.setAttribute("hidden",""));var t=this.completedIdentity;t&&(this.hasChangeDestinationButtonTarget&&(this.changeDestinationButtonTarget.textContent=this.changeDestinationButtonTarget.dataset["".concat(t.kind,"Label")],this.showElement(this.changeDestinationButtonTarget)),this.submissionId&&this.submissionActionToken&&"queued"===this.submissionDeliveryStatus&&"unverified"===this.submissionVerificationState&&this.hasResendButtonTarget&&(this.showElement(this.resendButtonTarget),this.startResendCooldown(60)))}},{key:"resend",value:(a=Yi(function*(e){if(e&&e.preventDefault(),this.submissionId&&this.submissionActionToken&&!this.resendPending&&!this.resendCooldownActive&&this.completedIdentity){this.resendPending=!0,this.resendButtonTarget.disabled=!0;try{var t,n=yield xt.popups.resend(this.idValue,this.submissionId,this.submissionActionToken),r=Number(null===(t=n.data.headers)||void 0===t?void 0:t.get("Retry-After"))||60;n.succeeded||429===n.data.status?this.startResendCooldown(r):this.resendButtonTarget.disabled=!1}catch(e){this.resendButtonTarget.disabled=!1}finally{this.resendPending=!1}}}),function(e){return a.apply(this,arguments)})},{key:"changeDestination",value:(o=Yi(function*(e){var t;e&&e.preventDefault();var n=null===(t=this.completedIdentity)||void 0===t?void 0:t.input;if(n){var r=this.stepTargets.findIndex(e=>e.dataset.stepId===n.dataset.popupStepId);r<0||(this.stopResendCooldown(),this.submissionId=null,this.submissionActionToken=null,this.submissionVerificationState=null,this.submissionDeliveryStatus=null,this.submissionDeliveryChannel=null,this.submissionDestination=null,this.showStep(r),n.focus())}}),function(e){return o.apply(this,arguments)})},{key:"startResendCooldown",value:function(e){this.stopResendCooldown(),this.resendCooldownEndsAt=Date.now()+1e3*Math.max(e,1),this.updateResendCountdown(),this.resendTimer=window.setInterval(()=>this.updateResendCountdown(),1e3)}},{key:"stopResendCooldown",value:function(){this.resendTimer&&window.clearInterval(this.resendTimer),this.resendTimer=null,this.resendCooldownEndsAt=null}},{key:"updateResendCountdown",value:function(){var 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);var t="".concat(Math.floor(e/60),":").concat(String(e%60).padStart(2,"0")),n=this.resendButtonTarget.dataset.countdownLabel||"".concat(this.resendLabel," %{time}");this.resendButtonTarget.textContent=n.replace("%{time}",t),this.resendButtonTarget.disabled=!0}},{key:"resendCooldownActive",get:function(){return this.resendCooldownEndsAt>Date.now()}},{key:"completionIdentity",get:function(){return this.identityInputs.map(e=>({input:e,kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value)}},{key:"completedIdentity",get:function(){if(this.submissionDestination&&this.submissionDeliveryChannel){var e="email"===this.submissionDeliveryChannel?"email":"phone";return{input:this.identityInputs.find(t=>t.dataset.popupFieldKind===e),kind:e,value:this.submissionDestination}}return this.completionIdentity}},{key:"renderNoDeliveryCopy",value:function(){var e=this.completedTarget.querySelector(".hellotext--popup__completion-headline"),t=this.completedTarget.querySelector(".hellotext--popup__completion-description");if(e&&this.completedTarget.dataset.notRequiredHeadline){e.innerHTML="";var n=document.createElement("h4"),r=document.createElement("strong");r.textContent=this.completedTarget.dataset.notRequiredHeadline,n.appendChild(r),e.appendChild(n)}t&&(t.textContent=this.completedTarget.dataset.notRequiredDescription||"")}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Yi(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Xi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l}(g.xI);ro.targets=["bubble","dialog","step","completed","input","submitButton","resendButton","changeDestinationButton"],ro.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const io=["start","end"],oo=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+io[0],t+"-"+io[1]),[]),ao=Math.min,so=Math.max,lo=Math.round,co=Math.floor,uo=e=>({x:e,y:e}),ho={left:"right",right:"left",bottom:"top",top:"bottom"};function po(e,t){return"function"==typeof e?e(t):e}function fo(e){return e.split("-")[0]}function mo(e){return e.split("-")[1]}function yo(e){return"x"===e?"y":"x"}function go(e){return"y"===e?"height":"width"}function vo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function bo(e){return yo(vo(e))}function wo(e,t,n){void 0===n&&(n=!1);const r=mo(e),i=bo(e),o=go(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Eo(a)),[a,Eo(a)]}function To(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Oo=["left","right"],xo=["right","left"],ko=["top","bottom"],So=["bottom","top"];function Eo(e){const t=fo(e);return ho[t]+e.slice(t.length)}function Co(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Po(e,t,n){let{reference:r,floating:i}=e;const o=vo(t),a=bo(t),s=go(a),l=fo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=mo(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function Ao(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=po(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=Co(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Co(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const jo=new Set(["left","top"]);function _o(){return"undefined"!=typeof window}function Mo(e){return No(e)?(e.nodeName||"").toLowerCase():"#document"}function Io(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Lo(e){var t;return null==(t=(No(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function No(e){return!!_o()&&(e instanceof Node||e instanceof Io(e).Node)}function Do(e){return!!_o()&&(e instanceof Element||e instanceof Io(e).Element)}function Ro(e){return!!_o()&&(e instanceof HTMLElement||e instanceof Io(e).HTMLElement)}function Fo(e){return!(!_o()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Io(e).ShadowRoot)}function Bo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Jo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function Vo(e){return/^(table|td|th)$/.test(Mo(e))}function qo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const zo=/transform|translate|scale|rotate|perspective|filter/,Uo=/paint|layout|strict|content/,Ho=e=>!!e&&"none"!==e;let Wo;function $o(e){const t=Do(e)?Jo(e):e;return Ho(t.transform)||Ho(t.translate)||Ho(t.scale)||Ho(t.rotate)||Ho(t.perspective)||!Ko()&&(Ho(t.backdropFilter)||Ho(t.filter))||zo.test(t.willChange||"")||Uo.test(t.contain||"")}function Ko(){return null==Wo&&(Wo="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Wo}function Go(e){return/^(html|body|#document)$/.test(Mo(e))}function Jo(e){return Io(e).getComputedStyle(e)}function Yo(e){return Do(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xo(e){if("html"===Mo(e))return e;const t=e.assignedSlot||e.parentNode||Fo(e)&&e.host||Lo(e);return Fo(t)?t.host:t}function Zo(e){const t=Xo(e);return Go(t)?(e.ownerDocument||e).body:Ro(t)&&Bo(t)?t:Zo(t)}function Qo(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Zo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Io(i);if(o){const e=ea(a);return t.concat(a,a.visualViewport||[],Bo(i)?i:[],e&&n?Qo(e):[])}return t.concat(i,Qo(i,[],n))}function ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ta(e){const t=Jo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ro(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=lo(n)!==o||lo(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function na(e){return Do(e)?e:e.contextElement}function ra(e){const t=na(e);if(!Ro(t))return uo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=ta(t);let a=(o?lo(n.width):n.width)/r,s=(o?lo(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const ia=uo(0);function oa(e){const t=Io(e);return Ko()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ia}function aa(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=na(e);let a=uo(1);t&&(r?Do(r)&&(a=ra(r)):a=ra(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===Io(e)}(o,n,r)?oa(o):uo(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=Io(o),t=Do(r)?Io(r):r;let n=e,i=ea(n);for(;i&&t!==n;){const e=ra(i),t=i.getBoundingClientRect(),r=Jo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=Io(i),i=ea(n)}}return Co({width:u,height:h,x:l,y:c})}function sa(e,t){const n=Yo(e).scrollLeft;return t?t.left+n:aa(Lo(e)).left+n}function la(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-sa(e,n),y:n.top+t.scrollTop}}function ca(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=Io(e),o=Lo(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Ko()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(sa(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Yo(e),n=e.ownerDocument.body,r=so(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=so(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+sa(e);const a=-t.scrollTop;return"rtl"===Jo(n).direction&&(o+=so(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(Lo(e));else if(Do(t))r=function(e,t){const n=aa(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ra(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=oa(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Co(r)}function ua(e,t,n){const r=Ro(t),i=Lo(t),o="fixed"===n,a=aa(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=uo(0);if((r||!o)&&(("body"!==Mo(t)||Bo(i))&&(s=Yo(t)),r)){const e=aa(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=sa(i));const c=!i||r||o?uo(0):la(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function ha(e){return"static"===Jo(e).position}function pa(e,t){if(!Ro(e)||"fixed"===Jo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Lo(e)===n&&(n=n.ownerDocument.body),n}function da(e,t){const n=Io(e);if(qo(e))return n;if(!Ro(e)){let t=Xo(e);for(;t&&!Go(t);){if(Do(t)&&!ha(t))return t;t=Xo(t)}return n}let r=pa(e,t);for(;r&&Vo(r)&&ha(r);)r=pa(r,t);return r&&Go(r)&&ha(r)&&!$o(r)?n:r||function(e){let t=Xo(e);for(;Ro(t)&&!Go(t);){if($o(t))return t;if(qo(t))return null;t=Xo(t)}return null}(e)||n}const fa={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Lo(r),s=!!t&&qo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=uo(1);const u=uo(0),h=Ro(r);if((h||!o)&&(("body"!==Mo(r)||Bo(a))&&(l=Yo(r)),h)){const e=aa(r);c=ra(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?uo(0):la(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:Lo,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?qo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=Qo(e,[],!1).filter(e=>Do(e)&&"body"!==Mo(e)),i=null;const o="fixed"===Jo(e).position;let a=o?Xo(e):e;for(;Do(a)&&!Go(a);){const e=Jo(a),t=$o(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Xo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=ca(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;emo(t)===e),...n.filter(t=>mo(t)!==e)]:n.filter(e=>fo(e)===e)).filter(n=>!e||mo(n)===e||!!t&&To(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=wo(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[fo(g)],v[b[0]],v[b[1]]],T=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],O=m[y+1];if(O)return{data:{index:y+1,overflows:T},reset:{placement:O}};const x=T.map(e=>{const t=mo(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),k=(null==(i=x.filter(e=>e[2].slice(0,mo(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return k!==s?{data:{index:y+1,overflows:T},reset:{placement:k}}:{}}}},va=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=po(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=vo(i),d=yo(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],so(n,ao(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},ba=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=po(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=fo(i),v=vo(s),b=fo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),T=p||(b||!m?[Eo(s)]:function(e){const t=Eo(e);return[To(e),t,To(t)]}(s)),O="none"!==f;!p&&O&&T.push(...function(e,t,n,r){const i=mo(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?xo:Oo:t?Oo:xo;case"left":case"right":return t?ko:So;default:return[]}}(fo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(To)))),o}(s,m,f,w));const x=[s,...T],k=await l.detectOverflow(t,y),S=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&S.push(k[g]),h){const e=wo(i,a,w);S.push(k[e[0]],k[e[1]])}if(E=[...E,{placement:i,overflows:S}],!S.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===vo(t)||E.every(e=>vo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(O){const t=vo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var wa=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=na(e),u=i||o?[...c?Qo(c):[],...t?Qo(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=Lo(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-co(h)+"px "+-co(o.clientWidth-(u+p))+"px "+-co(o.clientHeight-(h+d))+"px "+-co(u)+"px",threshold:so(0,ao(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!ma(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=Io(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?aa(e):null;return l&&function t(){const r=aa(e);m&&!ma(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...fa,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:Ao},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=Po(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Ta(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ia(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ia(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:Ai.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:Ai.session})}},{key:"create",value:(i=Na(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(Ai.business.id)},body:e});return new ke(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:Ai.headers,body:JSON.stringify({session:Ai.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Da(t.prototype,n),r&&Da(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Ba=Fa;function Va(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&Va(t.prototype,n),r&&Va(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Ua(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ya(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ka(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ka(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ka(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&Ua(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(za);const Za=Xa;var Qa=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},es=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ts=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function ns(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=as(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:Ai.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),Tr(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){z.mode===q.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),Ai.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),Ai.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",Tr(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=as(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return wr(e,br)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),Ai.eventEmitter.dispatch("webchat:message:received",rs(rs({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=as(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",Ai.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};Ai.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=as(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",Ai.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=as(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",Ai.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),Ai.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=as(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=as(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[ya(this.offsetValue),va({padding:this.paddingValue}),ba()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=ys.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ms)}catch(e){return new Intl.DateTimeFormat(void 0,ms)}}}],r&&ss(n.prototype,r),i&&ss(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);vs.messageTimestampFormatters={},vs.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},vs.classes=["fadeOut"],vs.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"];var bs=g.lg.start();bs.register("hellotext--form",Fi),bs.register("hellotext--popup",ro),bs.register("hellotext--webchat",vs),bs.register("hellotext--webchat--emoji",Ma),bs.register("hellotext--message",Gi),window.Hellotext=Ai;const ws=Ai},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 1.125em;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__completion-headline h4 {\n margin: 0 0 8px;\n font-size: 1.44444444em;\n line-height: 1.25;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n}\n\n.hellotext--popup__completion-footer {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n justify-content: center;\n gap: 0 4px;\n text-align: center;\n}\n\n.hellotext--popup__completion-footer > span,\n.hellotext--popup__completion-action:disabled {\n opacity: 0.5;\n}\n\n.hellotext--popup__completion-action {\n appearance: none;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent;\n color: inherit;\n cursor: pointer;\n font: inherit;\n font-weight: 500;\n line-height: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n\n.hellotext--popup__completion-action:disabled {\n cursor: default;\n text-decoration: none;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c(()=>{"use strict";var e={891(e,t,n){n.d(t,{lg:()=>G,xI:()=>ie});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,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 n=e.index,r=t.index;return nr?1:0})}}class i{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,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach(e=>{n.push(`${t[e]?"":"!"}${e}`)}),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},a=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function s(e){return e.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function l(e){return s(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function h(e){return null!=e}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const d=["meta","ctrl","alt","shift"];class f{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||y("missing identifier"),this.methodName=n.methodName||y("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(a)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(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 n=t.filter(e=>!d.includes(e))[0];return!!n&&(p(this.keyMappings,n)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].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:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[s(o)]=g(r))}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[n,r,i,o]=d.map(e=>t.includes(e));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class v{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:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,a]of Object.entries(this.eventOptions))if(o in n){const s=n[o];i=i&&s({name:o,value:a,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,a={identifier:n,controller:r,element:i,index:o,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 b{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 n of this.matchElementsInTree(e))t.call(this,n)}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,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(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]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}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 O(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class T{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,n){O(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){O(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.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,n])=>n.has(e)).map(([e,t])=>e)}}class x{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new T}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 n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter(e=>this.matchElement(e));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}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 S{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 n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}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 k{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new T}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,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}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),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},(n,r)=>[e[r],t[r]])}(t,n).findIndex(([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r});return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter(e=>e.length).map((e,r)=>({element:t,attributeName:n,content:e,index:r}))}(e.getAttribute(t)||"",e,t)}}class E{constructor(e,t,n){this.tokenListObserver=new k(e,t,this),this.delegate=n,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:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}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 C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new E(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 v(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=f.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class P{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new S(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 n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.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 n=this.valueDescriptorMap[t];e[n.name]=n}),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class A{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new T}start(){this.tokenListObserver||(this.tokenListObserver=new k(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 n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.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 j(e,t){const n=_(e);return Array.from(n.reduce((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach(t=>e.add(t)),e),new Set))}function _(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class M{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new T,this.outletElementsByName=new T,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:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletConnected(e,t,n)))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause(()=>this.delegate.outletDisconnected(e,t,n)))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new x(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.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 T;return this.router.modules.forEach(t=>{j(t.definition.controllerConstructor,"outlets").forEach(n=>e.add(n,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 I{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new P(this,this.controller),this.targetObserver=new A(this,this),this.outletObserver=new M(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,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const L="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 N{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=D(e),r=function(e,t){return L(t).reduce((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n},{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return j(e,"blessings").reduce((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[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 I(this,e),this.contextsByScope.set(e,t)),t}}class R{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 F{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 n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,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}-${u(e)}`}}class B{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function V(e,t){return`[${e}~="${t}"]`}class z{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:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} 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(n=>this.matchesElement(n,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(n=>this.matchesElement(n,e,t))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class U{constructor(e,t,n,r){this.targets=new z(this),this.classes=new R(this),this.data=new F(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new B(r),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 W{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new E(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:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}}class H{constructor(e){this.application=e,this.scopeObserver=new W(this.element,this.schema,this),this.scopesByIdentifier=new T,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 N(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find(t=>t.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}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 $={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"},K("abcdefghijklmnopqrstuvwxyz".split("").map(e=>[e,e]))),K("0123456789".split("").map(e=>[e,e])))};function K(e){return e.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}class G{constructor(e=document.documentElement,t=$){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new H(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}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 n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function J(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function Y(e,t,n){let r=J(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=J(e,t,n),r||void 0)}function X([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),a=i&&o,s=i&&!o,l=!i&&o,c=Z(r.type),u=Q(e.typeObject.default);if(s)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return a?c:void 0}({controller:t,token:n,typeObject:r}),o=Q(r),a=Z(r),s=i||o||a;if(s)return s;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:s(r),get defaultValue(){return function(e){const t=Z(e);if(t)return ee[t];const n=p(e,"default"),r=p(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=Z(e);if(t)return ee[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==Q(n)},reader:te[i],writer:ne[i]||ne.default}}({controller:n,token:e,typeDefinition:t})}function Z(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},ne={default:function(e){return`${e}`},array:re,object:re};function re(e){return JSON.stringify(e)}class ie{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:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const a=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(a),a}}ie.blessings=[function(e){return j(e,"classes").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}}));var n},{})},function(e){return j(e,"targets").reduce((e,t)=>{return Object.assign(e,(n=t,{[`${n}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}}));var n},{})},function(e){const t=function(e,t){return _(e).reduce((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map(e=>[e,n[e]]):[]}(n,t)),e),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce((e,t)=>{const n=X(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})},{})}}};return t.reduce((e,t)=>Object.assign(e,function(e){const t=X(e,void 0),{key:n,name:r,reader:i,writer:o}=t;return{[r]:{get(){const e=this.data.get(n);return null!==e?i(e):t.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,o(e))}},[`has${c(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}(t)),n)},function(e){return j(e,"outlets").reduce((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=Y(this,t,e);if(n)return n;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 "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map(t=>{const n=Y(this,t,e);if(n)return n;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),n=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 "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t)),{})}],ie.targets=[],ie.outlets=[],ie.values={}},173(e,t,n){n.d(t,{default:()=>Os});var r=n.cjs(function(e,t){var n=[];function r(e){for(var t=-1,r=0;r0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}}),a=n.n(o),s=n.cjs(function(e,t){var n={};e.exports=function(e,t){var r=function(e){if(void 0===n[e]){var t=document.querySelector(e);if(window.HTMLIFrameElement&&t instanceof window.HTMLIFrameElement)try{t=t.contentDocument.head}catch(e){t=null}n[e]=t}return n[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(t)}}),l=n.n(s),c=n.cjs(function(e,t){e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}}),u=n.n(c),h=n.cjs(function(e,t){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}}),p=n.n(h),d=n.cjs(function(e,t){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}),f=n.n(d),m=n(109),y={};y.styleTagTransform=f(),y.setAttributes=u(),y.insert=l().bind(null,"head"),y.domAPI=a(),y.insertStyleElement=p(),i()(m.A,y),m.A&&m.A.locals&&m.A.locals;var g=n(891);function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return v(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&b(e.prototype,null),t&&b(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function T(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];this[n]=r}),this}}],null&&M(e.prototype,null),t&&M(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function D(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return N(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?N(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function N(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=D(e,2),n=t[0],r=t[1];if(!["primaryColor","secondaryColor","typography"].includes(n))throw new Error("Invalid style property: ".concat(n));if("typography"!==n&&!this.isHexOrRgba(r))throw new Error("Invalid color value: ".concat(r," for ").concat(n,". Colors must be hex or rgb/a."))}),this._style=e}},{key:"appearance",get:function(){return this._appearance},set:function(e){if(!this.isPlainObject(e))throw new Error("Appearance must be an object");Object.entries(e).forEach(e=>{var t=D(e,2),n=t[0],r=t[1];if(!["header","launcher"].includes(n))throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=D(e,2),r=t[0],i=t[1];if("header"===n&&"name"!==r)throw new Error("Invalid appearance header property: ".concat(r));if("launcher"===n&&"iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"whatsapp",get:function(){return this._whatsapp},set:function(e){if(!this.isPlainObject(e))throw new Error("WhatsApp must be an object");Object.entries(e).forEach(e=>{var t=D(e,2),n=t[0],r=t[1];if(!["number","restrictToChannel"].includes(n))throw new Error("Invalid WhatsApp property: ".concat(n));if(null!=r){if("number"===n&&"string"!=typeof r)throw new Error("Invalid WhatsApp number value: ".concat(r));if("restrictToChannel"===n&&"boolean"!=typeof r)throw new Error("Invalid WhatsApp restrictToChannel value: ".concat(r))}}),this._whatsapp=e}},{key:"mode",get:function(){return this._mode},set:function(e){if(!Object.values(z).includes(e))throw new Error("Invalid mode value: ".concat(e));this._mode=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(null!=e){if("object"!=typeof e||Array.isArray(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}else this._behaviour=e}},{key:"hasBehaviourOverride",get:function(){return this._hasBehaviourOverride}},{key:"behaviourOverride",set:function(e){this._hasBehaviourOverride=!!e}},{key:"strategy",get:function(){return this._strategy?this._strategy:"body"==this.container?V.FIXED:V.ABSOLUTE},set:function(e){if(e&&!Object.values(V).includes(e))throw new Error("Invalid strategy value: ".concat(e));this._strategy=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=D(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isHexOrRgba",value:function(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)}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&R(e.prototype,null),t&&R(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function U(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return W(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?W(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function W(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=U(e,2),n=t[0],r=t[1];if("launcher"!==n)throw new Error("Invalid appearance property: ".concat(n));if(!this.isPlainObject(r))throw new Error("Appearance ".concat(n," must be an object"));Object.entries(r).forEach(e=>{var t=U(e,2),r=t[0],i=t[1];if("iconUrl"!==r)throw new Error("Invalid appearance launcher property: ".concat(r));if(null!=i&&"string"!=typeof i)throw new Error("Invalid appearance ".concat(n,".").concat(r," value: ").concat(i))})}),this._appearance=e}},{key:"number",get:function(){return this._number},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid number value: ".concat(e));this._number=e}},{key:"body",get:function(){return this._body},set:function(e){if(null!=e&&"string"!=typeof e)throw new Error("Invalid body value: ".concat(e));this._body=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach(e=>{var t=U(e,2),n=t[0],r=t[1];this[n]=r}),this}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}],null&&H(e.prototype,null),t&&H(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return J(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),n=t[0],r=t[1];"forms"===n?this.forms=O.assign(r):"popup"===n?this.popup=L.assign(r):"webchat"===n?this.webchat=q.assign(r):"whatsappWidget"===n?this.whatsapp=G.assign(r):this[n]=r}),t&&(this.actionCableUrl=this.actionCableUrlForApiRoot(this.apiRoot))}return this}},{key:"locale",get:function(){return j.toString()},set:function(e){j.identifier=e}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}},{key:"actionCableUrlForApiRoot",value:function(e){try{var t=new URL(e),n="https:"===t.protocol?"wss:":"ws:";return t.protocol=n,t.pathname="/cable",t.search="",t.hash="",t.toString()}catch(e){return this.actionCableUrl}}}],null&&Y(e.prototype,null),t&&Y(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Q(e){var t="function"==typeof Map?new Map:void 0;return Q=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(ee())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&te(i,n.prototype),i}(e,arguments,ne(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),te(n,e)},Q(e)}function ee(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ee=function(){return!!e})()}function te(e,t){return te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},te(e,t)}function ne(e){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ne(e)}Z.apiRoot="https://api.hellotext.com/v1",Z.actionCableUrl="wss://www.hellotext.com/cable",Z.autoGenerateSession=!0,Z.session=null,Z.forms=O,Z.popup=L,Z.webchat=q,Z.whatsapp=G;var re=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=ne(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,ee()?Reflect.construct(t,n||[],ne(e).constructor):t.apply(e,n))}(this,t,["".concat(e," is not valid. Please provide a valid event name")])).name="InvalidEvent",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&te(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Q(Error));function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;tt===e)}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers=oe(oe({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new re(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(e=>e!==n))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach(e=>{e(t)})}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&se(t.prototype,n),r&&se(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function ue(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function he(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:Z.apiRoot;return"".concat(e,"/public/businesses")}},{key:"get",value:function(){var e,t=(e=function*(e,t){return fetch("".concat(this.endpoint(t),"/").concat(e),{method:"GET",headers:{Authorization:"Bearer ".concat(e),Accept:"application/json","Content-Type":"application/json"}})},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){ue(o,r,i,a,s,"next",e)}function s(e){ue(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e,n){return t.apply(this,arguments)}}()}],t&&he(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function fe(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=yield fetch(this.endpoint,{method:"POST",headers:ji.headers,body:JSON.stringify(Fe({session:ji.session},e))});return new Se(t.ok,t)},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Ve(o,r,i,a,s,"next",e)}function s(e){Ve(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&ze(e.prototype,null),t&&ze(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const We=Ue;function He(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $e(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return et(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append("style[".concat(r,"]"),i)}),this.appendWebchatOverrides(t),t.searchParams.append("placement",Z.webchat.placement);var n=yield fetch(t,{method:"GET",headers:ji.headers}),r=yield n.json();return ji.business.data||(ji.business.setData(r.business),ji.business.setLocale(r.locale)),(new DOMParser).parseFromString(r.html,"text/html").querySelector("article")},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){tt(o,r,i,a,s,"next",e)}function s(e){tt(o,r,i,a,s,"throw",e)}a(void 0)})});return function(e){return t.apply(this,arguments)}}()},{key:"appendWebchatOverrides",value:function(e){var t,n,r=Z.webchat,i=r.appearance,o=r.whatsapp;this.appendIfSupplied(e,"webchat[appearance][header][name]",null===(t=i.header)||void 0===t?void 0:t.name),this.appendIfSupplied(e,"webchat[appearance][launcher][icon_url]",null===(n=i.launcher)||void 0===n?void 0:n.iconUrl),this.appendIfSupplied(e,"webchat[handoff][identifier]",o.number),this.appendIfSupplied(e,"webchat[handoff][restrict_to_channel]",o.restrictToChannel)}},{key:"appendIfSupplied",value:function(e,t,n){null!=n&&e.searchParams.append(t,String(n))}}],t&&nt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ot=it;function at(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function st(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){at(o,r,i,a,s,"next",e)}function s(e){at(o,r,i,a,s,"throw",e)}a(void 0)})}}function lt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{}),{},{session:ji.session,at:(new Date).toISOString()});fetch(this.endpoint,{method:"POST",headers:ji.headers,body:JSON.stringify(e),keepalive:!0})},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){mt(o,r,i,a,s,"next",e)}function s(e){mt(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})}],null&&yt(e.prototype,null),t&&yt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();const bt=vt;function wt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=e.apiRoot,n=e.stylesheet,r=void 0===n||n;try{var i=t?yield de.get(this.id,t):yield de.get(this.id);if(!1===i.ok)return null;var o=yield i.json();return o?(this.setData(o,{stylesheet:r}),o.locale&&this.setLocale(o.locale),o):null}catch(e){return null}},i=function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function a(e){kt(o,n,i,a,s,"next",e)}function s(e){kt(o,n,i,a,s,"throw",e)}a(void 0)})},function(){return i.apply(this,arguments)})},{key:"setData",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).stylesheet,n=void 0===t||t;this.data=e,n&&this.loadStylesheet()}},{key:"loadStylesheet",value:function(){var e;if("undefined"!=typeof document&&null!==(e=this.data)&&void 0!==e&&e.style_url){var t=this.constructor.ensureStylesheet(this.data.style_url);return this.stylesheet===t&&this.holdsStylesheet||(this.releaseStylesheet(),this.stylesheet=t,this.holdsStylesheet=!0,t._hellotextStylesheetUsers=(t._hellotextStylesheetUsers||0)+1),void(this.stylesheetLoaded=this.constructor.waitForStylesheet(this.stylesheet))}this.releaseStylesheet(),this.stylesheet=null,this.stylesheetLoaded=Promise.resolve(!1)}},{key:"releaseStylesheet",value:function(){if(this.stylesheet&&this.holdsStylesheet){var e=this.stylesheet;e._hellotextStylesheetUsers-=1,e._hellotextStylesheetUsers<=0&&e.remove(),this.holdsStylesheet=!1,this.stylesheet=null}}},{key:"subscription",get:function(){return this.data.subscription}},{key:"country",get:function(){return this.data.country}},{key:"enabledWhitelist",get:function(){return"disabled"!==this.data.whitelist}},{key:"setLocale",value:function(e){if(!St[e])return console.warn("Locale ".concat(e," not found"));this.data||(this.data={}),this.data.locale=e}},{key:"locale",get:function(){return St[this.data.locale]}},{key:"features",get:function(){return this.data.features}}],n=[{key:"stylesheetSelector",get:function(){return'link[rel="stylesheet"]['.concat(Pt,"]")}},{key:"ensureStylesheet",value:function(e){var t=this.normalizedStylesheetUrl(e),n=this.stylesheetLinks.find(e=>e.href===t);if(n)return n.setAttribute(Pt,"true"),n;var r=document.createElement("link");return r.rel="stylesheet",r.href=e,r.setAttribute(Pt,"true"),this.waitForStylesheet(r),document.head.append(r),r}},{key:"stylesheetLinks",get:function(){return"undefined"==typeof document?[]:Array.from(document.querySelectorAll(this.stylesheetSelector))}},{key:"latestStylesheet",get:function(){return this.stylesheetLinks[this.stylesheetLinks.length-1]}},{key:"normalizedStylesheetUrl",value:function(e){try{return new URL(e,document.baseURI).href}catch(t){return e}}},{key:"waitForStylesheet",value:function(e){return e?this.stylesheetIsLoaded(e)?Promise.resolve(!0):"false"===e.dataset.hellotextStylesheetLoaded?Promise.resolve(!1):(e._hellotextStylesheetLoaded||(e._hellotextStylesheetLoaded=new Promise(t=>{var n,r=r=>{clearTimeout(n),e.removeEventListener("load",i),e.removeEventListener("error",o),e.dataset.hellotextStylesheetLoaded=r?"true":"false",t(r)},i=()=>r(this.stylesheetIsLoaded(e)),o=()=>r(!1);e.addEventListener("load",i),e.addEventListener("error",o),(n=setTimeout(()=>r(this.stylesheetIsLoaded(e)),1e4)).unref&&n.unref()})),e._hellotextStylesheetLoaded):Promise.resolve(!1)}},{key:"stylesheetIsLoaded",value:function(e){return"true"===e.dataset.hellotextStylesheetLoaded||!!e.sheet}}],t&&Et(e.prototype,t),n&&Et(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();function jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return It(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2);return t[0],t[1]}));t.observed_at=(new Date).toISOString(),Mt.set("hello_utm",JSON.stringify(t))}}},{key:"current",get:function(){try{return JSON.parse(Mt.get("hello_utm"))||{}}catch(e){return{}}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Rt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.utm=new Nt,this._url=t}return t=e,r=[{key:"getRootDomain",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;try{if(!e){var t;if("undefined"==typeof window||null===(t=window.location)||void 0===t||!t.hostname)return null;e=window.location.hostname}var n=e.split(".");if(n.length<=1)return e;for(var r of["myshopify.com","vtexcommercestable.com.br","myvtex.com","wixsite.com"]){var i=r.split(".");if(n.slice(-i.length).join(".")===r&&n.length>i.length)return".".concat(n.slice(-(i.length+1)).join("."))}var o=n[n.length-1],a=n[n.length-2];return n.length>2&&2===o.length&&a.length<=3?".".concat(n.slice(-3).join(".")):".".concat(n.slice(-2).join("."))}catch(e){return null}}}],(n=[{key:"url",get:function(){return null!==this._url&&void 0!==this._url?this._url:window.location.href}},{key:"title",get:function(){return document.title}},{key:"path",get:function(){if(this._url)try{return new URL(this._url).pathname}catch(e){return"/"}return window.location.pathname}},{key:"utmParams",get:function(){return this.utm.current}},{key:"trackingData",get:function(){return{page:{url:this.url,title:this.title,path:this.path},utm_params:this.utmParams}}},{key:"domain",get:function(){try{var t=this.url;if(!t)return null;var n=new URL(t).hostname;return e.getRootDomain(n)}catch(e){return null}}}])&&Rt(t.prototype,n),r&&Rt(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Vt(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:new Bt;qt(this,Kt)[Kt]=e,qt(this,$t)[$t]=new ye,this.session=qt(this,$t)[$t].session||Z.session||Mt.get("hello_session"),!this.session&&Z.autoGenerateSession&&(this.session=crypto.randomUUID())}}],null&&Vt(e.prototype,null),t&&Vt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Jt(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n\n ".concat(ji.business.locale.white_label.powered_by,'\n\n \n \n Hellotext\n \n \n \n \n ')}});const sn=Object.entries,ln=Object.setPrototypeOf,cn=Object.isFrozen,un=Object.getPrototypeOf,hn=Object.getOwnPropertyDescriptor;let pn=Object.freeze,dn=Object.seal,fn=Object.create,mn="undefined"!=typeof Reflect&&Reflect,yn=mn.apply,gn=mn.construct;pn||(pn=function(e){return e}),dn||(dn=function(e){return e}),yn||(yn=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i1?t-1:0),r=1;r1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:Sn;if(ln&&ln(e,null),!xn(t))return e;let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(cn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function zn(e){for(let t=0;t/g),rr=dn(/\${[\w\W]*/g),ir=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),or=dn(/^aria-[\-\w]+$/),ar=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sr=dn(/^(?:\w+script|data):/i),lr=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cr=dn(/^html$/i),ur=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),hr=dn(/<[/\w!]/g),pr=dn(/<[/\w]/g),dr=dn(/<\/no(script|embed|frames)/i),fr=dn(/\/>/i),mr=function(){return"undefined"==typeof window?null:window},yr=function(e,t,n,r){return Ln(e,t)&&xn(e[t])?Vn(r.base?qn(r.base):{},e[t],r.transform):n};var gr=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr();const n=t=>e(t);if(n.version="3.4.13",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let r=t.document;const i=r,o=i.currentScript;t.DocumentFragment;const a=t.HTMLTemplateElement,s=t.Node,l=t.Element,c=t.NodeFilter;void 0===t.NamedNodeMap&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const u=t.DOMParser,h=t.trustedTypes,p=l.prototype,d=Un(p,"cloneNode"),f=Un(p,"remove"),m=Un(p,"nextSibling"),y=Un(p,"childNodes"),g=Un(p,"parentNode"),v=Un(p,"shadowRoot"),b=Un(p,"attributes"),w=s&&s.prototype?Un(s.prototype,"nodeType"):null,O=s&&s.prototype?Un(s.prototype,"nodeName"):null,T=s&&s.prototype?Un(s.prototype,"ownerDocument"):null;if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let x,S,k="",E=!1,C=0;const P=function(){if(C>0)throw Rn('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.')},A=function(e){P(),C++;try{return x.createHTML(e)}finally{C--}},j=r,_=j.implementation,M=j.createNodeIterator,I=j.createDocumentFragment,L=j.getElementsByTagName,D=i.importNode;let N={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof sn&&"function"==typeof g&&_&&void 0!==_.createHTMLDocument;const R=tr,F=nr,B=rr,V=ir,z=or,q=sr,U=lr,W=ur;let H=ar,$=null;const K=Vn({},[...Wn,...Hn,...$n,...Gn,...Yn]);let G=null;const J=Vn({},[...Xn,...Zn,...Qn,...er]);let Y=Object.seal(fn(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}})),X=null,Z=null;const Q=Object.seal(fn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ee=!0,te=!0,ne=!1,re=!0,ie=!1,oe=!0,ae=!1,se=!1,le=null,ce=null,ue=!1,he=!1,pe=!1,de=!1,fe=!0,me=!1;const ye="user-content-";let ge=!0,ve=!1,be={},we=null;const Oe=Vn({},["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 Te=null;const xe=Vn({},["audio","video","img","source","image","track"]);let Se=null;const ke=Vn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Ae=Pe,je=!1,_e=null;const Me=Vn({},[Ee,Ce,Pe],kn),Ie=pn(["mi","mo","mn","ms","mtext"]);let Le=Vn({},Ie);const De=pn(["annotation-xml"]);let Ne=Vn({},De);const Re=Vn({},["title","style","font","a","script"]);let Fe=null;const Be=["application/xhtml+xml","text/html"];let Ve=null,ze=null;const qe=r.createElement("form"),Ue=function(e){return e instanceof RegExp||e instanceof Function},We=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ze&&ze===e)return;e&&"object"==typeof e||(e={}),e=qn(e),Fe=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Ve="application/xhtml+xml"===Fe?kn:Sn,$=yr(e,"ALLOWED_TAGS",K,{transform:Ve}),G=yr(e,"ALLOWED_ATTR",J,{transform:Ve}),_e=yr(e,"ALLOWED_NAMESPACES",Me,{transform:kn}),Se=yr(e,"ADD_URI_SAFE_ATTR",ke,{transform:Ve,base:ke}),Te=yr(e,"ADD_DATA_URI_TAGS",xe,{transform:Ve,base:xe}),we=yr(e,"FORBID_CONTENTS",Oe,{transform:Ve}),X=yr(e,"FORBID_TAGS",qn({}),{transform:Ve}),Z=yr(e,"FORBID_ATTR",qn({}),{transform:Ve}),be=!!Ln(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?qn(e.USE_PROFILES):e.USE_PROFILES),ee=!1!==e.ALLOW_ARIA_ATTR,te=!1!==e.ALLOW_DATA_ATTR,ne=e.ALLOW_UNKNOWN_PROTOCOLS||!1,re=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,ie=e.SAFE_FOR_TEMPLATES||!1,oe=!1!==e.SAFE_FOR_XML,ae=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,pe=e.RETURN_DOM_FRAGMENT||!1,de=e.RETURN_TRUSTED_TYPE||!1,ue=e.FORCE_BODY||!1,fe=!1!==e.SANITIZE_DOM,me=e.SANITIZE_NAMED_PROPS||!1,ge=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,H=function(e){try{return Nn(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:ar,Ae="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,Le=Ln(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?qn(e.MATHML_TEXT_INTEGRATION_POINTS):Vn({},Ie),Ne=Ln(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?qn(e.HTML_INTEGRATION_POINTS):Vn({},De);const t=Ln(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?qn(e.CUSTOM_ELEMENT_HANDLING):fn(null);if(Y=fn(null),Ln(t,"tagNameCheck")&&Ue(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Ln(t,"attributeNameCheck")&&Ue(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Ln(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),dn(Y),ie&&(te=!1),pe&&(he=!0),be&&($=Vn({},Yn),G=fn(null),!0===be.html&&(Vn($,Wn),Vn(G,Xn)),!0===be.svg&&(Vn($,Hn),Vn(G,Zn),Vn(G,er)),!0===be.svgFilters&&(Vn($,$n),Vn(G,Zn),Vn(G,er)),!0===be.mathMl&&(Vn($,Gn),Vn(G,Qn),Vn(G,er))),Q.tagCheck=null,Q.attributeCheck=null,Ln(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Q.tagCheck=e.ADD_TAGS:xn(e.ADD_TAGS)&&($===K&&($=qn($)),Vn($,e.ADD_TAGS,Ve))),Ln(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Q.attributeCheck=e.ADD_ATTR:xn(e.ADD_ATTR)&&(G===J&&(G=qn(G)),Vn(G,e.ADD_ATTR,Ve))),Ln(e,"ADD_URI_SAFE_ATTR")&&xn(e.ADD_URI_SAFE_ATTR)&&Vn(Se,e.ADD_URI_SAFE_ATTR,Ve),Ln(e,"FORBID_CONTENTS")&&xn(e.FORBID_CONTENTS)&&(we===Oe&&(we=qn(we)),Vn(we,e.FORBID_CONTENTS,Ve)),Ln(e,"ADD_FORBID_CONTENTS")&&xn(e.ADD_FORBID_CONTENTS)&&(we===Oe&&(we=qn(we)),Vn(we,e.ADD_FORBID_CONTENTS,Ve)),ge&&($["#text"]=!0),ae&&Vn($,["html","head","body"]),$.table&&(Vn($,["tbody"]),delete X.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{k=A("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,k=""):(void 0===x&&(E||(S=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o),E=!0),x=S),x&&"string"==typeof k&&(k=A("")));pn&&pn(e),ze=e},He=Vn({},[...Hn,...$n,...Kn]),$e=Vn({},[...Gn,...Jn]),Ke=function(e){On(n.removed,{element:e});try{g(e).removeChild(e)}catch(t){if(f(e),!g(e))throw Rn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Xe(e);const t=y(e);if(t){const e=[];vn(t,t=>{On(e,t)}),vn(e,e=>{try{f(e)}catch(e){}})}const n=b(e);if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],i=r&&r.name;if("string"==typeof i)try{e.removeAttribute(i)}catch(e){}}},Je=function(e,t){try{On(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){On(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(he||pe)try{Ke(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=b(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],i=r&&r.name;if("string"==typeof i&&!G[Ve(i)])try{e.removeAttribute(i)}catch(e){}}},Xe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(w?w(e):e.nodeType)&&Ye(e);const n=y(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Ze=function(e){let t=null,n=null;if(ue)e=""+e;else{const t=En(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Fe&&Ae===Pe&&(e=''+e+"");const i=x?A(e):e;if(Ae===Pe)try{t=(new u).parseFromString(i,Fe)}catch(e){}if(!t||!t.documentElement){t=_.createDocument(Ae,"template",null);try{t.documentElement.innerHTML=je?k:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Ae===Pe?L.call(t,ae?"html":"body")[0]:ae?t.documentElement:o},Qe=function(e){const t=T?T(e):e.ownerDocument;return M.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(e){return e=Cn(e,R," "),e=Cn(e,F," "),Cn(e,B," ")},tt=function(e){var t;e.normalize();const n=T?T(e):e.ownerDocument,r=M.call(n||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let i=r.nextNode();for(;i;)i.data=et(i.data),i=r.nextNode();const o=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");o&&vn(o,e=>{rt(e.content)&&tt(e.content)})},nt=function(e){const t=O?O(e):null;return"string"==typeof t&&"form"===Ve(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==b(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==w(e)||e.childNodes!==y(e))},rt=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return 11===w(e)}catch(e){return!1}},it=function(e){if(!w||"object"!=typeof e||null===e)return!1;try{return"number"==typeof w(e)}catch(e){return!1}};function ot(e,t,r){0!==e.length&&vn(e,e=>{e.call(n,t,r,ze)})}const at=function(e,t,n,r){return 0===e.length?t:t===n||t===r?qn(t):t},st=function(e,t){if(ot(N.beforeSanitizeElements,e,null),e!==t&&null===g(e))return ve&&Xe(e),!0;if(nt(e))return Ke(e),!0;const r=Ve(O?O(e):e.nodeName);if($=at(N.uponSanitizeElement,$,K,le),ot(N.uponSanitizeElement,e,{tagName:r,allowedTags:$}),e!==t&&null===g(e))return ve&&Xe(e),!0;if(function(e,t){return!!(oe&&e.hasChildNodes()&&!it(e.firstElementChild)&&Nn(hr,e.textContent)&&Nn(hr,e.innerHTML))||!(!oe||e.namespaceURI!==Pe||"style"!==t||!it(e.firstElementChild))||7===e.nodeType||!(!oe||8!==e.nodeType||!Nn(pr,e.data))}(e,r))return Ke(e),!0;if(X[r]||!(Q.tagCheck instanceof Function&&Q.tagCheck(r))&&!$[r]){const n=function(e,t,n){if(!X[t]&&ut(t)){if(Y.tagNameCheck instanceof RegExp&&Nn(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(ge&&!we[t]){const t=g(e),r=y(e);if(r&&t)for(let i=r.length-1;i>=0;--i){const o=e===n?d(r[i],!0):r[i];t.insertBefore(o,m(e))}}return Ke(e),!0}(e,r,t);return!1===n&&ot(N.afterSanitizeElements,e,null),n}if(1===(w?w(e):e.nodeType)&&!function(e){let t=g(e);t&&t.tagName||(t={namespaceURI:Ae,tagName:"template"});const n=Sn(e.tagName),r=Sn(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===Ce?function(e,t,n){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===Ee?"svg"===e&&("annotation-xml"===n||Le[n]):Boolean(He[e])}(n,t,r):e.namespaceURI===Ee?function(e,t,n){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===Ce?"math"===e&&Ne[n]:Boolean($e[e])}(n,t,r):e.namespaceURI===Pe?function(e,t,n){return!(t.namespaceURI===Ce&&!Ne[n])&&!(t.namespaceURI===Ee&&!Le[n])&&!$e[e]&&(Re[e]||!He[e])}(n,t,r):!("application/xhtml+xml"!==Fe||!_e[e.namespaceURI]))}(e))return Ke(e),!0;if(("noscript"===r||"noembed"===r||"noframes"===r)&&Nn(dr,e.innerHTML))return Ke(e),!0;if(ie&&3===e.nodeType){const t=et(e.textContent);e.textContent!==t&&(On(n.removed,{element:e.cloneNode()}),e.textContent=t)}return ot(N.afterSanitizeElements,e,null),!1},lt=function(e,t,n){if(Z[t])return!1;if(oe&&"patchsrc"===t)return!1;if(oe&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(fe&&("id"===t||"name"===t)&&(n in r||n in qe))return!1;const i=G[t]||Q.attributeCheck instanceof Function&&Q.attributeCheck(t,e);if(te&&Nn(V,t));else if(ee&&Nn(z,t));else if(i){if(Se[t]);else if(Nn(H,Cn(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Pn(n,"data:")||!Te[e])if(ne&&!Nn(q,Cn(n,U,"")));else if(n)return!1}else if(!(ut(e)&&(Y.tagNameCheck instanceof RegExp&&Nn(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Nn(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Nn(Y.tagNameCheck,n)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(n))))return!1;return!0},ct=Vn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ut=function(e){return!ct[Sn(e)]&&Nn(W,e)},ht=function(e,t,n,r){if(x&&"object"==typeof h&&"function"==typeof h.getAttributeType&&!n)switch(h.getAttributeType(e,t)){case"TrustedHTML":return A(r);case"TrustedScriptURL":return function(e){P(),C++;try{return x.createScriptURL(e)}finally{C--}}(r)}return r},pt=function(e,t,r,i){try{r?e.setAttributeNS(r,t,i):e.setAttribute(t,i),nt(e)?Ke(e):wn(n.removed)}catch(n){Je(t,e)}},dt=function(e){ot(N.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||nt(e))return;G=at(N.uponSanitizeAttribute,G,J,ce);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let r=t.length;const i=Ve(e.nodeName);for(;r--;){const o=t[r],a=o.name,s=o.namespaceURI,l=o.value,c=Ve(a),u=l;let h="value"===a?u:An(u);n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,ot(N.uponSanitizeAttribute,e,n),h=n.attrValue,!me||"id"!==c&&"name"!==c||0===Pn(h,ye)||(Je(a,e),h=ye+h),oe&&Nn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)||"attributename"===c&&En(h,"href")?Je(a,e):n.forceKeepAttr||(!n.keepAttr||!re&&Nn(fr,h)?Je(a,e):(ie&&(h=et(h)),lt(i,c,h)?(h=ht(i,c,s,h),h!==u&&pt(e,a,s,h)):Je(a,e)))}ot(N.afterSanitizeAttributes,e,null)},ft=function(e){let t=null;const n=Qe(e);for(ot(N.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(ot(N.uponSanitizeShadowNode,t,null),st(t,e),dt(t),rt(t.content)&&ft(t.content),1===(w?w(t):t.nodeType)){const e=v(t);rt(e)&&(mt(e),ft(e))}ot(N.afterSanitizeShadowDOM,e,null)},mt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){ft(e.shadow);continue}const n=e.node,r=1===(w?w(n):n.nodeType),i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){const e=O?O(n):null;if("string"==typeof e&&"template"===Ve(e)){const e=n.content;rt(e)&&t.push({node:e,shadow:null})}}if(r){const e=v(n);rt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,s=null;if(je=!e,je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!it(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return jn(e);case"boolean":return _n(e);case"bigint":return Mn?Mn(e):"0";case"symbol":return In?In(e):"Symbol()";case"undefined":default:return Dn(e);case"function":case"object":{if(null===e)return Dn(e);const t=e,n=Un(t,"toString");if("function"==typeof n){const e=n(t);return"string"==typeof e?e:Dn(e)}return Dn(e)}}}(e)))throw Rn("dirty is not a string, aborting");if(!n.isSupported)return e;se?($=le,G=ce):We(t),(N.uponSanitizeElement.length>0||N.uponSanitizeAttribute.length>0)&&($=qn($)),N.uponSanitizeAttribute.length>0&&(G=qn(G)),n.removed=[];const l=ve&&"string"!=typeof e&&it(e);if(l){!function(e){if(!oe)return;const t=[e];for(;t.length>0;){const e=t.pop(),n=w?w(e):e.nodeType;if(7===n||8===n&&Nn(pr,e.data)){try{f(e)}catch(e){}continue}if(1===n){const t=e,n=Ve(O?O(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==n&&"output"!==n&&t.removeAttribute("for")}catch(e){}}const r=y(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}}(e);const t=O?O(e):e.nodeName;if("string"==typeof t){const n=Ve(t);if(!$[n]||X[n])throw Ge(e),Rn("root node is forbidden and cannot be sanitized in-place")}if(nt(e))throw Ge(e),Rn("root node is clobbered and cannot be sanitized in-place");try{mt(e)}catch(t){throw Ge(e),t}}else if(it(e))r=Ze("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o),mt(o);else{if(!he&&!ie&&!ae&&-1===e.indexOf("<"))return x&&de?A(e):e;if(r=Ze(e),!r)return he?null:de?k:""}r&&ue&&Ke(r.firstChild);const c=l?e:r;try{const e=Qe(c);for(;a=e.nextNode();)st(a,c),dt(a),rt(a.content)&&ft(a.content)}catch(t){throw l&&(Ge(e),vn(n.removed,e=>{e.element&&Xe(e.element)})),t}if(l)return vn(n.removed,e=>{e.element&&Xe(e.element)}),ie&&tt(e),e;if(he){if(ie&&tt(r),pe)for(s=I.call(r.ownerDocument);r.firstChild;)s.appendChild(r.firstChild);else s=r;return(G.shadowroot||G.shadowrootmode)&&(s=D.call(i,s,!0)),s}let u=ae?r.outerHTML:r.innerHTML;return ae&&$["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Nn(cr,r.ownerDocument.doctype.name)&&(u="\n"+u),ie&&(u=et(u)),x&&de?A(u):u},n.setConfig=function(){We(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),se=!0,le=$,ce=G},n.clearConfig=function(){ze=null,se=!1,le=null,ce=null,x=S,k=""},n.isValidAttribute=function(e,t,n){ze||We({});const r=Ve(e),i=Ve(t);return lt(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ln(N,e)&&On(N[e],t)},n.removeHook=function(e,t){if(Ln(N,e)){if(void 0!==t){const n=bn(N[e],t);return-1===n?void 0:Tn(N[e],n,1)[0]}return wn(N[e])}},n.removeHooks=function(e){Ln(N,e)&&(N[e]=[])},n.removeAllHooks=function(){N={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}(),vr={ADD_ATTR:["target"],ALLOW_DATA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0}},br={ADD_ATTR:["target"],ADD_TAGS:["hellotext-icon"],RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0}};function wr(e,t){var n=gr.sanitize(e,t);return n.querySelectorAll('a[target="_blank"]').forEach(e=>{var t=new Set(e.rel.split(/\s+/).filter(Boolean));t.add("noopener"),t.add("noreferrer"),e.rel=Array.from(t).join(" ")}),n}function Or(e,t){e.replaceChildren(function(e){return wr(e,vr)}(t))}function Tr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xr(e,t,n){return(t=Er(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Sr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function kr(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,jr,{value:Mr}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")},t=[{key:"mount",value:(n=function*(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).ifCompleted;if((void 0===t||t)&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),ji.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)}),document.contains(this.element)||document.body.appendChild(this.element),ji.business.features.white_label||this.element.prepend(rn.build())},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Sr(o,r,i,a,s,"next",e)}function s(e){Sr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=Cr(this,jr)[jr]("[data-form-header]","header");Or(t,e.content),this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=Cr(this,jr)[jr]("[data-form-inputs]","main");e.map(e=>Xt.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)}},{key:"buildButton",value:function(e){var t=Cr(this,jr)[jr]("[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)}},{key:"buildFooter",value:function(e){var t=Cr(this,jr)[jr]("[data-form-footer]","footer");Or(t,e.content),this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),ji.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var 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"}},{key:"elementAttributes",get:function(){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)}]}}],t&&kr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Mr(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}function Ir(e){var t="function"==typeof Map?new Map:void 0;return Ir=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(Lr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&Dr(i,n.prototype),i}(e,arguments,Nr(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Dr(n,e)},Ir(e)}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Lr=function(){return!!e})()}function Dr(e,t){return Dr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Dr(e,t)}function Nr(e){return Nr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Nr(e)}var Rr=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=Nr(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Lr()?Reflect.construct(t,n||[],Nr(e).constructor):t.apply(e,n))}(this,t,["You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id"])).name="NotInitializedError",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Dr(e,t)}(t,e),n=t,Object.defineProperty(n,"prototype",{writable:!1}),n;var n}(Ir(Error));function Fr(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Br(e,t){for(var n=0;n0&&this.collect()}},{key:"formMutationObserver",value:function(e){e.find(e=>"childList"===e.type&&e.addedNodes.length>0)&&Array.from(document.querySelectorAll("[data-hello-form]")).length>0&&this.collect()}},{key:"collect",value:(n=function*(){if(ji.notInitialized)throw new Rr;if(!this.fetching){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.");var e=function(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,Ur)[Ur];if(0!==e.length){var t=e.map(e=>Ne.get(e).then(e=>e.json()));this.fetching=!0,yield Promise.all(t).then(e=>e.forEach(this.add)).then(()=>ji.eventEmitter.dispatch("forms:collected",this)).then(()=>this.fetching=!1),Z.forms.autoMount&&this.forms.forEach(e=>e.mount())}}},r=function(){var e=this,t=arguments;return new Promise(function(r,i){var o=n.apply(e,t);function a(e){Fr(o,r,i,a,s,"next",e)}function s(e){Fr(o,r,i,a,s,"throw",e)}a(void 0)})},function(){return r.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||(ji.business.data||(ji.business.setData(e.business),ji.business.setLocale(j.toString())),ji.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 _r(e)))}},{key:"getById",value:function(e){return this.forms.find(t=>t.id===e)}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some(t=>t.id===e)}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],t&&Br(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r}();function Hr(){return Array.from(document.querySelectorAll("[data-hello-form]")).map(e=>e.dataset.helloForm).filter(this.excludes)}function $r(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Kr(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){$r(o,r,i,a,s,"next",e)}function s(e){$r(o,r,i,a,s,"throw",e)}a(void 0)})}}function Gr(e,t){for(var n=0;nyi(e)).filter(e=>void 0!==e);if(e instanceof Date)return e.toISOString();if("object"==typeof e){var n=Object.keys(e).sort((e,t)=>e.localeCompare(t)).reduce((t,n)=>{var r=yi(e[n]);return void 0!==r&&(t[n]=r),t},{});return Object.keys(n).length>0?n:void 0}return"number"==typeof e||"boolean"==typeof e?e:void 0}}function gi(e,t){var n=yi(function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{}))||{};return JSON.stringify(n)}function vi(){return(vi=pi(function*(e){var t;if(null===(t=globalThis.crypto)||void 0===t||!t.subtle||"undefined"==typeof TextEncoder)return function(e){for(var t=5381,n=0;n>>0).toString(16))}(e);var n=yield globalThis.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("");return"v1:".concat(r)})).apply(this,arguments)}var bi=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"matches",value:function(e,t){return!!e&&e===t}},{key:"generate",value:(n=pi(function*(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return yield function(e){return vi.apply(this,arguments)}(gi(e,t,n))}),function(e,t){return n.apply(this,arguments)})}],t&&ui(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function wi(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Oi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Oi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Oi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{},n=++this.initializationGeneration;this.initializationBaseline||(this.initializationBaseline={configuration:this.configurationSnapshot(),runtime:this.runtimeSnapshot()});var r=this.initializationBaseline,i=r.configuration,o=r.runtime,a={popups:[]},s=new At(e);try{var l,c,u,h,p,d,f=yield s.hydrate({apiRoot:t.apiRoot,stylesheet:!1});if(!this.initializationIsCurrent(n))return;if(!f&&this.hasMountedSurfaces(o)&&(!this.hasExplicitSurface(t)&&this.hasDisabledSurface(t)?this.restoreRuntime(this.runtimeWithoutDisabledSurfaces(o,t)):this.hasExplicitSurface(t)||this.restoreRuntime(o),!this.hasExplicitSurface(t)))return void this.restoreConfiguration(i);Z.assign(t),this.business=s,s.loadStylesheet(),this.page=new Bt,Gt.initialize(this.page),this.forms=new Wr,this.query=new ye,this.popup=void 0,this.popups=[],this.webchat=void 0,this.whatsapp=void 0;var m=!1===t.popup?[]:this.popupConfigs(f,t.popup||{}),y=!1!==t.webchat&&this.mergeWebchatConfig(f&&f.webchat||{},t.webchat||{}),g=!1!==t.whatsappWidget&&this.mergeWhatsAppConfig(f&&f.whatsapp||{},t.whatsappWidget||{}),v=t.webchat&&!1!==t.webchat&&Object.prototype.hasOwnProperty.call(t.webchat,"behaviour");if(Z.webchat.behaviourOverride=v,y&&y.id&&(Z.webchat.assign(y),a.webchat=yield Yr.load(y.id),!this.initializationIsCurrent(n)))return;if(g&&g.id&&(Z.whatsapp.assign(g),a.whatsapp=yield ti.load(g.id),!this.initializationIsCurrent(n)))return;if(m.length>0)for(var b of(Z.popup.assign(m[0]),m)){var w=yield ai.load(b.id);if(a.popups.push(w),!this.initializationIsCurrent(n))return}this.unmountSurfaces(o),null===(l=o.business)||void 0===l||null===(c=l.releaseStylesheet)||void 0===c||c.call(l),null===(u=a.webchat)||void 0===u||null===(h=u.markCoexistingWidgets)||void 0===h||h.call(u),null===(p=a.whatsapp)||void 0===p||null===(d=p.markCoexistingWidgets)||void 0===d||d.call(p),this.webchat=a.webchat,this.whatsapp=a.whatsapp,this.popups=a.popups,this.popup=a.popups[0],"undefined"!=typeof MutationObserver&&this.forms.collectExistingFormsOnPage()}catch(e){throw this.unmountSurfaces(a),s.releaseStylesheet(),this.initializationIsCurrent(n)&&(this.restoreRuntime(o),this.restoreConfiguration(i)),e}finally{this.initializationIsCurrent(n)?this.initializationBaseline=void 0:(this.unmountSurfaces(a),s.releaseStylesheet())}}),function(e){return i.apply(this,arguments)})},{key:"initializationIsCurrent",value:function(e){return this.initializationGeneration===e}},{key:"unmountPopups",value:function(){this.unmountSurfaces({popups:this.popups})}},{key:"unmountSurfaces",value:function(e){var t=e.popups,n=void 0===t?[]:t,r=e.webchat,i=e.whatsapp;new Set([...n,r,i]).forEach(e=>{var t;return null==e||null===(t=e.unmount)||void 0===t?void 0:t.call(e)})}},{key:"runtimeSnapshot",value:function(){return{business:this.business,page:this.page,forms:this.forms,query:this.query,popup:this.popup,popups:this.popups,webchat:this.webchat,whatsapp:this.whatsapp}}},{key:"hasExplicitSurface",value:function(e){return[e.popup,e.webchat,e.whatsappWidget].some(e=>e&&!1!==e&&e.id)}},{key:"hasDisabledSurface",value:function(e){return!1===e.popup||!1===e.webchat||!1===e.whatsappWidget}},{key:"runtimeWithoutDisabledSurfaces",value:function(e,t){var n={popups:!1===t.popup?e.popups:[],webchat:!1===t.webchat?e.webchat:void 0,whatsapp:!1===t.whatsappWidget?e.whatsapp:void 0};return this.unmountSurfaces(n),xi(xi({},e),{},{popup:!1===t.popup?void 0:e.popup,popups:!1===t.popup?[]:e.popups,webchat:!1===t.webchat?void 0:e.webchat,whatsapp:!1===t.whatsappWidget?void 0:e.whatsapp})}},{key:"hasMountedSurfaces",value:function(e){var t=e.popups,n=void 0===t?[]:t,r=e.webchat,i=e.whatsapp;return n.length>0||!!r||!!i}},{key:"restoreRuntime",value:function(e){Object.assign(this,e)}},{key:"configurationSnapshot",value:function(){return{apiRoot:Z.apiRoot,actionCableUrl:Z.actionCableUrl,autoGenerateSession:Z.autoGenerateSession,session:Z.session,locale:Z.locale,forms:{autoMount:Z.forms.autoMount,successMessage:Z.forms.successMessage},popup:{id:Z.popup.id,container:Z.popup.container,device:Z.popup.device},webchat:{id:Z.webchat.id,container:Z.webchat.container,placement:Z.webchat.placement,style:this.clone(Z.webchat.style),appearance:this.clone(Z.webchat.appearance),whatsapp:this.clone(Z.webchat.whatsapp),mode:Z.webchat.mode,behaviour:this.clone(Z.webchat.behaviour),behaviourOverride:Z.webchat.hasBehaviourOverride,strategy:Z.webchat._strategy},whatsapp:{id:Z.whatsapp.id,container:Z.whatsapp.container,placement:Z.whatsapp.placement,appearance:this.clone(Z.whatsapp.appearance),number:Z.whatsapp.number,body:Z.whatsapp.body}}}},{key:"restoreConfiguration",value:function(e){Z.apiRoot=e.apiRoot,Z.actionCableUrl=e.actionCableUrl,Z.autoGenerateSession=e.autoGenerateSession,Z.session=e.session,Z.locale=e.locale,Z.forms.assign(e.forms),Z.popup.assign(e.popup),Z.webchat.assign(e.webchat),Z.webchat.behaviourOverride=e.webchat.behaviourOverride,Z.whatsapp.assign(e.whatsapp)}},{key:"clone",value:function(e){return Array.isArray(e)?e.map(e=>this.clone(e)):this.isPlainObject(e)?Object.fromEntries(Object.entries(e).map(e=>{var t=wi(e,2),n=t[0],r=t[1];return[n,this.clone(r)]})):e}},{key:"mergeWebchatConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergeWhatsAppConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"mergePopupConfig",value:function(e,t){return this.deepMergePlainObjects(e,t)}},{key:"popupConfigs",value:function(e,t){if(t.id)return[t];var n=Array.isArray(e&&e.popups)?e.popups.filter(e=>e&&e.id):[];return(n.length>0?n:[e&&e.popup||{}]).filter(e=>e&&e.id).map(e=>this.mergePopupConfig(e,t)).filter((e,t,n)=>n.findIndex(t=>t.id===e.id)===t)}},{key:"deepMergePlainObjects",value:function(e,t){var n=xi({},e);return Object.entries(t).forEach(e=>{var t=wi(e,2),r=t[0],i=t[1];this.isPlainObject(i)&&this.isPlainObject(n[r])?n[r]=this.deepMergePlainObjects(n[r],i):n[r]=i}),n}},{key:"isPlainObject",value:function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},{key:"track",value:(r=Ei(function*(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new Rr;var n=xi(xi({},t&&t.headers||{}),this.headers),r=xi(xi({},ci.identificationData),t.user_parameters||{}),i=t&&t.url?new Bt(t.url):this.page,o=xi(xi({session:this.session,user_parameters:r,action:e},t),i.trackingData);return delete o.headers,yield xt.events.create({headers:n,body:o,keepalive:Tt(o)})}),function(e){return r.apply(this,arguments)})},{key:"identify",value:(n=Ei(function*(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yield bi.generate(this.session,e,n);if(bi.matches(ci.fingerprint,r))return new Se(!0,{json:(t=Ei(function*(){return{already_identified:!0}}),function(){return t.apply(this,arguments)})});var i=yield xt.identifications.create(xi({user_id:e},n));return i.succeeded&&ci.remember(e,n.source,r),i}),function(e){return n.apply(this,arguments)})},{key:"forget",value:function(){ci.forget()}},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return Gt.session}},{key:"isInitialized",get:function(){return void 0!==Gt.session}},{key:"notInitialized",get:function(){return!this.business||void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new Rr;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],t&&Ci(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,r,i}();Ai.eventEmitter=new ce,Ai.forms=void 0,Ai.business=void 0,Ai.popup=void 0,Ai.popups=[],Ai.webchat=void 0,Ai.whatsapp=void 0,Ai.initializationGeneration=0,Ai.initializationBaseline=void 0;const ji=Ai;function _i(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Mi(e,t){for(var n=0;n{var t=e.type,n=e.parameter,r=this.inputTargets.find(e=>e.name===n);r.setCustomValidity(ji.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",()=>{r.setCustomValidity(""),r.reportValidity()})}),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach(e=>e.disabled=!0),this.completed()},o=function(){var e=this,t=arguments;return new Promise(function(n,r){var o=i.apply(e,t);function a(e){_i(o,n,r,a,s,"next",e)}function s(e){_i(o,n,r,a,s,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!Z.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof Z.forms.successMessage?this.element.innerHTML=Z.forms.successMessage:this.element.innerHTML=ji.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.inputTargets.forEach(e=>{var t=e.closest("article").querySelector("[data-error-container]");e.validity.valid?t.innerText="":t.innerText=e.validationMessage})}},{key:"clearErrorMessages",value:function(){this.inputTargets.forEach(e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""})}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter(e=>e.required)}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&Mi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o}(g.xI);function Vi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function zi(e){for(var t=1;t0?e:this.getCardScrollAmount()}},{key:"getNextPageScrollLeft",value:function(){var e=this.getCurrentScrollLeft(),t=e+this.carouselContainerTarget.clientWidth,n=this.getCardMetrics().find(e=>e.end>t+1),r=n?this.getPageAlignedScrollLeft(n.start):e+this.getPageScrollAmount(),i=e+this.getPageScrollAmount();return this.clampScrollLeft(r>e+1?r:i)}},{key:"getPreviousPageScrollLeft",value:function(){var e,t,n=this.getCurrentScrollLeft();if(n<=1)return 0;var r=Math.max(n-this.getPageScrollAmount(),0);if(r<=1)return 0;var i=this.getCardMetrics(),o=i.find(e=>e.start>=r-1&&e.starte.start{var t=this.getCardScrollLeft(e);return{start:t,end:t+e.offsetWidth}})}},{key:"getCardScrollLeft",value:function(e){var t=e.getBoundingClientRect(),n=this.carouselContainerTarget.getBoundingClientRect();return t.left||t.width||n.left||n.width?t.left-n.left+this.carouselContainerTarget.scrollLeft:e.offsetLeft||0}},{key:"getCurrentScrollLeft",value:function(){return this.clampScrollLeft(this.carouselContainerTarget.scrollLeft)}},{key:"clampScrollLeft",value:function(e){var t=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);return Math.min(Math.max(e,0),t)}},{key:"getGap",value:function(){var e=window.getComputedStyle(this.carouselContainerTarget),t=Number.parseFloat(e.columnGap||e.gap);return Number.isFinite(t)?t:16}},{key:"getFadeDistance",value:function(){return Number.isFinite(this.fadeDistanceValue)?this.fadeDistanceValue:64}},{key:"getPageStartOffset",value:function(){return Number.isFinite(this.pageStartOffsetValue)?this.pageStartOffsetValue:0}},{key:"observeContainerSize",value:function(){this.hasCarouselContainerTarget&&window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.updateFades()),this.resizeObserver.observe(this.carouselContainerTarget))}},{key:"updateFades",value:function(){if(this.hasCarouselContainerTarget){var e=Math.max(this.carouselContainerTarget.scrollWidth-this.carouselContainerTarget.clientWidth,0);if(e<=1)return this.hideFade(this.leftFadeTarget),void this.hideFade(this.rightFadeTarget);var t=Math.min(Math.max(this.carouselContainerTarget.scrollLeft,0),e),n=this.getFadeDistance();this.setFadeOpacity(this.leftFadeTarget,t/n),this.setFadeOpacity(this.rightFadeTarget,(e-t)/n)}}},{key:"setFadeOpacity",value:function(e,t){var n=Math.min(Math.max(t,0),1);n<=.05?this.hideFade(e):(e.classList.remove("hidden"),e.removeAttribute("disabled"),e.removeAttribute("tabindex"),e.setAttribute("aria-hidden","false"),e.style.opacity=n.toFixed(3),e.style.pointerEvents="auto")}},{key:"hideFade",value:function(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")}}],r&&Ui(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(g.xI);function Yi(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function Xi(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){Yi(o,r,i,a,s,"next",e)}function s(e){Yi(o,r,i,a,s,"throw",e)}a(void 0)})}}function Zi(e,t){for(var n=0;n{e.disabled=!0});var t=yield xt.popups.submit(this.idValue,this.submissionPayload());if(this.submitButtonTargets.forEach(e=>{e.disabled=!1}),t.failed)yield this.handleSubmissionError(t);else{try{var n=yield t.json();this.submissionId=n.id,this.submissionVerificationState=n.verification_state,this.submissionActionToken=n.action_token,this.submissionDeliveryStatus=n.delivery_status,this.submissionDeliveryChannel=n.delivery_channel,this.submissionDestination=n.destination}catch(e){this.submissionId=null}this.showCompleted()}}else this.showErrorMessages(this.currentStepInputs)}),function(e){return s.apply(this,arguments)})},{key:"evaluateDisplay",value:function(){!this.dismissed&&this.matchesDevice()&&this.rulesWithoutScrollPass()?!this.scrollRule||this.scrollRulePasses()?(window.removeEventListener("scroll",this.onScroll),this.claimDisplay()&&this.showInitialState()):window.addEventListener("scroll",this.onScroll,{passive:!0}):this.releaseDisplay()}},{key:"claimDisplay",value:function(){var e=this.constructor;return!(e.displayOwner&&e.displayOwner!==this||(e.displayOwner=this,0))}},{key:"releaseDisplay",value:function(){var e=this.constructor;e.displayOwner===this&&(e.displayOwner=void 0,e.controllers.forEach(e=>{e!==this&&e.evaluateDisplay()}))}},{key:"showInitialState",value:function(){if(this.showElement(this.element),this.hasBubbleValue&&this.hasBubbleTarget)return this.showElement(this.bubbleTarget),void this.hideElement(this.dialogTarget);this.showElement(this.dialogTarget),this.markViewed()}},{key:"showStep",value:function(e){this.stepIndex=e,this.stepTargets.forEach((t,n)=>{this.toggleElement(t,n!==e)}),this.hideElement(this.completedTarget)}},{key:"showCompleted",value:function(){this.stepTargets.forEach(e=>this.hideElement(e)),this.interpolateCompletionCopy(),this.configureCompletionActions(),this.showElement(this.completedTarget)}},{key:"interpolateCompletionCopy",value:function(){var e=this.completedIdentity;if(e){var t={destination:e.value,channel:this.submissionDeliveryChannel||e.kind};this.completionTextTemplates.forEach(e=>{var n=e.node,r=e.template;n.nodeValue=r.replace(/\{(destination|channel)\}/g,(e,n)=>t[n]||e)})}}},{key:"identityValue",value:function(e){var t=this.inputValue(e).trim();if("phone"!==e.dataset.popupFieldKind||t.startsWith("+"))return t;var n=e.dataset.popupPhonePrefix;return n?"".concat(n).concat(t.replace(/^0+/,"")):t}},{key:"configureCompletionActions",value:function(){var e;if("not_required"===this.submissionDeliveryStatus)return this.renderNoDeliveryCopy(),void(null===(e=this.completedTarget.querySelector("[data-delivery-actions]"))||void 0===e||e.setAttribute("hidden",""));var t=this.completedIdentity;t&&(this.hasChangeDestinationButtonTarget&&(this.changeDestinationButtonTarget.textContent=this.changeDestinationButtonTarget.dataset["".concat(t.kind,"Label")],this.showElement(this.changeDestinationButtonTarget)),this.submissionId&&this.submissionActionToken&&"queued"===this.submissionDeliveryStatus&&"unverified"===this.submissionVerificationState&&this.hasResendButtonTarget&&(this.showElement(this.resendButtonTarget),this.startResendCooldown(60)))}},{key:"resend",value:(a=Xi(function*(e){if(e&&e.preventDefault(),this.submissionId&&this.submissionActionToken&&!this.resendPending&&!this.resendCooldownActive&&this.completedIdentity){this.resendPending=!0,this.resendButtonTarget.disabled=!0;try{var t,n=yield xt.popups.resend(this.idValue,this.submissionId,this.submissionActionToken),r=Number(null===(t=n.data.headers)||void 0===t?void 0:t.get("Retry-After"))||60;n.succeeded||429===n.data.status?this.startResendCooldown(r):this.resendButtonTarget.disabled=!1}catch(e){this.resendButtonTarget.disabled=!1}finally{this.resendPending=!1}}}),function(e){return a.apply(this,arguments)})},{key:"changeDestination",value:(o=Xi(function*(e){var t;e&&e.preventDefault();var n=null===(t=this.completedIdentity)||void 0===t?void 0:t.input;if(n){var r=this.stepTargets.findIndex(e=>e.dataset.stepId===n.dataset.popupStepId);r<0||(this.stopResendCooldown(),this.submissionId=null,this.submissionActionToken=null,this.submissionVerificationState=null,this.submissionDeliveryStatus=null,this.submissionDeliveryChannel=null,this.submissionDestination=null,this.showStep(r),n.focus())}}),function(e){return o.apply(this,arguments)})},{key:"startResendCooldown",value:function(e){this.stopResendCooldown(),this.resendCooldownEndsAt=Date.now()+1e3*Math.max(e,1),this.updateResendCountdown(),this.resendTimer=window.setInterval(()=>this.updateResendCountdown(),1e3)}},{key:"stopResendCooldown",value:function(){this.resendTimer&&window.clearInterval(this.resendTimer),this.resendTimer=null,this.resendCooldownEndsAt=null}},{key:"updateResendCountdown",value:function(){var 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);var t="".concat(Math.floor(e/60),":").concat(String(e%60).padStart(2,"0")),n=this.resendButtonTarget.dataset.countdownLabel||"".concat(this.resendLabel," %{time}");this.resendButtonTarget.textContent=n.replace("%{time}",t),this.resendButtonTarget.disabled=!0}},{key:"resendCooldownActive",get:function(){return this.resendCooldownEndsAt>Date.now()}},{key:"completionIdentity",get:function(){return this.identityInputs.map(e=>({input:e,kind:e.dataset.popupFieldKind,value:this.identityValue(e)})).find(e=>e.value)}},{key:"completedIdentity",get:function(){if(this.submissionDestination&&this.submissionDeliveryChannel){var e="email"===this.submissionDeliveryChannel?"email":"phone";return{input:this.identityInputs.find(t=>t.dataset.popupFieldKind===e),kind:e,value:this.submissionDestination}}return this.completionIdentity}},{key:"renderNoDeliveryCopy",value:function(){var e=this.completedTarget.querySelector(".hellotext--popup__completion-headline"),t=this.completedTarget.querySelector(".hellotext--popup__completion-description");if(e&&this.completedTarget.dataset.notRequiredHeadline){e.innerHTML="";var n=document.createElement("h4"),r=document.createElement("strong");r.textContent=this.completedTarget.dataset.notRequiredHeadline,n.appendChild(r),e.appendChild(n)}t&&(t.textContent=this.completedTarget.dataset.notRequiredDescription||"")}},{key:"currentStepValid",value:function(){return this.currentStepInputs.every(e=>e.checkValidity())}},{key:"showErrorMessages",value:function(e){e.forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent=e.validity.valid?"":e.validationMessage)})}},{key:"clearErrorMessages",value:function(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.inputTargets).forEach(e=>{var t,n=null===(t=e.closest(".hellotext--popup-field"))||void 0===t?void 0:t.querySelector("[data-error-container]");n&&(n.textContent="")})}},{key:"clearCustomValidity",value:function(){this.inputTargets.forEach(e=>e.setCustomValidity(""))}},{key:"handleSubmissionError",value:(i=Xi(function*(e){var t;try{t=yield e.json()}catch(e){return}(t.errors||[]).forEach(e=>{var t=this.inputForError(e);t&&(t.setCustomValidity(e.description||t.validationMessage),t.reportValidity())}),this.showErrorMessages(this.inputTargets)}),function(e){return i.apply(this,arguments)})},{key:"inputForError",value:function(e){var t=e.parameter;return t?this.inputTargets.find(e=>e.dataset.popupFieldKind===t||e.dataset.popupFieldKey===t):null}},{key:"submissionPayload",value:function(){var e={metadata:{capture:this.captureValue||{},fields:{},steps:[]}};return this.stepTargets.forEach(t=>{var n={};this.inputsForStep(t).forEach(t=>{var r=this.inputValue(t),i=t.dataset.popupFieldKey||t.name;n[i]=r,e.metadata.fields[i]=r,"email"===t.dataset.popupFieldKind&&(e.email=r),"phone"===t.dataset.popupFieldKind&&(e.phone=r)}),e.metadata.steps.push({id:t.dataset.stepId,name:t.dataset.stepName,fields:n})}),e}},{key:"inputValue",value:function(e){return"checkbox"===e.type?e.checked:e.value}},{key:"inputsForStep",value:function(e){return this.inputTargets.filter(t=>t.dataset.popupStepId===e.dataset.stepId)}},{key:"identityInputs",get:function(){var e=this.inputTargets.filter(e=>["email","phone"].includes(e.dataset.popupFieldKind));return e.filter(e=>e.required).concat(e.filter(e=>!e.required))}},{key:"completionTextTemplates",get:function(){if(this._completionTextTemplates)return this._completionTextTemplates;var 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}},{key:"rulesWithoutScrollPass",value:function(){return this.conditions.filter(e=>"scroll_depth"!==e.type).every(e=>this.conditionPasses(e))}},{key:"conditionPasses",value:function(e){return"properties"===e.group&&"page_property"===e.type?this.pagePropertyRulePasses(e):"actions"!==e.group||"viewed_popup"!==e.type||this.viewedPopupRulePasses(e)}},{key:"pagePropertyRulePasses",value:function(e){var t=String(e.value||"").trim().toLowerCase();if(!t)return!0;var n=this.pagePropertyValue(e.field).includes(t);return"does_not_contain"===e.query?!n:n}},{key:"pagePropertyValue",value:function(e){return"url"===e?window.location.href.toLowerCase():"title"===e?document.title.toLowerCase():window.location.pathname.toLowerCase()}},{key:"viewedPopupRulePasses",value:function(e){var t=this.popupWasViewed();return!1===e.inclusion?!t:t}},{key:"scrollRulePasses",value:function(){return this.scrollPercentage>=Number(this.scrollRule.value||0)}},{key:"matchesDevice",value:function(){return"all"===this.deviceValue||("mobile"===this.deviceValue?window.innerWidth<768:"desktop"!==this.deviceValue||window.innerWidth>=768)}},{key:"markViewed",value:function(){try{localStorage.setItem(this.viewedStorageKey,"true")}catch(e){}}},{key:"popupWasViewed",value:function(){try{return"true"===localStorage.getItem(this.viewedStorageKey)}catch(e){return!1}}},{key:"showElement",value:function(e){e.hidden=!1}},{key:"hideElement",value:function(e){e.hidden=!0}},{key:"toggleElement",value:function(e,t){e.hidden=t}},{key:"currentStep",get:function(){return this.stepTargets[this.stepIndex]}},{key:"currentStepInputs",get:function(){return this.inputsForStep(this.currentStep)}},{key:"conditions",get:function(){var e;return(null===(e=this.rulesValue)||void 0===e?void 0:e.conditions)||[]}},{key:"scrollRule",get:function(){return this.conditions.find(e=>"actions"===e.group&&"scroll_depth"===e.type)}},{key:"scrollPercentage",get:function(){var e=document.documentElement.scrollHeight-window.innerHeight;return e<=0?100:Math.round(window.scrollY/e*100)}},{key:"viewedStorageKey",get:function(){return"hellotext:popup:".concat(this.idValue,":viewed")}}],r&&Zi(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l}(g.xI);io.controllers=new Set,io.displayOwner=void 0,io.targets=["bubble","dialog","step","completed","input","submitButton","resendButton","changeDestinationButton"],io.values={capture:Object,device:String,hasBubble:Boolean,id:String,rules:Object};const oo=["start","end"],ao=["top","right","bottom","left"].reduce((e,t)=>e.concat(t,t+"-"+oo[0],t+"-"+oo[1]),[]),so=Math.min,lo=Math.max,co=Math.round,uo=Math.floor,ho=e=>({x:e,y:e}),po={left:"right",right:"left",bottom:"top",top:"bottom"};function fo(e,t){return"function"==typeof e?e(t):e}function mo(e){return e.split("-")[0]}function yo(e){return e.split("-")[1]}function go(e){return"x"===e?"y":"x"}function vo(e){return"y"===e?"height":"width"}function bo(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function wo(e){return go(bo(e))}function Oo(e,t,n){void 0===n&&(n=!1);const r=yo(e),i=wo(e),o=vo(i);let a="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Co(a)),[a,Co(a)]}function To(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const xo=["left","right"],So=["right","left"],ko=["top","bottom"],Eo=["bottom","top"];function Co(e){const t=mo(e);return po[t]+e.slice(t.length)}function Po(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Ao(e,t,n){let{reference:r,floating:i}=e;const o=bo(t),a=wo(t),s=vo(a),l=mo(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,p=r[s]/2-i[s]/2;let d;switch(l){case"top":d={x:u,y:r.y-i.height};break;case"bottom":d={x:u,y:r.y+r.height};break;case"right":d={x:r.x+r.width,y:h};break;case"left":d={x:r.x-i.width,y:h};break;default:d={x:r.x,y:r.y}}const f=yo(t);return f&&(d[a]+=p*("end"===f?1:-1)*(n&&c?-1:1)),d}async function jo(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:d=0}=fo(t,e),f=function(e){return"number"!=typeof e?function(e){var t,n,r,i;return{top:null!=(t=e.top)?t:0,right:null!=(n=e.right)?n:0,bottom:null!=(r=e.bottom)?r:0,left:null!=(i=e.left)?i:0}}(e):{top:e,right:e,bottom:e,left:e}}(d),m=s[p?"floating"===h?"reference":"floating":h],y=Po(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(m)))||n?m:m.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(s.floating)),boundary:c,rootBoundary:u,strategy:l})),g="floating"===h?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,v=await(null==o.getOffsetParent?void 0:o.getOffsetParent(s.floating)),b=await(null==o.isElement?void 0:o.isElement(v))&&await(null==o.getScale?void 0:o.getScale(v))||{x:1,y:1},w=Po(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:g,offsetParent:v,strategy:l}):g);return{top:(y.top-w.top+f.top)/b.y,bottom:(w.bottom-y.bottom+f.bottom)/b.y,left:(y.left-w.left+f.left)/b.x,right:(w.right-y.right+f.right)/b.x}}const _o=new Set(["left","top"]);function Mo(){return"undefined"!=typeof window}function Io(e){return No(e)?(e.nodeName||"").toLowerCase():"#document"}function Lo(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Do(e){var t;return null==(t=(No(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function No(e){return!!Mo()&&(e instanceof Node||e instanceof Lo(e).Node)}function Ro(e){return!!Mo()&&(e instanceof Element||e instanceof Lo(e).Element)}function Fo(e){return!!Mo()&&(e instanceof HTMLElement||e instanceof Lo(e).HTMLElement)}function Bo(e){return!(!Mo()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Lo(e).ShadowRoot)}function Vo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Yo(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==i&&"contents"!==i}function zo(e){return/^(table|td|th)$/.test(Io(e))}function qo(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const Uo=/transform|translate|scale|rotate|perspective|filter/,Wo=/paint|layout|strict|content/,Ho=e=>!!e&&"none"!==e;let $o;function Ko(e){const t=Ro(e)?Yo(e):e;return Ho(t.transform)||Ho(t.translate)||Ho(t.scale)||Ho(t.rotate)||Ho(t.perspective)||!Go()&&(Ho(t.backdropFilter)||Ho(t.filter))||Uo.test(t.willChange||"")||Wo.test(t.contain||"")}function Go(){return null==$o&&($o="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),$o}function Jo(e){return/^(html|body|#document)$/.test(Io(e))}function Yo(e){return Lo(e).getComputedStyle(e)}function Xo(e){return Ro(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Zo(e){if("html"===Io(e))return e;const t=e.assignedSlot||e.parentNode||Bo(e)&&e.host||Do(e);return Bo(t)?t.host:t}function Qo(e){const t=Zo(e);return Jo(t)?(e.ownerDocument||e).body:Fo(t)&&Vo(t)?t:Qo(t)}function ea(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Qo(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),a=Lo(i);if(o){const e=ta(a);return t.concat(a,a.visualViewport||[],Vo(i)?i:[],e&&n?ea(e):[])}return t.concat(i,ea(i,[],n))}function ta(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function na(e){const t=Yo(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Fo(e),o=i?e.offsetWidth:n,a=i?e.offsetHeight:r,s=co(n)!==o||co(r)!==a;return s&&(n=o,r=a),{width:n,height:r,$:s}}function ra(e){return Ro(e)?e:e.contextElement}function ia(e){const t=ra(e);if(!Fo(t))return ho(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=na(t);let a=(o?co(n.width):n.width)/r,s=(o?co(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const oa=ho(0);function aa(e){const t=Lo(e);return Go()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:oa}function sa(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=ra(e);let a=ho(1);t&&(r?Ro(r)&&(a=ia(r)):a=ia(e));const s=function(e,t,n){return void 0===t&&(t=!1),!!n&&t&&n===Lo(e)}(o,n,r)?aa(o):ho(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,u=i.width/a.x,h=i.height/a.y;if(o&&r){const e=Lo(o),t=Ro(r)?Lo(r):r;let n=e,i=ta(n);for(;i&&t!==n;){const e=ia(i),t=i.getBoundingClientRect(),r=Yo(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,u*=e.x,h*=e.y,l+=o,c+=a,n=Lo(i),i=ta(n)}}return Po({width:u,height:h,x:l,y:c})}function la(e,t){const n=Xo(e).scrollLeft;return t?t.left+n:sa(Do(e)).left+n}function ca(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-la(e,n),y:n.top+t.scrollTop}}function ua(e,t,n){let r;if("viewport"===t||"layoutViewport"===t)r=function(e,t,n){void 0===n&&(n="viewport");const r="layoutViewport"===n,i=Lo(e),o=Do(e),a=i.visualViewport;let s=o.clientWidth,l=o.clientHeight,c=0,u=0;if(a){const e=!Go()||"fixed"===t;r?e||(c=-a.offsetLeft,u=-a.offsetTop):(s=a.width,l=a.height,e&&(c=a.offsetLeft,u=a.offsetTop))}if(la(o)<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),r="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(o.clientWidth-t.clientWidth-r),a="stable both-edges"===getComputedStyle(o).scrollbarGutter?i/2:i;a<=25&&(s-=a)}return{width:s,height:l,x:c,y:u}}(e,n,t);else if("document"===t)r=function(e){const t=Xo(e),n=e.ownerDocument.body,r=lo(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=lo(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+la(e);const a=-t.scrollTop;return"rtl"===Yo(n).direction&&(o+=lo(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:a}}(Do(e));else if(Ro(t))r=function(e,t){const n=sa(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=ia(e);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=aa(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Po(r)}function ha(e,t,n){const r=Fo(t),i=Do(t),o="fixed"===n,a=sa(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const l=ho(0);if((r||!o)&&(("body"!==Io(t)||Vo(i))&&(s=Xo(t)),r)){const e=sa(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!r&&i&&(l.x=la(i));const c=!i||r||o?ho(0):ca(i,s);return{x:a.left+s.scrollLeft-l.x-c.x,y:a.top+s.scrollTop-l.y-c.y,width:a.width,height:a.height}}function pa(e){return"static"===Yo(e).position}function da(e,t){if(!Fo(e)||"fixed"===Yo(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Do(e)===n&&(n=n.ownerDocument.body),n}function fa(e,t){const n=Lo(e);if(qo(e))return n;if(!Fo(e)){let t=Zo(e);for(;t&&!Jo(t);){if(Ro(t)&&!pa(t))return t;t=Zo(t)}return n}let r=da(e,t);for(;r&&zo(r)&&pa(r);)r=da(r,t);return r&&Jo(r)&&pa(r)&&!Ko(r)?n:r||function(e){let t=Zo(e);for(;Fo(t)&&!Jo(t);){if(Ko(t))return t;if(qo(t))return null;t=Zo(t)}return null}(e)||n}const ma={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,a=Do(r),s=!!t&&qo(t.floating);if(r===a||s&&o)return n;let l={scrollLeft:0,scrollTop:0},c=ho(1);const u=ho(0),h=Fo(r);if((h||!o)&&(("body"!==Io(r)||Vo(a))&&(l=Xo(r)),h)){const e=sa(r);c=ia(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}const p=!a||h||o?ho(0):ca(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}},getDocumentElement:Do,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?qo(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=ea(e,[],!1).filter(e=>Ro(e)&&"body"!==Io(e)),i=null;const o="fixed"===Yo(e).position;let a=o?Zo(e):e;for(;Ro(a)&&!Jo(a);){const e=Yo(a),t=Ko(a),n=i?i.position:o?"fixed":"";t||"fixed"!==n&&("absolute"!==n||"static"!==e.position)?i=e:r=r.filter(e=>e!==a),a=Zo(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=ua(t,o[0],i);let s=a.top,l=a.right,c=a.bottom,u=a.left;for(let e=1;eyo(t)===e),...n.filter(t=>yo(t)!==e)]:n.filter(e=>mo(e)===e)).filter(n=>!e||yo(n)===e||!!t&&To(n)!==n)}(h||null,d,p):p,y=(null==(n=a.autoPlacement)?void 0:n.index)||0,g=m[y];if(null==g)return{};if(s!==g)return{reset:{placement:m[0]}};const v=await l.detectOverflow(t,f),b=Oo(g,o,await(null==l.isRTL?void 0:l.isRTL(c.floating))),w=[v[mo(g)],v[b[0]],v[b[1]]],O=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:g,overflows:w}],T=m[y+1];if(T)return{data:{index:y+1,overflows:O},reset:{placement:T}};const x=O.map(e=>{const t=yo(e.placement);return[e.placement,t&&u?e.overflows.slice(0,2).reduce((e,t)=>e+t,0):e.overflows[0],e.overflows]}).sort((e,t)=>e[1]-t[1]),S=(null==(i=x.filter(e=>e[2].slice(0,yo(e[0])?2:3).every(e=>e<=0))[0])?void 0:i[0])||x[0][0];return S!==s?{data:{index:y+1,overflows:O},reset:{placement:S}}:{}}}},ba=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=fo(e,t),u={x:n,y:r},h=await o.detectOverflow(t,c),p=bo(i),d=go(p);let f=u[d],m=u[p];const y=(e,t)=>{return n=t+h["y"===e?"top":"left"],r=t,i=t-h["y"===e?"bottom":"right"],lo(n,so(r,i));var n,r,i};a&&(f=y(d,f)),s&&(m=y(p,m));const g=l.fn({...t,[d]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[d]:a,[p]:s}}}}}},wa=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...y}=fo(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const g=mo(i),v=bo(s),b=mo(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),O=p||(b||!m?[Co(s)]:function(e){const t=Co(e);return[To(e),t,To(t)]}(s)),T="none"!==f;!p&&T&&O.push(...function(e,t,n,r){const i=yo(e);let o=function(e,t,n){switch(e){case"top":case"bottom":return n?t?So:xo:t?xo:So;case"left":case"right":return t?ko:Eo;default:return[]}}(mo(e),"start"===n,r);return i&&(o=o.map(e=>e+"-"+i),t&&(o=o.concat(o.map(To)))),o}(s,m,f,w));const x=[s,...O],S=await l.detectOverflow(t,y),k=[];let E=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&k.push(S[g]),h){const e=Oo(i,a,w);k.push(S[e[0]],S[e[1]])}if(E=[...E,{placement:i,overflows:k}],!k.every(e=>e<=0)){var C,P;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=x[e];if(t&&("alignment"!==h||v===bo(t)||E.every(e=>bo(e.placement)!==v||e.overflows[0]>0)))return{data:{index:e,overflows:E},reset:{placement:t}};let n=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(d){case"bestFit":{var A;const e=null==(A=E.filter(e=>{if(T){const t=bo(e.placement);return t===v||"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:A[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};var Oa=e=>{Object.assign(e,{show(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!0},hide(){this.openValue=!1},toggle(){var e;null===(e=this.cancelBehaviourOpen)||void 0===e||e.call(this),this.openValue=!this.openValue},setupFloatingUI(e){var t=e.trigger,n=e.popover,r=e.strategy;this.floatingUICleanup=function(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=ra(e),u=i||o?[...c?ea(c):[],...t?ea(t):[]]:[];u.forEach(e=>{i&&e.addEventListener("scroll",n),o&&e.addEventListener("resize",n)});const h=c&&s?function(e,t,n){let r,i=null;const o=Do(e);function a(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}function s(n,l){void 0===n&&(n=!1),void 0===l&&(l=1),a();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:d}=c;if(n||t(),!p||!d)return;const f={rootMargin:-uo(h)+"px "+-uo(o.clientWidth-(u+p))+"px "+-uo(o.clientHeight-(h+d))+"px "+-uo(u)+"px",threshold:lo(0,so(1,l))||1};let m=!0;function y(t){const n=t[0].intersectionRatio;if(!ya(c,e.getBoundingClientRect()))return s();if(n!==l){if(!m)return s();n?s(!1,n):r=setTimeout(()=>{s(!1,1e-7)},1e3)}m=!1}try{i=new IntersectionObserver(y,{...f,root:o.ownerDocument})}catch(e){i=new IntersectionObserver(y,f)}i.observe(e)}const l=Lo(e),c=()=>s(n);return l.addEventListener("resize",c),s(!0),()=>{l.removeEventListener("resize",c),a()}}(c,n,o):null;let p,d=-1,f=null;a&&(f=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&f&&t&&(f.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),c&&!l&&f.observe(c),t&&f.observe(t));let m=l?sa(e):null;return l&&function t(){const r=sa(e);m&&!ya(m,r)&&n(),m=r,p=requestAnimationFrame(t)}(),n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),null==h||h(),null==(e=f)||e.disconnect(),f=null,l&&cancelAnimationFrame(p)}}(t,n,()=>{((e,t,n)=>{const r=new Map,i=null!=n?n:{},o={...ma,...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:a}=n,s=a.detectOverflow?a:{...a,detectOverflow:jo},l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=Ao(c,r,l),p=r,d=0;const f={};for(let n=0;n{var t=e.x,r=e.y,i=e.strategy,o={left:"".concat(t,"px"),top:"".concat(r,"px"),position:i};Object.assign(n.style,o)})})},openValueChanged(){var e;this.disabledValue||(this.openValue?(null===(e=this.preparePopoverOpenAnimation)||void 0===e||e.call(this),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()))}})};function Ta(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,a,s=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(s.push(r.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return La(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?La(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(e,2),r=n[0],i=n[1];t.searchParams.append(r,i)}),yield fetch(t,{method:"GET",headers:ji.headers})}),function(e){return o.apply(this,arguments)})},{key:"catchUp",value:function(e){return this.index({after_id:e,session:ji.session})}},{key:"create",value:(i=Na(function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(ji.business.id)},body:e});return new Se(t.ok,t)}),function(e){return i.apply(this,arguments)})},{key:"markAsSeen",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=e?this.url+"/".concat(e):this.url+"/seen";fetch(t,{method:"PATCH",headers:ji.headers,body:JSON.stringify({session:ji.session})})}},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return Z.endpoint("public/webchats/:id/messages")}}],n&&Ra(t.prototype,n),r&&Ra(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r,i,o}();const Va=Ba;function za(e,t){for(var n=0;n{a.send(s)})}},{key:"onMessage",value:function(t){var n=e=>{var n=JSON.parse(e.data),r=n.type,i=n.message;this.ignoredEvents.includes(r)||t(i)};e.messageHandlers.add(n),e.ensureWebSocket().addEventListener("message",n)}},{key:"onDisconnect",value:function(t){e.disconnectHandlers.add(t)}},{key:"onSubscriptionConfirmed",value:function(t){e.subscriptionConfirmHandlers.add(t)}},{key:"webSocket",get:function(){return e.ensureWebSocket()}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}],r=[{key:"ensureWebSocket",value:function(){return this.webSocket&&!this.closedWebSocket(this.webSocket)?this.webSocket:(this.webSocket&&(this.needsResubscribe=!0),this.openWebSocket())}},{key:"openWebSocket",value:function(){this.clearReconnectTimeout();var e=new WebSocket(Z.actionCableUrl);return this.webSocket=e,this.installWebSocketHandlers(e),e}},{key:"installWebSocketHandlers",value:function(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)})}},{key:"handleOpen",value:function(e){e===this.webSocket&&(this.reconnectAttempts=0,this.needsResubscribe&&(this.needsResubscribe=!1,this.resubscribeChannels()))}},{key:"handleControlMessage",value:function(e){var t;try{t=JSON.parse(e.data)}catch(e){return}"confirm_subscription"===t.type&&this.subscriptionConfirmHandlers.forEach(e=>e(t.identifier))}},{key:"handleDisconnect",value:function(e){e===this.webSocket&&(this.disconnectHandlers.forEach(e=>e()),this.webSocket=null,this.needsResubscribe=!0,this.scheduleReconnect())}},{key:"scheduleReconnect",value:function(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts+=1,this.openWebSocket()},this.reconnectDelay))}},{key:"clearReconnectTimeout",value:function(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}},{key:"resubscribeChannels",value:function(){this.channels.forEach(e=>{var t=e.resubscribe||e.subscribe;"function"==typeof t&&t.call(e)})}},{key:"closedWebSocket",value:function(e){return e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING}},{key:"reconnectDelay",get:function(){var e=Math.min(this.reconnectMaxDelay,this.reconnectBaseDelay*2**this.reconnectAttempts);return e+Math.round(e*this.reconnectJitter*Math.random())}}],n&&za(t.prototype,n),r&&za(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n,r}();function Wa(e,t){for(var n=0;ni.handleSubscriptionConfirmed(e)),i.subscribe(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Xa(e,t)}(t,e),n=t,(r=[{key:"subscribe",value:function(){this.subscribed=!0;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"subscribe",identifier:e})}},{key:"unsubscribe",value:function(){this.subscribed=!1;var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"unsubscribe",identifier:e})}},{key:"resubscribe",value:function(){!1!==this.subscribed&&(this.awaitingReconnectConfirmation=!0,this.subscribe())}},{key:"onReconnect",value:function(e){this.reconnectCallbacks.add(e)}},{key:"handleSubscriptionConfirmed",value:function(e){this.awaitingReconnectConfirmation&&this.matchesIdentifier(e)&&(this.awaitingReconnectConfirmation=!1,this.reconnectCallbacks.forEach(e=>e()))}},{key:"matchesIdentifier",value:function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return!1}return"WebchatChannel"===t.channel&&t.id===this.id&&t.session===this.session&&t.conversation===this.conversation}},{key:"startTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"message",identifier:e,data:{action:"started_typing"}})}},{key:"stopTypingIndicator",value:function(){var e={channel:"WebchatChannel",id:this.id,session:this.session,conversation:this.conversation};this.send({command:"typing:stop",identifier:e,data:{action:"stopped_typing"}})}},{key:"onMessage",value:function(e){Ga(t,"onMessage",this,3)([t=>{"message"===t.type&&e(t)}])}},{key:"onReaction",value:function(e){Ga(t,"onMessage",this,3)([t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}])}},{key:"onTypingStart",value:function(e){Ga(t,"onMessage",this,3)([t=>{"started_typing"===t.type&&e(t)}])}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout(()=>{this.conversation=e,this.subscribe()},1e3)}}])&&Wa(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r}(Ua);const Qa=Za;var es=e=>{Object.assign(e,{scheduleBehaviourOpen(){if(this.shouldAutoOpenFromBehaviour()){var 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(){var 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--".concat(this.idValue,"--auto-opened")},sessionKey(){return"hellotext--webchat--".concat(this.idValue,"--auto-opened-session")}})},ts=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){var t=this.openingSequenceMessages[e];if(t){var n=1e3*this.openingSequenceMessageDelay(t);this.openingSequenceTimeout=window.setTimeout(()=>{this.openingSequenceTimeout=null,this.openingSequenceCancelled||(this.revealOpeningSequenceMessage(t),this.playOpeningSequenceMessageAt(e+1))},n)}},revealOpeningSequenceMessage(e){this.messagesContainerTarget.insertBefore(e,this.messageTemplateTarget),e.hidden=!1,this.recordOpeningSequenceMessage(e),this.scrollOpeningSequenceToBottom()},recordOpeningSequenceMessage(e){var t=e.dataset.openingSequenceMessageId;t&&!this.revealedOpeningSequenceMessageIds.includes(t)&&this.revealedOpeningSequenceMessageIds.push(t)},openingSequenceMessageDelay(e){var 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=[]}})},ns=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.teaserTarget.classList.remove("invisible"),this.showTeaserMessage(0),this.teaserMessages.length<2||this.scheduleNextTeaserMessage(0)):this.hideTeaser())},scheduleNextTeaserMessage(e){var t=e+1;if(!(t>=this.teaserMessages.length)){var n=this.teaserMessages[e],r=this.teaserPresentationDelay(n);this.teaserCycleTimeout=window.setTimeout(()=>{this.teaserCycleTimeout=null,this.showTeaserMessage(t),this.scheduleNextTeaserMessage(t)},r)}},showTeaserMessage(e){this.teaserMessages.forEach((t,n)=>{t.classList.toggle("hidden",n!==e)})},stopTeaserCycle(){null!==this.teaserCycleTimeout&&void 0!==this.teaserCycleTimeout&&(window.clearTimeout(this.teaserCycleTimeout),this.teaserCycleTimeout=null)},teaserMessageDelay(e){var t=Number(e.dataset.delaySeconds||0);return Number.isFinite(t)?t:0},teaserPresentationDelay(e){return Math.max(1e3*this.teaserMessageDelay(e),250)},hasRenderedConversationMessages(){var e=[];try{e=Array.from(this.messageTargets||[])}catch(t){e=[]}return e.some(e=>e!==this.messageTemplateTarget)},teaserSeenKey(){var e=this.hasTeaserTarget?this.teaserTarget.dataset.teaserVersion:"",t=e?":".concat(e):"";return"hellotext:webchat:".concat(this.idValue||this.element.id,":teaser-seen").concat(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())}})};function rs(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function is(e){for(var t=1;t{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})});var t=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},t)}},{key:"resetTypingIndicatorTimer",value:function(){if(this.typingIndicatorVisible){clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout);var e=this.typingIndicatorKeepAliveValue;this.incomingTypingIndicatorTimeout=setTimeout(()=>{this.clearTypingIndicator()},e)}}},{key:"clearTypingIndicator",value:function(){this.hasTypingIndicatorTarget&&this.typingIndicatorTarget.remove(),this.typingIndicatorVisible=!1,clearTimeout(this.incomingTypingIndicatorTimeout),clearTimeout(this.optimisticTypingTimeout)}},{key:"onMessageInputChange",value:function(){this.resizeInput(),clearTimeout(this.typingIndicatorTimeout),this.hasSentTypingIndicator||(this.webChatChannel.startTypingIndicator(),this.hasSentTypingIndicator=!0),this.typingIndicatorTimeout=setTimeout(()=>{this.hasSentTypingIndicator=!1},3e3)}},{key:"onOutboundMessageSent",value:function(e){var t=e.data,n={"message:sent":e=>{var 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=>{var t=this.messagesContainerTarget.querySelector("#".concat(e.id));this.markMessageFailed(t,e.reason)}};n[t.type]?n[t.type](t):console.log("Unhandled message event: ".concat(t.type))}},{key:"onScroll",value:(h=ss(function*(){if(!(this.messagesContainerTarget.scrollTop>300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:ji.session}),t=yield e.json(),n=t.next,r=t.messages;this.nextPageValue=n,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,r.forEach(e=>{var t=e.body,n=e.attachments,r=e.created_at||e.createdAt,i=this.messageTemplateTarget.cloneNode(!0);i.classList.add("hellotext--webchat-message"),i.setAttribute("data-hellotext--webchat-target","message"),i.setAttribute("data-id",e.id),r&&i.setAttribute("data-created-at",r),i.style.removeProperty("display"),Or(i.querySelector("[data-body]"),t),"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.removeAttribute("data-hellotext--webchat-target"),n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.appendChild(n)}),i.setAttribute("data-body",t),this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),r),this.messagesContainerTarget.prepend(i)}),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}}),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){q.mode===z.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"closePopover",value:function(){this.clearPopoverOpenAnimation(),this.popoverTarget.classList.remove(...this.fadeOutClasses),this.openValue=!1}},{key:"preparePopoverOpenAnimation",value:function(){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)}},{key:"clearPopoverOpenAnimation",value:function(){var e;this.popoverOpenAnimationTimeout&&(clearTimeout(this.popoverOpenAnimationTimeout),this.popoverOpenAnimationTimeout=null),null===(e=this.popoverTarget)||void 0===e||e.classList.remove("hellotext--webchat-popover-opening")}},{key:"onPopoverOpened",value:function(){var e;this.popoverTarget.classList.remove(...this.fadeOutClasses),null===(e=this.dismissTeaserForSession)||void 0===e||e.call(this),this.onMobile||this.focusComposeInput(),this.scrolled||(requestAnimationFrame(()=>{this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"})}),this.scrolled=!0),ji.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.messageTeaserValue&&(this.messageTeaserValue=null),this.startOpeningSequence(),"none"!==this.unreadCounterTarget.style.display&&(this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0",this.messagesAPI.markAsSeen())}},{key:"onPopoverClosed",value:function(){this.clearPopoverOpenAnimation(),ji.eventEmitter.dispatch("webchat:closed"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var t=e.message,n=e.reaction,r=e.type,i=this.messageTargets.find(e=>e.dataset.id===t).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.id,i=e.body,o=e.attachments,a=e.teaser,s=e.created_at||e.createdAt;if(this.claimMessageId(r)){if(null===(t=this.hideTeaser)||void 0===t||t.call(this),e.carousel)return this.insertCarouselMessage(e,n);var l=this.messageTemplateTarget.cloneNode(!0);l.classList.add("hellotext--webchat-message"),l.style.display="flex",Or(l.querySelector("[data-body]"),i),l.setAttribute("data-id",r),l.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(l,s),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),s),o&&o.forEach(e=>{var t,n=this.attachmentImageTarget.cloneNode(!0);n.src=e,n.style.display="block",null===(t=this.messageAttachmentsContainer(l))||void 0===t||t.appendChild(n)}),this.clearTypingIndicator(),this.insertMessageElement(l),ji.eventEmitter.dispatch("webchat:message:received",is(is({},e),{},{body:l.querySelector("[data-body]").innerText})),!1!==n.scroll&&l.scrollIntoView({behavior:"smooth"}),this.updateMessageTeaser(a),this.openValue?this.messagesAPI.markAsSeen(r):this.incrementUnreadCounter()}}},{key:"claimMessageId",value:function(e){var t=this.messageTargets||[];return!this.messageIds.has(e)&&(this.messageIds.add(e),!t.some(t=>t.dataset.id===e))}},{key:"captureCatchUpCursor",value:function(){this.catchUpAfterMessageId=this.lastRenderedMessageId}},{key:"catchUpMessages",value:(u=ss(function*(){var e=this.catchUpAfterMessageId;if(e&&!this.fetchingCatchUpMessages){this.fetchingCatchUpMessages=!0;try{var t=yield this.messagesAPI.catchUp(e),n=(yield t.json()).messages;(void 0===n?[]:n).forEach(e=>this.onMessageReceived(e,{scroll:!1})),this.catchUpAfterMessageId=this.lastRenderedMessageId}finally{this.fetchingCatchUpMessages=!1}}}),function(){return u.apply(this,arguments)})},{key:"lastRenderedMessageId",get:function(){var e,t=this.persistedMessageElements;return(null===(e=t[t.length-1])||void 0===e?void 0:e.dataset.id)||null}},{key:"persistedMessageElements",get:function(){return Array.from(this.messagesContainerTarget.querySelectorAll(".hellotext--webchat-message[data-id]"))}},{key:"setMessageCreatedAt",value:function(e,t){t&&e.setAttribute("data-created-at",t)}},{key:"insertMessageElement",value:function(e){var t=this.nextMessageElementFor(e);t?this.messagesContainerTarget.insertBefore(e,t):this.messagesContainerTarget.appendChild(e)}},{key:"nextMessageElementFor",value:function(e){var t=Date.parse(e.dataset.createdAt);return Number.isNaN(t)?null:this.persistedMessageElements.find(n=>{if(n===e)return!1;var r=Date.parse(n.dataset.createdAt);return!Number.isNaN(r)&&r>t})}},{key:"updateMessageTeaser",value:function(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))}},{key:"insertCarouselMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.html,i=e.created_at||e.createdAt,o=function(e){return wr(e,br)}(r).firstElementChild;o.classList.add("hellotext--webchat-message"),o.setAttribute("data-id",e.id),o.setAttribute("data-hellotext--webchat-target","message"),this.setMessageCreatedAt(o,i),this.localizeMessageTimestamps(o),this.clearTypingIndicator(),this.insertMessageElement(o),!1!==n.scroll&&o.scrollIntoView({behavior:"smooth"}),ji.eventEmitter.dispatch("webchat:message:received",is(is({},e),{},{body:(null===(t=o.querySelector("[data-body]"))||void 0===t?void 0:t.innerText)||""})),this.updateMessageTeaser(e.teaser),this.openValue?this.messagesAPI.markAsSeen(e.id):this.incrementUnreadCounter()}},{key:"resizeInput",value:function(){this.inputTarget.style.height="auto";var e=this.inputTarget.scrollHeight;this.inputTarget.style.height="".concat(Math.min(e,96),"px")}},{key:"sendQuickReplyMessage",value:(c=ss(function*(e){var t,n,r=e.detail,i=r.id,o=r.product,a=r.buttonId,s=r.body,l=r.cardElement;null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var c=new FormData;c.append("message[body]",s),i&&c.append("message[replied_to]",i),o&&c.append("message[product]",o),a&&c.append("message[button]",a),c.append("session",ji.session),c.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(c);var u,h=this.buildMessageElement(),p=null==l||null===(n=l.querySelector("img"))||void 0===n?void 0:n.cloneNode(!0);h.querySelector("[data-body]").innerText=s,p&&(p.removeAttribute("width"),p.removeAttribute("height"),null===(u=this.messageAttachmentsContainer(h))||void 0===u||u.appendChild(p)),this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(h,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(h),h.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:h.outerHTML});var d=yield this.messagesAPI.create(c);if(d.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(d,h);var f=yield d.json();this.dispatch("set:id",{target:h,detail:f.id}),this.localizeMessageTimestamp(h.querySelector("[data-message-timestamp]"),f.created_at||f.createdAt),this.clearRevealedOpeningSequenceMessageIds();var m={id:f.id,body:s,attachments:p?[p.src]:[],replied_to:i,product:o,button:a,type:"quick_reply"};ji.eventEmitter.dispatch("webchat:message:sent",m)}),function(e){return c.apply(this,arguments)})},{key:"sendTeaserQuickReply",value:(l=ss(function*(e){var t;e.preventDefault(),e.stopPropagation();var n=e.currentTarget,r=(n.dataset.value||"").trim(),i=[n.dataset.text,n.textContent].map(e=>(e||"").trim()).find(e=>e.length>0),o=r||i;if(o){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this),this.show();var a=(n.dataset.type||"").trim()||"quick_reply",s=new FormData;s.append("message[body]",o),s.append("session",ji.session),s.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(s);var l=this.buildMessageElement();l.querySelector("[data-body]").innerText=o,this.typingIndicatorVisible&&this.hasTypingIndicatorTarget?this.messagesContainerTarget.insertBefore(l,this.typingIndicatorTarget):this.messagesContainerTarget.appendChild(l),l.scrollIntoView({behavior:"smooth"}),this.broadcastChannel.postMessage({type:"message:sent",element:l.outerHTML}),this.typingIndicatorVisible||(clearTimeout(this.optimisticTypingTimeout),this.optimisticTypingTimeout=setTimeout(()=>{this.showOptimisticTypingIndicator()},this.optimisticTypingIndicatorWaitValue));var c=yield this.messagesAPI.create(s);if(c.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(c,l);var u=yield c.json();l.setAttribute("data-id",u.id),this.localizeMessageTimestamp(l.querySelector("[data-message-timestamp]"),u.created_at||u.createdAt),this.clearRevealedOpeningSequenceMessageIds(),ji.eventEmitter.dispatch("webchat:message:sent",{id:u.id,body:o,attachments:[],type:"quick_reply",teaser:{text:i||o,value:r||o,type:a}}),u.conversation&&u.conversation!==this.conversationIdValue&&(this.conversationIdValue=u.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer()}}),function(e){return l.apply(this,arguments)})},{key:"sendMessage",value:(s=ss(function*(e){var t,n={body:this.inputTarget.value,attachments:this.files};if(0!==this.inputTarget.value.trim().length||0!==this.files.length){null===(t=this.dismissTeaserForSession)||void 0===t||t.call(this);var r=new FormData;this.inputTarget.value.trim().length>0?r.append("message[body]",this.inputTarget.value):delete n.body,this.files.forEach(e=>{r.append("message[attachments][]",e)}),r.append("session",ji.session),r.append("locale",j.toString()),this.appendOpeningSequenceMessageIds(r);var i=this.buildMessageElement();this.inputTarget.value.trim().length>0?i.querySelector("[data-body]").innerText=this.inputTarget.value:i.querySelector("[data-message-bubble]").remove();var o=this.attachmentContainerTarget.querySelectorAll("img");o.length>0&&o.forEach(e=>{var t;null===(t=this.messageAttachmentsContainer(i))||void 0===t||t.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));var a=yield this.messagesAPI.create(r);if(a.failed)return clearTimeout(this.optimisticTypingTimeout),this.markMessageFailedFromResponse(a,i);var s=yield a.json();i.setAttribute("data-id",s.id),n.id=s.id,this.localizeMessageTimestamp(i.querySelector("[data-message-timestamp]"),s.created_at||s.createdAt),this.clearRevealedOpeningSequenceMessageIds(),ji.eventEmitter.dispatch("webchat:message:sent",n),s.conversation!==this.conversationIdValue&&(this.conversationIdValue=s.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue)),this.typingIndicatorVisible&&this.resetTypingIndicatorTimer(),this.attachmentContainerTarget.style.display=""}else e&&e.target&&e.preventDefault()}),function(e){return s.apply(this,arguments)})},{key:"buildMessageElement",value:function(){var e=this.messageTemplateTarget.cloneNode(!0);return e.id="hellotext--webchat--".concat(this.idValue,"--message--").concat(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}},{key:"focusCompose",value:function(e){var t=e.target,n=["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(n)&&this.focusComposeInput({moveCursorToEnd:!0})&&e.preventDefault()}},{key:"closePopoverFromHeader",value:function(e){e.target.closest(".hellotext--webchat-header-channel-button, .hellotext--webchat-close-button")||(e.preventDefault(),this.closePopover())}},{key:"closePopoverOnEscape",value:function(e){var t,n;"Escape"===e.key&&this.openValue&&(e.preventDefault(),e.stopPropagation(),this.closePopover(),null===(t=this.triggerTarget)||void 0===t||null===(n=t.focus)||void 0===n||n.call(t))}},{key:"markMessageFailedFromResponse",value:(a=ss(function*(e,t){var n=yield this.messageFailureReason(e);this.markMessageFailed(t,n),this.broadcastChannel.postMessage({type:"message:failed",id:t.id,reason:n})}),function(e,t){return a.apply(this,arguments)})},{key:"markMessageFailed",value:function(e,t){if(e&&(e.classList.add("failed"),t)){var n=e.querySelector("[data-message-timestamp]");n&&(n.textContent=t)}}},{key:"localizeMessageTimestamps",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.element;n&&(null!==(e=n.matches)&&void 0!==e&&e.call(n,"time[datetime][data-message-timestamp]")?[n]:Array.from((null===(t=n.querySelectorAll)||void 0===t?void 0:t.call(n,"time[datetime][data-message-timestamp]"))||[])).forEach(e=>this.localizeMessageTimestamp(e))}},{key:"localizeMessageTimestamp",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null==e?void 0:e.getAttribute("datetime");if(e&&t){var n=t instanceof Date?t:new Date(t);Number.isNaN(n.getTime())||(e.setAttribute("datetime",n.toISOString()),e.textContent=this.formatMessageTimestamp(n))}}},{key:"formatMessageTimestamp",value:function(e){return this.constructor.messageTimestampFormatterFor(j.toString()).format(e)}},{key:"messageFailureReason",value:(o=ss(function*(e){var t=(null==e?void 0:e.data)||(null==e?void 0:e.response),n=(null==t?void 0:t.statusText)||"Message failed";try{var r,i=null!=t&&t.clone?t.clone():t,o=yield null==i||null===(r=i.json)||void 0===r?void 0:r.call(i),a=this.messageFailureReasonFromPayload(o);if(a)return a}catch(e){}try{var s,l=null!=t&&t.clone?t.clone():t,c=yield null==l||null===(s=l.text)||void 0===s?void 0:s.call(l);return this.messageFailureReasonFromText(c)||n}catch(e){return n}}),function(e){return o.apply(this,arguments)})},{key:"messageFailureReasonFromText",value:function(e){if("string"!=typeof e)return null;var t=e.trim();if(!t||t.startsWith("<"))return null;try{return this.messageFailureReasonFromPayload(JSON.parse(t))||t}catch(e){return t}}},{key:"messageFailureReasonFromPayload",value:function(e){var t,n,r,i;return e?[null===(t=e.error)||void 0===t?void 0:t.message,e.message,null===(n=e.errors)||void 0===n?void 0:n.message,null===(r=e.errors)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.message,null===(i=e.errors)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.description].find(e=>"string"==typeof e&&e.trim().length>0):null}},{key:"messageAttachmentsContainer",value:function(e){return e.querySelector("[data-attachments-container], [data-attachment-container]")}},{key:"incrementUnreadCounter",value:function(){this.unreadCounterTarget.style.display="flex";var e=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=Math.min(e,9)}},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.style.display="none";var e=Array.from(this.attachmentInputTarget.files);this.attachmentInputTarget.value="";var t=e.find(e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e)),this.focusComposeInput()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.style.display="",t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else{var r=t.querySelector("main");r.style.height="5rem",r.style.borderRadius="0.375rem",r.style.backgroundColor="#e5e7eb",r.style.padding="0.25rem",t.querySelector("p[data-attachment-name]").innerText=e.name,this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}}},{key:"removeAttachment",value:function(e){var t=e.currentTarget.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter(e=>e.name!==t.dataset.name),this.attachmentInputTarget.value="",t.remove(),this.focusComposeInput()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var t=e.detail,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.focusComposeInput()}},{key:"focusComposeInput",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).moveCursorToEnd,t=void 0!==e&&e;if(!this.shouldAutofocusCompose)return!1;if(!1===this.hasInputTarget)return!1;if(void 0===this.hasInputTarget&&!this.inputTarget)return!1;if(this.inputTarget.focus(),t&&"number"==typeof this.inputTarget.selectionStart){var n=this.inputTarget.value.length;this.inputTarget.setSelectionRange(n,n)}return!0}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"middlewares",get:function(){return[ga(this.offsetValue),ba({padding:this.paddingValue}),wa()]}},{key:"shouldOpenOnMount",get:function(){return"opened"===localStorage.getItem("hellotext--webchat--".concat(this.idValue))&&!this.onMobile}},{key:"shouldAutofocusCompose",get:function(){return!this.usesVirtualKeyboard}},{key:"usesVirtualKeyboard",get:function(){var e;if("undefined"==typeof navigator)return!1;var t=navigator.userAgent||"",n="MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,r=gs.test(t),i=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile);return r||n||i||this.hasTouchOnlyPointer}},{key:"hasTouchOnlyPointer",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches}},{key:"onMobile",get:function(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(max-width: ".concat(this.fullScreenThresholdValue,"px)")).matches}}],i=[{key:"messageTimestampFormatterFor",value:function(e){var t=e||"default";return this.messageTimestampFormatters[t]||(this.messageTimestampFormatters[t]=this.buildMessageTimestampFormatter(e)),this.messageTimestampFormatters[t]}},{key:"buildMessageTimestampFormatter",value:function(e){try{return new Intl.DateTimeFormat(e||void 0,ys)}catch(e){return new Intl.DateTimeFormat(void 0,ys)}}}],r&&ls(n.prototype,r),i&&ls(n,i),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,r,i,o,a,s,l,c,u,h}(g.xI);bs.messageTimestampFormatters={},bs.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},bs.classes=["fadeOut"],bs.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"];var ws=g.lg.start();ws.register("hellotext--form",Bi),ws.register("hellotext--popup",io),ws.register("hellotext--webchat",bs),ws.register("hellotext--webchat--emoji",Ia),ws.register("hellotext--message",Ji),window.Hellotext=ji;const Os=ji},109(e,t,n){var r=n(601),i=n.n(r),o=n(314),a=n.n(o)()(i());a.push([e.id,"form[data-hello-form] {\n position: relative;\n}\n\nform[data-hello-form] article [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n}\n\nform[data-hello-form] article:has(input:invalid) [data-error-container] {\n display: block;\n}\n\nform[data-hello-form] [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n}\n\nform[data-hello-form] [data-logo-container] small {\n margin: 0 0.3rem;\n}\n\nform[data-hello-form] [data-logo-container] [data-hello-brand] {\n width: 4rem;\n}\n\n.hellotext--popup,\n.hellotext--popup * {\n box-sizing: border-box;\n}\n\n.hellotext--popup[hidden],\n.hellotext--popup [hidden] {\n display: none !important;\n}\n\n.hellotext--popup {\n --hellotext-popup-background-color: #ffffff;\n --hellotext-popup-color: #140434;\n --hellotext-popup-font-family: 'PP Object Sans', 'Object Sans', system-ui, -apple-system, Helvetica, Arial, sans-serif;\n --hellotext-popup-font-size: 16px;\n --hellotext-popup-button-background-color: #ff4c00;\n --hellotext-popup-button-color: #ffffff;\n --hellotext-popup-bubble-background-color: #ff4c00;\n --hellotext-popup-bubble-color: #ffffff;\n --hellotext-popup-header-background-color: #ffddf4;\n --hellotext-popup-header-background-size: cover;\n --hellotext-popup-header-background-image: none;\n\n color: var(--hellotext-popup-color);\n font-family: var(--hellotext-popup-font-family);\n font-size: var(--hellotext-popup-font-size);\n line-height: 1.4;\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n pointer-events: none;\n}\n\n.hellotext--popup-bubble {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-bubble-background-color);\n color: var(--hellotext-popup-bubble-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 18px;\n position: fixed;\n bottom: 24px;\n min-height: 44px;\n max-width: min(320px, calc(100vw - 32px));\n pointer-events: auto;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup--bubble-left .hellotext--popup-bubble {\n left: 24px;\n}\n\n.hellotext--popup--bubble-center .hellotext--popup-bubble {\n left: 50%;\n transform: translateX(-50%);\n}\n\n.hellotext--popup--bubble-right .hellotext--popup-bubble {\n right: 24px;\n}\n\n.hellotext--popup-dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n pointer-events: none;\n}\n\n.hellotext--popup-dialog--footer {\n align-items: flex-end;\n padding: 0;\n}\n\n.hellotext--popup-surface {\n position: relative;\n display: flex;\n overflow: visible;\n max-width: calc(100vw - 32px);\n max-height: calc(100vh - 32px);\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n background: var(--hellotext-popup-background-color);\n color: var(--hellotext-popup-color);\n pointer-events: auto;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup-surface--desktop-default,\n.hellotext--popup-surface--desktop-image_to_right {\n width: min(768px, calc(100vw - 32px));\n min-height: 420px;\n align-items: stretch;\n}\n\n.hellotext--popup-surface--image-to-right {\n flex-direction: row-reverse;\n}\n\n.hellotext--popup-surface--desktop-column {\n width: min(448px, calc(100vw - 32px));\n flex-direction: column;\n}\n\n.hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n max-height: none;\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup-header {\n min-height: 320px;\n width: 40%;\n flex: 0 0 40%;\n border-radius: 28px 0 0 28px;\n background-color: var(--hellotext-popup-header-background-color);\n background-image: var(--hellotext-popup-header-background-image);\n background-position: center;\n background-repeat: no-repeat;\n background-size: var(--hellotext-popup-header-background-size);\n}\n\n.hellotext--popup-header--image-right {\n border-radius: 0 28px 28px 0;\n}\n\n.hellotext--popup-surface--desktop-column .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup-content {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 0;\n margin: 0;\n padding: 28px;\n background: transparent;\n color: inherit;\n}\n\n.hellotext--popup-surface--desktop-default .hellotext--popup-content,\n.hellotext--popup-surface--desktop-image_to_right .hellotext--popup-content {\n width: 60%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n flex-direction: row;\n flex-wrap: wrap;\n gap: 16px 28px;\n align-items: center;\n justify-content: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n\n.hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup-copy {\n width: 100%;\n margin: 0;\n}\n\n.hellotext--popup-copy * {\n color: inherit;\n margin-top: 0;\n}\n\n.hellotext--popup-copy--header {\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup-copy--header h1,\n.hellotext--popup-copy--header h2,\n.hellotext--popup-copy--header h3 {\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n margin: 0 0 8px;\n}\n\n.hellotext--popup-copy--footer {\n margin-top: 16px;\n font-size: 12px;\n opacity: 0.72;\n}\n\n.hellotext--popup-fields {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-field {\n width: 100%;\n}\n\n.hellotext--popup-label {\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 100%;\n font-size: 13px;\n font-weight: 600;\n}\n\n.hellotext--popup-label input {\n width: 100%;\n min-height: 48px;\n border: 1px solid color-mix(in srgb, var(--hellotext-popup-color) 16%, transparent);\n border-radius: 12px;\n background: #ffffff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: none;\n padding: 12px 16px;\n}\n\n.hellotext--popup-label input:focus {\n border-color: var(--hellotext-popup-button-background-color);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--hellotext-popup-button-background-color) 20%, transparent);\n}\n\n.hellotext--popup-error {\n display: block;\n min-height: 18px;\n margin-top: 4px;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup-actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup-content--button-left .hellotext--popup-actions {\n justify-content: flex-start;\n}\n\n.hellotext--popup-content--button-center .hellotext--popup-actions {\n justify-content: center;\n}\n\n.hellotext--popup-content--button-right .hellotext--popup-actions {\n justify-content: flex-end;\n}\n\n.hellotext--popup-content--button-full_width .hellotext--popup-actions {\n justify-content: stretch;\n}\n\n.hellotext--popup-button {\n appearance: none;\n border: 0;\n border-radius: 999px;\n background: var(--hellotext-popup-button-background-color);\n color: var(--hellotext-popup-button-color);\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n min-height: 48px;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup-button--full-width {\n width: 100%;\n}\n\n.hellotext--popup-button:disabled {\n cursor: progress;\n opacity: 0.65;\n}\n\n.hellotext--popup-close {\n appearance: none;\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 999px;\n background: #f0eef4;\n color: #81778f;\n cursor: pointer;\n padding: 0;\n}\n\n.hellotext--popup-close svg {\n width: 14px;\n height: 14px;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup-surface {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n flex-direction: column;\n overflow-y: auto;\n }\n\n .hellotext--popup-surface--mobile-center .hellotext--popup-header,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-header {\n display: none;\n }\n\n .hellotext--popup-header {\n width: 100%;\n min-height: 200px;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n }\n\n .hellotext--popup-content,\n .hellotext--popup-surface--desktop-footer .hellotext--popup-content {\n width: 100%;\n padding: 24px;\n }\n\n .hellotext--popup-surface--desktop-footer .hellotext--popup-step {\n display: flex;\n }\n\n .hellotext--popup-surface--desktop-footer {\n width: 100vw;\n max-width: none;\n border-radius: 24px 24px 0 0;\n }\n}\n\n/* Popup runtime markup. Keep these selectors in sync with\n * Popup::RuntimeComponent; the dashboard preview uses the same layout rules. */\n.hellotext--popup__bubble {\n position: fixed;\n bottom: 24px;\n z-index: 1;\n appearance: none;\n border: 0;\n background: transparent;\n cursor: pointer;\n font: inherit;\n max-width: min(320px, calc(100vw - 32px));\n padding: 0;\n pointer-events: auto;\n}\n\n.hellotext--popup__bubble--left { left: 24px; }\n.hellotext--popup__bubble--center { left: 50%; transform: translateX(-50%); }\n.hellotext--popup__bubble--right { right: 24px; }\n\n.hellotext--popup__bubble-content {\n display: block;\n border-radius: 999px;\n box-shadow: 0 16px 38px rgba(20, 4, 52, 0.18);\n font-weight: 700;\n min-height: 44px;\n padding: 12px 18px;\n}\n\n.hellotext--popup__dialog {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(20, 4, 52, 0.35);\n pointer-events: auto;\n}\n\n.hellotext--popup__frame {\n display: flex;\n width: min(768px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n}\n\n.hellotext--popup__frame--desktop-column { width: min(448px, calc(100vw - 32px)); }\n\n.hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n}\n\n.hellotext--popup__panel {\n position: relative;\n display: flex;\n width: 100%;\n min-height: 420px;\n overflow: hidden;\n border: 1px solid rgba(20, 4, 52, 0.1);\n border-radius: 28px;\n box-shadow: 0 22px 60px rgba(20, 4, 52, 0.18);\n}\n\n.hellotext--popup__panel--desktop-image_to_right { flex-direction: row-reverse; }\n\n.hellotext--popup__panel--desktop-column {\n flex-direction: column;\n min-height: 0;\n}\n\n.hellotext--popup__panel--desktop-footer {\n min-height: 132px;\n border-right: 0;\n border-bottom: 0;\n border-left: 0;\n border-radius: 24px 24px 0 0;\n}\n\n.hellotext--popup__media {\n width: 40%;\n min-height: 420px;\n flex: 0 0 40%;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.hellotext--popup__media--desktop-default { border-radius: 28px 0 0 28px; }\n.hellotext--popup__media--desktop-image_to_right { border-radius: 0 28px 28px 0; }\n\n.hellotext--popup__panel--desktop-column .hellotext--popup__media {\n width: 100%;\n min-height: 0;\n flex-basis: auto;\n border-radius: 28px 28px 0 0;\n}\n\n.hellotext--popup__content {\n display: flex;\n width: 60%;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n justify-content: center;\n margin: 0;\n padding: 28px;\n}\n\n.hellotext--popup__content--desktop-column { width: 100%; }\n\n.hellotext--popup__content--desktop-footer {\n width: 100%;\n align-items: center;\n padding: 24px 56px;\n}\n\n.hellotext--popup__step {\n display: flex;\n width: 100%;\n flex-direction: column;\n}\n\n.hellotext--popup__step--desktop-footer {\n display: grid;\n grid-template-columns: minmax(180px, auto) minmax(220px, 320px) auto;\n align-items: center;\n justify-content: center;\n gap: 12px 28px;\n}\n\n.hellotext--popup__step-header {\n width: 100%;\n margin: 0;\n font-size: 18px;\n line-height: 1.25;\n}\n\n.hellotext--popup__completion-headline {\n width: 100%;\n margin: 0;\n font-size: 1.125em;\n line-height: 1.25;\n}\n\n.hellotext--popup__rich-text * { color: inherit; }\n\n.hellotext--popup__step-header h1,\n.hellotext--popup__step-header h2,\n.hellotext--popup__step-header h3 {\n margin: 0 0 8px;\n font-size: clamp(32px, 7vw, 48px);\n line-height: 0.95;\n}\n\n.hellotext--popup__completion-headline h4 {\n margin: 0 0 8px;\n font-size: 1.44444444em;\n line-height: 1.25;\n}\n\n.hellotext--popup__fields-region { width: 100%; }\n\n.hellotext--popup__fields {\n display: flex;\n width: 100%;\n flex-direction: column;\n gap: 10px;\n margin-top: 20px;\n}\n\n.hellotext--popup__field { width: 100%; }\n\n.hellotext--popup__input {\n width: 100%;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n font: inherit;\n font-size: 16px;\n outline: 0;\n padding: 12px 16px;\n}\n\n.hellotext--popup__input:focus {\n border-color: currentColor;\n box-shadow: 0 0 0 3px rgba(20, 4, 52, 0.12);\n}\n\n.hellotext--popup__checkbox-label {\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 48px;\n border: 1px solid rgba(20, 4, 52, 0.16);\n border-radius: 12px;\n background: #fff;\n color: #140434;\n padding: 12px 16px;\n}\n\n.hellotext--popup__checkbox { width: 16px; height: 16px; }\n\n.hellotext--popup__error,\n.hellotext--popup__global-error {\n display: block;\n min-height: 18px;\n margin: 4px 0 0;\n color: #d92d20;\n font-size: 12px;\n}\n\n.hellotext--popup__actions {\n display: flex;\n width: 100%;\n margin-top: 20px;\n}\n\n.hellotext--popup__actions--left { justify-content: flex-start; }\n.hellotext--popup__actions--center { justify-content: center; }\n.hellotext--popup__actions--right { justify-content: flex-end; }\n.hellotext--popup__actions--full_width { justify-content: stretch; }\n\n.hellotext--popup__button,\n.hellotext--popup__completion-button {\n appearance: none;\n min-height: 48px;\n border: 0;\n border-radius: 999px;\n cursor: pointer;\n font: inherit;\n font-weight: 700;\n padding: 12px 24px;\n text-align: center;\n}\n\n.hellotext--popup__button--full_width { width: 100%; }\n.hellotext--popup__button:disabled { cursor: progress; opacity: 0.65; }\n\n.hellotext--popup__step-footer,\n.hellotext--popup__completion-footer {\n width: 100%;\n margin-top: 16px;\n font-size: 12px;\n}\n\n.hellotext--popup__completion-footer {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n justify-content: center;\n gap: 0 4px;\n text-align: center;\n}\n\n.hellotext--popup__completion-footer > span,\n.hellotext--popup__completion-action:disabled {\n opacity: 0.5;\n}\n\n.hellotext--popup__completion-action {\n appearance: none;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent;\n color: inherit;\n cursor: pointer;\n font: inherit;\n font-weight: 500;\n line-height: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n\n.hellotext--popup__completion-action:disabled {\n cursor: default;\n text-decoration: none;\n}\n\n.hellotext--popup__completed { width: 100%; text-align: center; }\n.hellotext--popup__completion-description { margin-top: 12px; }\n.hellotext--popup__completion-button { margin-top: 20px; }\n\n.hellotext--popup__close {\n top: 12px;\n right: 12px;\n z-index: 2;\n cursor: pointer;\n}\n\n.hellotext--popup__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n@media (max-width: 767px) {\n .hellotext--popup__dialog { padding: 16px; }\n .hellotext--popup__frame,\n .hellotext--popup__frame--desktop-column {\n width: min(350px, calc(100vw - 32px));\n max-height: calc(100vh - 32px);\n }\n .hellotext--popup__frame--desktop-footer {\n align-self: flex-end;\n width: 100vw;\n max-height: none;\n }\n .hellotext--popup__panel,\n .hellotext--popup__panel--desktop-image_to_right,\n .hellotext--popup__panel--desktop-column {\n min-height: 0;\n flex-direction: column;\n overflow-y: auto;\n }\n .hellotext--popup__panel--desktop-footer {\n width: 100vw;\n border-radius: 24px 24px 0 0;\n }\n .hellotext--popup__media {\n display: block;\n width: 100%;\n min-height: 0;\n flex: 0 0 auto;\n border-radius: 28px 28px 0 0;\n }\n .hellotext--popup__content,\n .hellotext--popup__content--desktop-footer {\n width: 100%;\n padding: 24px;\n }\n .hellotext--popup__step--desktop-footer { display: flex; }\n}\n",""]);const s=a;n.d(t,["A",0,s])},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(r)for(var s=0;s0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},601(e){e.exports=function(e){return e[1]}}};const t={};function n(r){const i=t[r];if(void 0!==i)return i.exports;const o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.m=e,n.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},(()=>{const e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;let t;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"==typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"==typeof r.then)return r}const o=Object.create(null);n.r(o);const a={};t=t||[null,e({}),e([]),e(e)];for(var s=2&i&&r;("object"==typeof s||"function"==typeof s)&&!~t.indexOf(s);s=e(s))Object.getOwnPropertyNames(s).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,n.d(o,a),o}})(),n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;rPromise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({160:"webchat-emoji",200:"webchat-emoji-en",437:"webchat-emoji-es"}[e]+".js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Hellotext:";n.l=(r,i,o,a)=>{if(e[r])return void e[r].push(i);let s,l;if(void 0!==o){const e=document.getElementsByTagName("script");for(var c=0;c{s.onerror=s.onload=null,clearTimeout(h);const i=e[r];if(delete e[r],s.parentNode?.removeChild(s),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(u.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=u.bind(null,s.onerror),s.onload=u.bind(null,s.onload),l&&document.head.appendChild(s)}})(),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.cjs=e=>{const t={exports:{}};return e.call(t.exports,t,t.exports),t.exports},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^http(s?):/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,r)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{const o=new Promise((n,r)=>i=e[t]=[n,r]);r.push(i[2]=o);const a=n.p+n.u(t),s=new Error,l=r=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;s.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",s.name="ChunkLoadError",s.type=e,s.request=n,s.event=r,i[1](s)}};n.l(a,l,"chunk-"+t,t)}};const t=(t,r)=>{let[i,o,a]=r;var s,l,c=0;if(i.some(t=>0!==e[t])){for(s in o)n.o(o,s)&&(n.m[s]=o[s]);a&&a(n)}for(t&&t(r);c 0 && arguments[0] !== undefined ? arguments[0] : Configuration.apiRoot; + return "".concat(apiRoot, "/public/businesses"); } }, { key: "get", value: function () { - var _get = _asyncToGenerator(function* (id) { - return fetch("".concat(this.endpoint, "/").concat(id), { + var _get = _asyncToGenerator(function* (id, apiRoot) { + return fetch("".concat(this.endpoint(apiRoot), "/").concat(id), { method: 'GET', headers: { Authorization: "Bearer ".concat(id), @@ -28,7 +29,7 @@ var _default = /*#__PURE__*/function () { } }); }); - function get(_x) { + function get(_x, _x2) { return _get.apply(this, arguments); } return get; diff --git a/lib/controllers/popup_controller.cjs b/lib/controllers/popup_controller.cjs index 24d9e185..af93d9c1 100644 --- a/lib/controllers/popup_controller.cjs +++ b/lib/controllers/popup_controller.cjs @@ -50,6 +50,7 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { return _createClass(_default, [{ key: "connect", value: function connect() { + this.constructor.controllers.add(this); this.stepIndex = 0; this.onScroll = this.evaluateDisplay.bind(this); this.resendLabel = this.hasResendButtonTarget ? this.resendButtonTarget.textContent.trim() : ''; @@ -61,6 +62,8 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { }, { key: "disconnect", value: function disconnect() { + this.releaseDisplay(); + this.constructor.controllers.delete(this); window.removeEventListener('scroll', this.onScroll); this.stopResendCooldown(); } @@ -76,13 +79,11 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { key: "close", value: function close(event) { if (event) event.preventDefault(); + this.dismissed = true; this.hideElement(this.dialogTarget); - if (this.hasBubbleValue && this.hasBubbleTarget) { - this.showElement(this.element); - this.showElement(this.bubbleTarget); - } else { - this.hideElement(this.element); - } + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget); + this.hideElement(this.element); + this.releaseDisplay(); } }, { key: "next", @@ -141,7 +142,10 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { }, { key: "evaluateDisplay", value: function evaluateDisplay() { - if (!this.matchesDevice() || !this.rulesWithoutScrollPass()) return; + if (this.dismissed || !this.matchesDevice() || !this.rulesWithoutScrollPass()) { + this.releaseDisplay(); + return; + } if (this.scrollRule && !this.scrollRulePasses()) { window.addEventListener('scroll', this.onScroll, { passive: true @@ -149,8 +153,27 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { return; } window.removeEventListener('scroll', this.onScroll); + if (!this.claimDisplay()) return; this.showInitialState(); } + }, { + key: "claimDisplay", + value: function claimDisplay() { + const Controller = this.constructor; + if (Controller.displayOwner && Controller.displayOwner !== this) return false; + Controller.displayOwner = this; + return true; + } + }, { + key: "releaseDisplay", + value: function releaseDisplay() { + const Controller = this.constructor; + if (Controller.displayOwner !== this) return; + Controller.displayOwner = undefined; + Controller.controllers.forEach(controller => { + if (controller !== this) controller.evaluateDisplay(); + }); + } }, { key: "showInitialState", value: function showInitialState() { @@ -580,6 +603,8 @@ let _default = exports.default = /*#__PURE__*/function (_Controller) { } }]); }(_stimulus.Controller); +_default.controllers = new Set(); +_default.displayOwner = void 0; _default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton', 'resendButton', 'changeDestinationButton']; _default.values = { capture: Object, diff --git a/lib/controllers/popup_controller.js b/lib/controllers/popup_controller.js index 5293752a..a1082de3 100644 --- a/lib/controllers/popup_controller.js +++ b/lib/controllers/popup_controller.js @@ -46,6 +46,7 @@ var _default = /*#__PURE__*/function (_Controller) { return _createClass(_default, [{ key: "connect", value: function connect() { + this.constructor.controllers.add(this); this.stepIndex = 0; this.onScroll = this.evaluateDisplay.bind(this); this.resendLabel = this.hasResendButtonTarget ? this.resendButtonTarget.textContent.trim() : ''; @@ -57,6 +58,8 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "disconnect", value: function disconnect() { + this.releaseDisplay(); + this.constructor.controllers.delete(this); window.removeEventListener('scroll', this.onScroll); this.stopResendCooldown(); } @@ -72,13 +75,11 @@ var _default = /*#__PURE__*/function (_Controller) { key: "close", value: function close(event) { if (event) event.preventDefault(); + this.dismissed = true; this.hideElement(this.dialogTarget); - if (this.hasBubbleValue && this.hasBubbleTarget) { - this.showElement(this.element); - this.showElement(this.bubbleTarget); - } else { - this.hideElement(this.element); - } + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget); + this.hideElement(this.element); + this.releaseDisplay(); } }, { key: "next", @@ -149,7 +150,10 @@ var _default = /*#__PURE__*/function (_Controller) { }, { key: "evaluateDisplay", value: function evaluateDisplay() { - if (!this.matchesDevice() || !this.rulesWithoutScrollPass()) return; + if (this.dismissed || !this.matchesDevice() || !this.rulesWithoutScrollPass()) { + this.releaseDisplay(); + return; + } if (this.scrollRule && !this.scrollRulePasses()) { window.addEventListener('scroll', this.onScroll, { passive: true @@ -157,8 +161,27 @@ var _default = /*#__PURE__*/function (_Controller) { return; } window.removeEventListener('scroll', this.onScroll); + if (!this.claimDisplay()) return; this.showInitialState(); } + }, { + key: "claimDisplay", + value: function claimDisplay() { + var Controller = this.constructor; + if (Controller.displayOwner && Controller.displayOwner !== this) return false; + Controller.displayOwner = this; + return true; + } + }, { + key: "releaseDisplay", + value: function releaseDisplay() { + var Controller = this.constructor; + if (Controller.displayOwner !== this) return; + Controller.displayOwner = undefined; + Controller.controllers.forEach(controller => { + if (controller !== this) controller.evaluateDisplay(); + }); + } }, { key: "showInitialState", value: function showInitialState() { @@ -607,6 +630,8 @@ var _default = /*#__PURE__*/function (_Controller) { } }]); }(Controller); +_default.controllers = new Set(); +_default.displayOwner = void 0; _default.targets = ['bubble', 'dialog', 'step', 'completed', 'input', 'submitButton', 'resendButton', 'changeDestinationButton']; _default.values = { capture: Object, diff --git a/lib/hellotext.cjs b/lib/hellotext.cjs index 8cc3d708..93c8e451 100644 --- a/lib/hellotext.cjs +++ b/lib/hellotext.cjs @@ -27,34 +27,239 @@ let Hellotext = /*#__PURE__*/function () { * @param { Configuration } config */ async function initialize(business, config = {}) { - this.business = new _models.Business(business); - this.page = new _models.Page(); - _core.Configuration.assign(config); - _models.Session.initialize(this.page); - this.forms = new _models.FormCollection(); - this.query = new _models.Query(); - const businessData = await this.business.hydrate(); - const popupConfig = config.popup === false ? false : this.mergePopupConfig(businessData && businessData.popup || {}, config.popup || {}); - const webchatConfig = config.webchat === false ? false : this.mergeWebchatConfig(businessData && businessData.webchat || {}, config.webchat || {}); - const whatsappConfig = config.whatsappWidget === false ? false : this.mergeWhatsAppConfig(businessData && businessData.whatsapp || {}, config.whatsappWidget || {}); - const hasExplicitBehaviourOverride = config.webchat && config.webchat !== false && Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour'); - _core.Configuration.webchat.behaviourOverride = hasExplicitBehaviourOverride; - if (webchatConfig && webchatConfig.id) { - _core.Configuration.webchat.assign(webchatConfig); - this.webchat = await _models.Webchat.load(webchatConfig.id); - } - if (whatsappConfig && whatsappConfig.id) { - _core.Configuration.whatsapp.assign(whatsappConfig); - this.whatsapp = await _models.WhatsAppWidget.load(whatsappConfig.id); - } - if (popupConfig && popupConfig.id) { - _core.Configuration.popup.assign(popupConfig); - this.popup = await _models.Popup.load(popupConfig.id); - } - if (typeof MutationObserver !== 'undefined') { - this.forms.collectExistingFormsOnPage(); + const generation = ++this.initializationGeneration; + this.initializationBaseline || (this.initializationBaseline = { + configuration: this.configurationSnapshot(), + runtime: this.runtimeSnapshot() + }); + const { + configuration, + runtime: previous + } = this.initializationBaseline; + const staged = { + popups: [] + }; + const nextBusiness = new _models.Business(business); + try { + var _previous$business, _previous$business$re, _staged$webchat, _staged$webchat$markC, _staged$whatsapp, _staged$whatsapp$mark; + const businessData = await nextBusiness.hydrate({ + apiRoot: config.apiRoot, + stylesheet: false + }); + if (!this.initializationIsCurrent(generation)) return; + if (!businessData && this.hasMountedSurfaces(previous)) { + if (!this.hasExplicitSurface(config) && this.hasDisabledSurface(config)) { + this.restoreRuntime(this.runtimeWithoutDisabledSurfaces(previous, config)); + } else if (!this.hasExplicitSurface(config)) { + this.restoreRuntime(previous); + } + if (!this.hasExplicitSurface(config)) { + this.restoreConfiguration(configuration); + return; + } + } + _core.Configuration.assign(config); + this.business = nextBusiness; + nextBusiness.loadStylesheet(); + this.page = new _models.Page(); + _models.Session.initialize(this.page); + this.forms = new _models.FormCollection(); + this.query = new _models.Query(); + this.popup = undefined; + this.popups = []; + this.webchat = undefined; + this.whatsapp = undefined; + const popupConfigs = config.popup === false ? [] : this.popupConfigs(businessData, config.popup || {}); + const webchatConfig = config.webchat === false ? false : this.mergeWebchatConfig(businessData && businessData.webchat || {}, config.webchat || {}); + const whatsappConfig = config.whatsappWidget === false ? false : this.mergeWhatsAppConfig(businessData && businessData.whatsapp || {}, config.whatsappWidget || {}); + const hasExplicitBehaviourOverride = config.webchat && config.webchat !== false && Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour'); + _core.Configuration.webchat.behaviourOverride = hasExplicitBehaviourOverride; + if (webchatConfig && webchatConfig.id) { + _core.Configuration.webchat.assign(webchatConfig); + staged.webchat = await _models.Webchat.load(webchatConfig.id); + if (!this.initializationIsCurrent(generation)) return; + } + if (whatsappConfig && whatsappConfig.id) { + _core.Configuration.whatsapp.assign(whatsappConfig); + staged.whatsapp = await _models.WhatsAppWidget.load(whatsappConfig.id); + if (!this.initializationIsCurrent(generation)) return; + } + if (popupConfigs.length > 0) { + _core.Configuration.popup.assign(popupConfigs[0]); + for (const popupConfig of popupConfigs) { + const popup = await _models.Popup.load(popupConfig.id); + staged.popups.push(popup); + if (!this.initializationIsCurrent(generation)) return; + } + } + this.unmountSurfaces(previous); + (_previous$business = previous.business) === null || _previous$business === void 0 || (_previous$business$re = _previous$business.releaseStylesheet) === null || _previous$business$re === void 0 || _previous$business$re.call(_previous$business); + (_staged$webchat = staged.webchat) === null || _staged$webchat === void 0 || (_staged$webchat$markC = _staged$webchat.markCoexistingWidgets) === null || _staged$webchat$markC === void 0 || _staged$webchat$markC.call(_staged$webchat); + (_staged$whatsapp = staged.whatsapp) === null || _staged$whatsapp === void 0 || (_staged$whatsapp$mark = _staged$whatsapp.markCoexistingWidgets) === null || _staged$whatsapp$mark === void 0 || _staged$whatsapp$mark.call(_staged$whatsapp); + this.webchat = staged.webchat; + this.whatsapp = staged.whatsapp; + this.popups = staged.popups; + this.popup = staged.popups[0]; + if (typeof MutationObserver !== 'undefined') { + this.forms.collectExistingFormsOnPage(); + } + } catch (error) { + this.unmountSurfaces(staged); + nextBusiness.releaseStylesheet(); + if (this.initializationIsCurrent(generation)) { + this.restoreRuntime(previous); + this.restoreConfiguration(configuration); + } + throw error; + } finally { + if (!this.initializationIsCurrent(generation)) { + this.unmountSurfaces(staged); + nextBusiness.releaseStylesheet(); + } else { + this.initializationBaseline = undefined; + } } } + }, { + key: "initializationIsCurrent", + value: function initializationIsCurrent(generation) { + return this.initializationGeneration === generation; + } + }, { + key: "unmountPopups", + value: function unmountPopups() { + this.unmountSurfaces({ + popups: this.popups + }); + } + }, { + key: "unmountSurfaces", + value: function unmountSurfaces({ + popups = [], + webchat, + whatsapp + }) { + new Set([...popups, webchat, whatsapp]).forEach(surface => { + var _surface$unmount; + return surface === null || surface === void 0 || (_surface$unmount = surface.unmount) === null || _surface$unmount === void 0 ? void 0 : _surface$unmount.call(surface); + }); + } + }, { + key: "runtimeSnapshot", + value: function runtimeSnapshot() { + return { + business: this.business, + page: this.page, + forms: this.forms, + query: this.query, + popup: this.popup, + popups: this.popups, + webchat: this.webchat, + whatsapp: this.whatsapp + }; + } + }, { + key: "hasExplicitSurface", + value: function hasExplicitSurface(config) { + return [config.popup, config.webchat, config.whatsappWidget].some(surface => surface && surface !== false && surface.id); + } + }, { + key: "hasDisabledSurface", + value: function hasDisabledSurface(config) { + return config.popup === false || config.webchat === false || config.whatsappWidget === false; + } + }, { + key: "runtimeWithoutDisabledSurfaces", + value: function runtimeWithoutDisabledSurfaces(previous, config) { + const disabled = { + popups: config.popup === false ? previous.popups : [], + webchat: config.webchat === false ? previous.webchat : undefined, + whatsapp: config.whatsappWidget === false ? previous.whatsapp : undefined + }; + this.unmountSurfaces(disabled); + return { + ...previous, + popup: config.popup === false ? undefined : previous.popup, + popups: config.popup === false ? [] : previous.popups, + webchat: config.webchat === false ? undefined : previous.webchat, + whatsapp: config.whatsappWidget === false ? undefined : previous.whatsapp + }; + } + }, { + key: "hasMountedSurfaces", + value: function hasMountedSurfaces({ + popups = [], + webchat, + whatsapp + }) { + return popups.length > 0 || !!webchat || !!whatsapp; + } + }, { + key: "restoreRuntime", + value: function restoreRuntime(snapshot) { + Object.assign(this, snapshot); + } + }, { + key: "configurationSnapshot", + value: function configurationSnapshot() { + return { + apiRoot: _core.Configuration.apiRoot, + actionCableUrl: _core.Configuration.actionCableUrl, + autoGenerateSession: _core.Configuration.autoGenerateSession, + session: _core.Configuration.session, + locale: _core.Configuration.locale, + forms: { + autoMount: _core.Configuration.forms.autoMount, + successMessage: _core.Configuration.forms.successMessage + }, + popup: { + id: _core.Configuration.popup.id, + container: _core.Configuration.popup.container, + device: _core.Configuration.popup.device + }, + webchat: { + id: _core.Configuration.webchat.id, + container: _core.Configuration.webchat.container, + placement: _core.Configuration.webchat.placement, + style: this.clone(_core.Configuration.webchat.style), + appearance: this.clone(_core.Configuration.webchat.appearance), + whatsapp: this.clone(_core.Configuration.webchat.whatsapp), + mode: _core.Configuration.webchat.mode, + behaviour: this.clone(_core.Configuration.webchat.behaviour), + behaviourOverride: _core.Configuration.webchat.hasBehaviourOverride, + strategy: _core.Configuration.webchat._strategy + }, + whatsapp: { + id: _core.Configuration.whatsapp.id, + container: _core.Configuration.whatsapp.container, + placement: _core.Configuration.whatsapp.placement, + appearance: this.clone(_core.Configuration.whatsapp.appearance), + number: _core.Configuration.whatsapp.number, + body: _core.Configuration.whatsapp.body + } + }; + } + }, { + key: "restoreConfiguration", + value: function restoreConfiguration(snapshot) { + _core.Configuration.apiRoot = snapshot.apiRoot; + _core.Configuration.actionCableUrl = snapshot.actionCableUrl; + _core.Configuration.autoGenerateSession = snapshot.autoGenerateSession; + _core.Configuration.session = snapshot.session; + _core.Configuration.locale = snapshot.locale; + _core.Configuration.forms.assign(snapshot.forms); + _core.Configuration.popup.assign(snapshot.popup); + _core.Configuration.webchat.assign(snapshot.webchat); + _core.Configuration.webchat.behaviourOverride = snapshot.webchat.behaviourOverride; + _core.Configuration.whatsapp.assign(snapshot.whatsapp); + } + }, { + key: "clone", + value: function clone(value) { + if (Array.isArray(value)) return value.map(item => this.clone(item)); + if (!this.isPlainObject(value)) return value; + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.clone(item)])); + } }, { key: "mergeWebchatConfig", value: function mergeWebchatConfig(dashboardConfig, localConfig) { @@ -70,6 +275,16 @@ let Hellotext = /*#__PURE__*/function () { value: function mergePopupConfig(dashboardConfig, localConfig) { return this.deepMergePlainObjects(dashboardConfig, localConfig); } + }, { + key: "popupConfigs", + value: function popupConfigs(businessData, localConfig) { + if (localConfig.id) { + return [localConfig]; + } + const configuredPopups = Array.isArray(businessData && businessData.popups) ? businessData.popups.filter(config => config && config.id) : []; + const dashboardConfigs = configuredPopups.length > 0 ? configuredPopups : [businessData && businessData.popup || {}]; + return dashboardConfigs.filter(config => config && config.id).map(config => this.mergePopupConfig(config, localConfig)).filter((config, index, configs) => configs.findIndex(candidate => candidate.id === config.id) === index); + } }, { key: "deepMergePlainObjects", value: function deepMergePlainObjects(base, override) { @@ -244,6 +459,9 @@ Hellotext.eventEmitter = new _core.Event(); Hellotext.forms = void 0; Hellotext.business = void 0; Hellotext.popup = void 0; +Hellotext.popups = []; Hellotext.webchat = void 0; Hellotext.whatsapp = void 0; +Hellotext.initializationGeneration = 0; +Hellotext.initializationBaseline = void 0; var _default = exports.default = Hellotext; \ No newline at end of file diff --git a/lib/hellotext.js b/lib/hellotext.js index d2b25126..05a28720 100644 --- a/lib/hellotext.js +++ b/lib/hellotext.js @@ -33,32 +33,96 @@ var Hellotext = /*#__PURE__*/function () { function () { var _initialize = _asyncToGenerator(function* (business) { var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.business = new Business(business); - this.page = new Page(); - Configuration.assign(config); - Session.initialize(this.page); - this.forms = new FormCollection(); - this.query = new Query(); - var businessData = yield this.business.hydrate(); - var popupConfig = config.popup === false ? false : this.mergePopupConfig(businessData && businessData.popup || {}, config.popup || {}); - var webchatConfig = config.webchat === false ? false : this.mergeWebchatConfig(businessData && businessData.webchat || {}, config.webchat || {}); - var whatsappConfig = config.whatsappWidget === false ? false : this.mergeWhatsAppConfig(businessData && businessData.whatsapp || {}, config.whatsappWidget || {}); - var hasExplicitBehaviourOverride = config.webchat && config.webchat !== false && Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour'); - Configuration.webchat.behaviourOverride = hasExplicitBehaviourOverride; - if (webchatConfig && webchatConfig.id) { - Configuration.webchat.assign(webchatConfig); - this.webchat = yield Webchat.load(webchatConfig.id); - } - if (whatsappConfig && whatsappConfig.id) { - Configuration.whatsapp.assign(whatsappConfig); - this.whatsapp = yield WhatsAppWidget.load(whatsappConfig.id); - } - if (popupConfig && popupConfig.id) { - Configuration.popup.assign(popupConfig); - this.popup = yield Popup.load(popupConfig.id); - } - if (typeof MutationObserver !== 'undefined') { - this.forms.collectExistingFormsOnPage(); + var generation = ++this.initializationGeneration; + this.initializationBaseline || (this.initializationBaseline = { + configuration: this.configurationSnapshot(), + runtime: this.runtimeSnapshot() + }); + var _this$initializationB = this.initializationBaseline, + configuration = _this$initializationB.configuration, + previous = _this$initializationB.runtime; + var staged = { + popups: [] + }; + var nextBusiness = new Business(business); + try { + var _previous$business, _previous$business$re, _staged$webchat, _staged$webchat$markC, _staged$whatsapp, _staged$whatsapp$mark; + var businessData = yield nextBusiness.hydrate({ + apiRoot: config.apiRoot, + stylesheet: false + }); + if (!this.initializationIsCurrent(generation)) return; + if (!businessData && this.hasMountedSurfaces(previous)) { + if (!this.hasExplicitSurface(config) && this.hasDisabledSurface(config)) { + this.restoreRuntime(this.runtimeWithoutDisabledSurfaces(previous, config)); + } else if (!this.hasExplicitSurface(config)) { + this.restoreRuntime(previous); + } + if (!this.hasExplicitSurface(config)) { + this.restoreConfiguration(configuration); + return; + } + } + Configuration.assign(config); + this.business = nextBusiness; + nextBusiness.loadStylesheet(); + this.page = new Page(); + Session.initialize(this.page); + this.forms = new FormCollection(); + this.query = new Query(); + this.popup = undefined; + this.popups = []; + this.webchat = undefined; + this.whatsapp = undefined; + var popupConfigs = config.popup === false ? [] : this.popupConfigs(businessData, config.popup || {}); + var webchatConfig = config.webchat === false ? false : this.mergeWebchatConfig(businessData && businessData.webchat || {}, config.webchat || {}); + var whatsappConfig = config.whatsappWidget === false ? false : this.mergeWhatsAppConfig(businessData && businessData.whatsapp || {}, config.whatsappWidget || {}); + var hasExplicitBehaviourOverride = config.webchat && config.webchat !== false && Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour'); + Configuration.webchat.behaviourOverride = hasExplicitBehaviourOverride; + if (webchatConfig && webchatConfig.id) { + Configuration.webchat.assign(webchatConfig); + staged.webchat = yield Webchat.load(webchatConfig.id); + if (!this.initializationIsCurrent(generation)) return; + } + if (whatsappConfig && whatsappConfig.id) { + Configuration.whatsapp.assign(whatsappConfig); + staged.whatsapp = yield WhatsAppWidget.load(whatsappConfig.id); + if (!this.initializationIsCurrent(generation)) return; + } + if (popupConfigs.length > 0) { + Configuration.popup.assign(popupConfigs[0]); + for (var popupConfig of popupConfigs) { + var popup = yield Popup.load(popupConfig.id); + staged.popups.push(popup); + if (!this.initializationIsCurrent(generation)) return; + } + } + this.unmountSurfaces(previous); + (_previous$business = previous.business) === null || _previous$business === void 0 || (_previous$business$re = _previous$business.releaseStylesheet) === null || _previous$business$re === void 0 || _previous$business$re.call(_previous$business); + (_staged$webchat = staged.webchat) === null || _staged$webchat === void 0 || (_staged$webchat$markC = _staged$webchat.markCoexistingWidgets) === null || _staged$webchat$markC === void 0 || _staged$webchat$markC.call(_staged$webchat); + (_staged$whatsapp = staged.whatsapp) === null || _staged$whatsapp === void 0 || (_staged$whatsapp$mark = _staged$whatsapp.markCoexistingWidgets) === null || _staged$whatsapp$mark === void 0 || _staged$whatsapp$mark.call(_staged$whatsapp); + this.webchat = staged.webchat; + this.whatsapp = staged.whatsapp; + this.popups = staged.popups; + this.popup = staged.popups[0]; + if (typeof MutationObserver !== 'undefined') { + this.forms.collectExistingFormsOnPage(); + } + } catch (error) { + this.unmountSurfaces(staged); + nextBusiness.releaseStylesheet(); + if (this.initializationIsCurrent(generation)) { + this.restoreRuntime(previous); + this.restoreConfiguration(configuration); + } + throw error; + } finally { + if (!this.initializationIsCurrent(generation)) { + this.unmountSurfaces(staged); + nextBusiness.releaseStylesheet(); + } else { + this.initializationBaseline = undefined; + } } }); function initialize(_x) { @@ -66,6 +130,150 @@ var Hellotext = /*#__PURE__*/function () { } return initialize; }()) + }, { + key: "initializationIsCurrent", + value: function initializationIsCurrent(generation) { + return this.initializationGeneration === generation; + } + }, { + key: "unmountPopups", + value: function unmountPopups() { + this.unmountSurfaces({ + popups: this.popups + }); + } + }, { + key: "unmountSurfaces", + value: function unmountSurfaces(_ref) { + var _ref$popups = _ref.popups, + popups = _ref$popups === void 0 ? [] : _ref$popups, + webchat = _ref.webchat, + whatsapp = _ref.whatsapp; + new Set([...popups, webchat, whatsapp]).forEach(surface => { + var _surface$unmount; + return surface === null || surface === void 0 || (_surface$unmount = surface.unmount) === null || _surface$unmount === void 0 ? void 0 : _surface$unmount.call(surface); + }); + } + }, { + key: "runtimeSnapshot", + value: function runtimeSnapshot() { + return { + business: this.business, + page: this.page, + forms: this.forms, + query: this.query, + popup: this.popup, + popups: this.popups, + webchat: this.webchat, + whatsapp: this.whatsapp + }; + } + }, { + key: "hasExplicitSurface", + value: function hasExplicitSurface(config) { + return [config.popup, config.webchat, config.whatsappWidget].some(surface => surface && surface !== false && surface.id); + } + }, { + key: "hasDisabledSurface", + value: function hasDisabledSurface(config) { + return config.popup === false || config.webchat === false || config.whatsappWidget === false; + } + }, { + key: "runtimeWithoutDisabledSurfaces", + value: function runtimeWithoutDisabledSurfaces(previous, config) { + var disabled = { + popups: config.popup === false ? previous.popups : [], + webchat: config.webchat === false ? previous.webchat : undefined, + whatsapp: config.whatsappWidget === false ? previous.whatsapp : undefined + }; + this.unmountSurfaces(disabled); + return _objectSpread(_objectSpread({}, previous), {}, { + popup: config.popup === false ? undefined : previous.popup, + popups: config.popup === false ? [] : previous.popups, + webchat: config.webchat === false ? undefined : previous.webchat, + whatsapp: config.whatsappWidget === false ? undefined : previous.whatsapp + }); + } + }, { + key: "hasMountedSurfaces", + value: function hasMountedSurfaces(_ref2) { + var _ref2$popups = _ref2.popups, + popups = _ref2$popups === void 0 ? [] : _ref2$popups, + webchat = _ref2.webchat, + whatsapp = _ref2.whatsapp; + return popups.length > 0 || !!webchat || !!whatsapp; + } + }, { + key: "restoreRuntime", + value: function restoreRuntime(snapshot) { + Object.assign(this, snapshot); + } + }, { + key: "configurationSnapshot", + value: function configurationSnapshot() { + return { + apiRoot: Configuration.apiRoot, + actionCableUrl: Configuration.actionCableUrl, + autoGenerateSession: Configuration.autoGenerateSession, + session: Configuration.session, + locale: Configuration.locale, + forms: { + autoMount: Configuration.forms.autoMount, + successMessage: Configuration.forms.successMessage + }, + popup: { + id: Configuration.popup.id, + container: Configuration.popup.container, + device: Configuration.popup.device + }, + webchat: { + id: Configuration.webchat.id, + container: Configuration.webchat.container, + placement: Configuration.webchat.placement, + style: this.clone(Configuration.webchat.style), + appearance: this.clone(Configuration.webchat.appearance), + whatsapp: this.clone(Configuration.webchat.whatsapp), + mode: Configuration.webchat.mode, + behaviour: this.clone(Configuration.webchat.behaviour), + behaviourOverride: Configuration.webchat.hasBehaviourOverride, + strategy: Configuration.webchat._strategy + }, + whatsapp: { + id: Configuration.whatsapp.id, + container: Configuration.whatsapp.container, + placement: Configuration.whatsapp.placement, + appearance: this.clone(Configuration.whatsapp.appearance), + number: Configuration.whatsapp.number, + body: Configuration.whatsapp.body + } + }; + } + }, { + key: "restoreConfiguration", + value: function restoreConfiguration(snapshot) { + Configuration.apiRoot = snapshot.apiRoot; + Configuration.actionCableUrl = snapshot.actionCableUrl; + Configuration.autoGenerateSession = snapshot.autoGenerateSession; + Configuration.session = snapshot.session; + Configuration.locale = snapshot.locale; + Configuration.forms.assign(snapshot.forms); + Configuration.popup.assign(snapshot.popup); + Configuration.webchat.assign(snapshot.webchat); + Configuration.webchat.behaviourOverride = snapshot.webchat.behaviourOverride; + Configuration.whatsapp.assign(snapshot.whatsapp); + } + }, { + key: "clone", + value: function clone(value) { + if (Array.isArray(value)) return value.map(item => this.clone(item)); + if (!this.isPlainObject(value)) return value; + return Object.fromEntries(Object.entries(value).map(_ref3 => { + var _ref4 = _slicedToArray(_ref3, 2), + key = _ref4[0], + item = _ref4[1]; + return [key, this.clone(item)]; + })); + } }, { key: "mergeWebchatConfig", value: function mergeWebchatConfig(dashboardConfig, localConfig) { @@ -81,14 +289,24 @@ var Hellotext = /*#__PURE__*/function () { value: function mergePopupConfig(dashboardConfig, localConfig) { return this.deepMergePlainObjects(dashboardConfig, localConfig); } + }, { + key: "popupConfigs", + value: function popupConfigs(businessData, localConfig) { + if (localConfig.id) { + return [localConfig]; + } + var configuredPopups = Array.isArray(businessData && businessData.popups) ? businessData.popups.filter(config => config && config.id) : []; + var dashboardConfigs = configuredPopups.length > 0 ? configuredPopups : [businessData && businessData.popup || {}]; + return dashboardConfigs.filter(config => config && config.id).map(config => this.mergePopupConfig(config, localConfig)).filter((config, index, configs) => configs.findIndex(candidate => candidate.id === config.id) === index); + } }, { key: "deepMergePlainObjects", value: function deepMergePlainObjects(base, override) { var result = _objectSpread({}, base); - Object.entries(override).forEach(_ref => { - var _ref2 = _slicedToArray(_ref, 2), - key = _ref2[0], - value = _ref2[1]; + Object.entries(override).forEach(_ref5 => { + var _ref6 = _slicedToArray(_ref5, 2), + key = _ref6[0], + value = _ref6[1]; if (this.isPlainObject(value) && this.isPlainObject(result[key])) { result[key] = this.deepMergePlainObjects(result[key], value); } else { @@ -269,6 +487,9 @@ Hellotext.eventEmitter = new Event(); Hellotext.forms = void 0; Hellotext.business = void 0; Hellotext.popup = void 0; +Hellotext.popups = []; Hellotext.webchat = void 0; Hellotext.whatsapp = void 0; +Hellotext.initializationGeneration = 0; +Hellotext.initializationBaseline = void 0; export default Hellotext; \ No newline at end of file diff --git a/lib/models/business.cjs b/lib/models/business.cjs index 37b6b451..75ec1b1c 100644 --- a/lib/models/business.cjs +++ b/lib/models/business.cjs @@ -38,6 +38,7 @@ const stylesheetLoadTimeout = 10000; * @property {String} [locale] - Default dashboard locale for the business. * @property {String} [style_url] - Stylesheet URL to inject for dashboard-managed surfaces. * @property {{id: String}|null} [popup] - Dashboard popup defaults. + * @property {Array<{id: String}>} [popups] - Dashboard popups for automatic loading. * @property {BusinessWebchat|null} [webchat] - Dashboard webchat defaults. * @property {{id: String}|null} [whatsapp] - Dashboard WhatsApp widget defaults. * @property {String|Array} [whitelist] - Domain whitelist configuration. @@ -57,6 +58,7 @@ let Business = exports.Business = /*#__PURE__*/function () { this.data = null; this.stylesheet = null; this.stylesheetLoaded = Promise.resolve(false); + this.holdsStylesheet = false; } /** @@ -69,9 +71,12 @@ let Business = exports.Business = /*#__PURE__*/function () { */ return _createClass(Business, [{ key: "hydrate", - value: async function hydrate() { + value: async function hydrate({ + apiRoot, + stylesheet = true + } = {}) { try { - const response = await _businesses.default.get(this.id); + const response = apiRoot ? await _businesses.default.get(this.id, apiRoot) : await _businesses.default.get(this.id); if (response.ok === false) { return null; } @@ -79,7 +84,9 @@ let Business = exports.Business = /*#__PURE__*/function () { if (!business) { return null; } - this.setData(business); + this.setData(business, { + stylesheet + }); if (business.locale) { this.setLocale(business.locale); } @@ -95,15 +102,40 @@ let Business = exports.Business = /*#__PURE__*/function () { */ }, { key: "setData", - value: function setData(data) { + value: function setData(data, { + stylesheet = true + } = {}) { this.data = data; - if (typeof document !== 'undefined' && data.style_url) { - this.stylesheet = this.constructor.ensureStylesheet(data.style_url); + if (stylesheet) this.loadStylesheet(); + } + }, { + key: "loadStylesheet", + value: function loadStylesheet() { + var _this$data; + if (typeof document !== 'undefined' && (_this$data = this.data) !== null && _this$data !== void 0 && _this$data.style_url) { + const stylesheet = this.constructor.ensureStylesheet(this.data.style_url); + if (this.stylesheet !== stylesheet || !this.holdsStylesheet) { + this.releaseStylesheet(); + this.stylesheet = stylesheet; + this.holdsStylesheet = true; + stylesheet._hellotextStylesheetUsers = (stylesheet._hellotextStylesheetUsers || 0) + 1; + } this.stylesheetLoaded = this.constructor.waitForStylesheet(this.stylesheet); - } else { - this.stylesheet = null; - this.stylesheetLoaded = Promise.resolve(false); + return; } + this.releaseStylesheet(); + this.stylesheet = null; + this.stylesheetLoaded = Promise.resolve(false); + } + }, { + key: "releaseStylesheet", + value: function releaseStylesheet() { + if (!this.stylesheet || !this.holdsStylesheet) return; + const stylesheet = this.stylesheet; + stylesheet._hellotextStylesheetUsers -= 1; + if (stylesheet._hellotextStylesheetUsers <= 0) stylesheet.remove(); + this.holdsStylesheet = false; + this.stylesheet = null; } }, { key: "subscription", diff --git a/lib/models/business.js b/lib/models/business.js index 49065885..0834cd41 100644 --- a/lib/models/business.js +++ b/lib/models/business.js @@ -33,6 +33,7 @@ var stylesheetLoadTimeout = 10000; * @property {String} [locale] - Default dashboard locale for the business. * @property {String} [style_url] - Stylesheet URL to inject for dashboard-managed surfaces. * @property {{id: String}|null} [popup] - Dashboard popup defaults. + * @property {Array<{id: String}>} [popups] - Dashboard popups for automatic loading. * @property {BusinessWebchat|null} [webchat] - Dashboard webchat defaults. * @property {{id: String}|null} [whatsapp] - Dashboard WhatsApp widget defaults. * @property {String|Array} [whitelist] - Domain whitelist configuration. @@ -52,6 +53,7 @@ var Business = /*#__PURE__*/function () { this.data = null; this.stylesheet = null; this.stylesheetLoaded = Promise.resolve(false); + this.holdsStylesheet = false; } /** @@ -66,8 +68,12 @@ var Business = /*#__PURE__*/function () { key: "hydrate", value: (function () { var _hydrate = _asyncToGenerator(function* () { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + apiRoot = _ref.apiRoot, + _ref$stylesheet = _ref.stylesheet, + stylesheet = _ref$stylesheet === void 0 ? true : _ref$stylesheet; try { - var response = yield BusinessesAPI.get(this.id); + var response = apiRoot ? yield BusinessesAPI.get(this.id, apiRoot) : yield BusinessesAPI.get(this.id); if (response.ok === false) { return null; } @@ -75,7 +81,9 @@ var Business = /*#__PURE__*/function () { if (!business) { return null; } - this.setData(business); + this.setData(business, { + stylesheet + }); if (business.locale) { this.setLocale(business.locale); } @@ -97,14 +105,40 @@ var Business = /*#__PURE__*/function () { }, { key: "setData", value: function setData(data) { + var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref2$stylesheet = _ref2.stylesheet, + stylesheet = _ref2$stylesheet === void 0 ? true : _ref2$stylesheet; this.data = data; - if (typeof document !== 'undefined' && data.style_url) { - this.stylesheet = this.constructor.ensureStylesheet(data.style_url); + if (stylesheet) this.loadStylesheet(); + } + }, { + key: "loadStylesheet", + value: function loadStylesheet() { + var _this$data; + if (typeof document !== 'undefined' && (_this$data = this.data) !== null && _this$data !== void 0 && _this$data.style_url) { + var stylesheet = this.constructor.ensureStylesheet(this.data.style_url); + if (this.stylesheet !== stylesheet || !this.holdsStylesheet) { + this.releaseStylesheet(); + this.stylesheet = stylesheet; + this.holdsStylesheet = true; + stylesheet._hellotextStylesheetUsers = (stylesheet._hellotextStylesheetUsers || 0) + 1; + } this.stylesheetLoaded = this.constructor.waitForStylesheet(this.stylesheet); - } else { - this.stylesheet = null; - this.stylesheetLoaded = Promise.resolve(false); + return; } + this.releaseStylesheet(); + this.stylesheet = null; + this.stylesheetLoaded = Promise.resolve(false); + } + }, { + key: "releaseStylesheet", + value: function releaseStylesheet() { + if (!this.stylesheet || !this.holdsStylesheet) return; + var stylesheet = this.stylesheet; + stylesheet._hellotextStylesheetUsers -= 1; + if (stylesheet._hellotextStylesheetUsers <= 0) stylesheet.remove(); + this.holdsStylesheet = false; + this.stylesheet = null; } }, { key: "subscription", diff --git a/lib/models/popup.cjs b/lib/models/popup.cjs index 29d3a132..13f21e3d 100644 --- a/lib/models/popup.cjs +++ b/lib/models/popup.cjs @@ -18,18 +18,20 @@ let Popup = exports.Popup = /*#__PURE__*/function () { _classCallCheck(this, Popup); this.data = data; this.mounted = false; + this.unmounted = false; this.rendered = Promise.resolve(false); } return _createClass(Popup, [{ key: "render", value: async function render() { - if (!this.data.html) return false; + if (!this.data.html || this.unmounted) return false; const container = this.containerToAppendTo; if (!container) { console.warn(`Hellotext popup was not mounted because the container ${_core.Configuration.popup.container} was not found.`); return false; } - if (!(await this.stylesheetLoaded)) { + if (!(await this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false; console.warn('Hellotext popup was not mounted because its stylesheet failed to load.'); return false; } @@ -37,6 +39,14 @@ let Popup = exports.Popup = /*#__PURE__*/function () { this.mounted = true; return true; } + }, { + key: "unmount", + value: function unmount() { + var _this$data$html; + this.unmounted = true; + (_this$data$html = this.data.html) === null || _this$data$html === void 0 || _this$data$html.remove(); + this.mounted = false; + } }, { key: "containerToAppendTo", get: function () { diff --git a/lib/models/popup.js b/lib/models/popup.js index b1e9fb09..d59f3d2f 100644 --- a/lib/models/popup.js +++ b/lib/models/popup.js @@ -13,19 +13,21 @@ var Popup = /*#__PURE__*/function () { _classCallCheck(this, Popup); this.data = data; this.mounted = false; + this.unmounted = false; this.rendered = Promise.resolve(false); } return _createClass(Popup, [{ key: "render", value: function () { var _render = _asyncToGenerator(function* () { - if (!this.data.html) return false; + if (!this.data.html || this.unmounted) return false; var container = this.containerToAppendTo; if (!container) { console.warn("Hellotext popup was not mounted because the container ".concat(Configuration.popup.container, " was not found.")); return false; } - if (!(yield this.stylesheetLoaded)) { + if (!(yield this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false; console.warn('Hellotext popup was not mounted because its stylesheet failed to load.'); return false; } @@ -38,6 +40,14 @@ var Popup = /*#__PURE__*/function () { } return render; }() + }, { + key: "unmount", + value: function unmount() { + var _this$data$html; + this.unmounted = true; + (_this$data$html = this.data.html) === null || _this$data$html === void 0 || _this$data$html.remove(); + this.mounted = false; + } }, { key: "containerToAppendTo", get: function get() { diff --git a/lib/models/webchat.cjs b/lib/models/webchat.cjs index c8153736..59bec215 100644 --- a/lib/models/webchat.cjs +++ b/lib/models/webchat.cjs @@ -18,13 +18,16 @@ let Webchat = exports.Webchat = /*#__PURE__*/function () { _classCallCheck(this, Webchat); this.data = data; this.mounted = false; + this.unmounted = false; this.rendered = Promise.resolve(false); } return _createClass(Webchat, [{ key: "render", value: async function render() { + if (!this.data.html || this.unmounted) return false; this.applyBehaviourOverride(); - if (!(await this.stylesheetLoaded)) { + if (!(await this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false; console.warn('Hellotext webchat was not mounted because its stylesheet failed to load.'); return false; } @@ -33,6 +36,15 @@ let Webchat = exports.Webchat = /*#__PURE__*/function () { this.mounted = true; return true; } + }, { + key: "unmount", + value: function unmount() { + var _this$data$html, _document$querySelect; + this.unmounted = true; + (_this$data$html = this.data.html) === null || _this$data$html === void 0 || _this$data$html.remove(); + (_document$querySelect = document.querySelector('.hellotext--whatsapp-widget')) === null || _document$querySelect === void 0 || _document$querySelect.classList.remove('hellotext--with-webchat'); + this.mounted = false; + } }, { key: "applyBehaviourOverride", value: function applyBehaviourOverride() { diff --git a/lib/models/webchat.js b/lib/models/webchat.js index d9990d40..0e9d9217 100644 --- a/lib/models/webchat.js +++ b/lib/models/webchat.js @@ -13,14 +13,17 @@ var Webchat = /*#__PURE__*/function () { _classCallCheck(this, Webchat); this.data = data; this.mounted = false; + this.unmounted = false; this.rendered = Promise.resolve(false); } return _createClass(Webchat, [{ key: "render", value: function () { var _render = _asyncToGenerator(function* () { + if (!this.data.html || this.unmounted) return false; this.applyBehaviourOverride(); - if (!(yield this.stylesheetLoaded)) { + if (!(yield this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false; console.warn('Hellotext webchat was not mounted because its stylesheet failed to load.'); return false; } @@ -34,6 +37,15 @@ var Webchat = /*#__PURE__*/function () { } return render; }() + }, { + key: "unmount", + value: function unmount() { + var _this$data$html, _document$querySelect; + this.unmounted = true; + (_this$data$html = this.data.html) === null || _this$data$html === void 0 || _this$data$html.remove(); + (_document$querySelect = document.querySelector('.hellotext--whatsapp-widget')) === null || _document$querySelect === void 0 || _document$querySelect.classList.remove('hellotext--with-webchat'); + this.mounted = false; + } }, { key: "applyBehaviourOverride", value: function applyBehaviourOverride() { diff --git a/lib/models/whatsapp_widget.cjs b/lib/models/whatsapp_widget.cjs index b87d4416..cf2ef18f 100644 --- a/lib/models/whatsapp_widget.cjs +++ b/lib/models/whatsapp_widget.cjs @@ -18,18 +18,20 @@ let WhatsAppWidget = exports.WhatsAppWidget = /*#__PURE__*/function () { _classCallCheck(this, WhatsAppWidget); this.data = data; this.mounted = false; + this.unmounted = false; this.rendered = Promise.resolve(false); } return _createClass(WhatsAppWidget, [{ key: "render", value: async function render() { - if (!this.data.html) return false; + if (!this.data.html || this.unmounted) return false; const container = this.containerToAppendTo; if (!container) { console.warn(`Hellotext WhatsApp widget was not mounted because the container ${_core.Configuration.whatsapp.container} was not found.`); return false; } - if (!(await this.stylesheetLoaded)) { + if (!(await this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false; console.warn('Hellotext WhatsApp widget was not mounted because its stylesheet failed to load.'); return false; } @@ -38,6 +40,15 @@ let WhatsAppWidget = exports.WhatsAppWidget = /*#__PURE__*/function () { this.mounted = true; return true; } + }, { + key: "unmount", + value: function unmount() { + var _this$data$html, _document$querySelect; + this.unmounted = true; + (_this$data$html = this.data.html) === null || _this$data$html === void 0 || _this$data$html.remove(); + (_document$querySelect = document.querySelector('.hellotext--webchat:not(.hellotext--whatsapp-widget)')) === null || _document$querySelect === void 0 || _document$querySelect.classList.remove('hellotext--with-whatsapp-widget'); + this.mounted = false; + } }, { key: "containerToAppendTo", get: function () { diff --git a/lib/models/whatsapp_widget.js b/lib/models/whatsapp_widget.js index 757f1a06..02810658 100644 --- a/lib/models/whatsapp_widget.js +++ b/lib/models/whatsapp_widget.js @@ -13,19 +13,21 @@ var WhatsAppWidget = /*#__PURE__*/function () { _classCallCheck(this, WhatsAppWidget); this.data = data; this.mounted = false; + this.unmounted = false; this.rendered = Promise.resolve(false); } return _createClass(WhatsAppWidget, [{ key: "render", value: function () { var _render = _asyncToGenerator(function* () { - if (!this.data.html) return false; + if (!this.data.html || this.unmounted) return false; var container = this.containerToAppendTo; if (!container) { console.warn("Hellotext WhatsApp widget was not mounted because the container ".concat(Configuration.whatsapp.container, " was not found.")); return false; } - if (!(yield this.stylesheetLoaded)) { + if (!(yield this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false; console.warn('Hellotext WhatsApp widget was not mounted because its stylesheet failed to load.'); return false; } @@ -39,6 +41,15 @@ var WhatsAppWidget = /*#__PURE__*/function () { } return render; }() + }, { + key: "unmount", + value: function unmount() { + var _this$data$html, _document$querySelect; + this.unmounted = true; + (_this$data$html = this.data.html) === null || _this$data$html === void 0 || _this$data$html.remove(); + (_document$querySelect = document.querySelector('.hellotext--webchat:not(.hellotext--whatsapp-widget)')) === null || _document$querySelect === void 0 || _document$querySelect.classList.remove('hellotext--with-whatsapp-widget'); + this.mounted = false; + } }, { key: "containerToAppendTo", get: function get() { diff --git a/src/api/businesses.js b/src/api/businesses.js index e96e38d3..449607a3 100644 --- a/src/api/businesses.js +++ b/src/api/businesses.js @@ -1,12 +1,12 @@ import { Configuration } from '../core' export default class { - static get endpoint() { - return Configuration.endpoint('public/businesses') + static endpoint(apiRoot = Configuration.apiRoot) { + return `${apiRoot}/public/businesses` } - static async get(id) { - return fetch(`${this.endpoint}/${id}`, { + static async get(id, apiRoot) { + return fetch(`${this.endpoint(apiRoot)}/${id}`, { method: 'GET', headers: { Authorization: `Bearer ${id}`, diff --git a/src/controllers/popup_controller.js b/src/controllers/popup_controller.js index d05161a5..76ff3116 100644 --- a/src/controllers/popup_controller.js +++ b/src/controllers/popup_controller.js @@ -25,6 +25,9 @@ import API from '../api' * - rules: Persisted AND display rules. */ export default class extends Controller { + static controllers = new Set() + static displayOwner + static targets = [ 'bubble', 'dialog', @@ -44,6 +47,7 @@ export default class extends Controller { } connect() { + this.constructor.controllers.add(this) this.stepIndex = 0 this.onScroll = this.evaluateDisplay.bind(this) this.resendLabel = this.hasResendButtonTarget ? this.resendButtonTarget.textContent.trim() : '' @@ -56,6 +60,8 @@ export default class extends Controller { } disconnect() { + this.releaseDisplay() + this.constructor.controllers.delete(this) window.removeEventListener('scroll', this.onScroll) this.stopResendCooldown() } @@ -71,14 +77,11 @@ export default class extends Controller { close(event) { if (event) event.preventDefault() + this.dismissed = true this.hideElement(this.dialogTarget) - - if (this.hasBubbleValue && this.hasBubbleTarget) { - this.showElement(this.element) - this.showElement(this.bubbleTarget) - } else { - this.hideElement(this.element) - } + if (this.hasBubbleTarget) this.hideElement(this.bubbleTarget) + this.hideElement(this.element) + this.releaseDisplay() } async next(event) { @@ -149,7 +152,10 @@ export default class extends Controller { } evaluateDisplay() { - if (!this.matchesDevice() || !this.rulesWithoutScrollPass()) return + if (this.dismissed || !this.matchesDevice() || !this.rulesWithoutScrollPass()) { + this.releaseDisplay() + return + } if (this.scrollRule && !this.scrollRulePasses()) { window.addEventListener('scroll', this.onScroll, { passive: true }) @@ -157,9 +163,29 @@ export default class extends Controller { } window.removeEventListener('scroll', this.onScroll) + if (!this.claimDisplay()) return this.showInitialState() } + claimDisplay() { + const Controller = this.constructor + + if (Controller.displayOwner && Controller.displayOwner !== this) return false + + Controller.displayOwner = this + return true + } + + releaseDisplay() { + const Controller = this.constructor + if (Controller.displayOwner !== this) return + + Controller.displayOwner = undefined + Controller.controllers.forEach(controller => { + if (controller !== this) controller.evaluateDisplay() + }) + } + showInitialState() { this.showElement(this.element) @@ -247,7 +273,13 @@ export default class extends Controller { async resend(event) { if (event) event.preventDefault() - if (!this.submissionId || !this.submissionActionToken || this.resendPending || this.resendCooldownActive) return + if ( + !this.submissionId || + !this.submissionActionToken || + this.resendPending || + this.resendCooldownActive + ) + return const identity = this.completedIdentity if (!identity) return @@ -281,7 +313,9 @@ export default class extends Controller { const input = this.completedIdentity?.input if (!input) return - const stepIndex = this.stepTargets.findIndex(step => step.dataset.stepId === input.dataset.popupStepId) + const stepIndex = this.stepTargets.findIndex( + step => step.dataset.stepId === input.dataset.popupStepId, + ) if (stepIndex < 0) return this.stopResendCooldown() @@ -329,11 +363,13 @@ export default class extends Controller { } get completionIdentity() { - return this.identityInputs.map(input => ({ - input, - kind: input.dataset.popupFieldKind, - value: this.identityValue(input), - })).find(({ value }) => value) + return this.identityInputs + .map(input => ({ + input, + kind: input.dataset.popupFieldKind, + value: this.identityValue(input), + })) + .find(({ value }) => value) } get completedIdentity() { @@ -349,7 +385,9 @@ export default class extends Controller { renderNoDeliveryCopy() { const headline = this.completedTarget.querySelector('.hellotext--popup__completion-headline') - const description = this.completedTarget.querySelector('.hellotext--popup__completion-description') + const description = this.completedTarget.querySelector( + '.hellotext--popup__completion-description', + ) if (headline && this.completedTarget.dataset.notRequiredHeadline) { headline.innerHTML = '' @@ -360,7 +398,8 @@ export default class extends Controller { headline.appendChild(title) } - if (description) description.textContent = this.completedTarget.dataset.notRequiredDescription || '' + if (description) + description.textContent = this.completedTarget.dataset.notRequiredDescription || '' } currentStepValid() { @@ -369,7 +408,9 @@ export default class extends Controller { showErrorMessages(inputs) { inputs.forEach(input => { - const container = input.closest('.hellotext--popup-field')?.querySelector('[data-error-container]') + const container = input + .closest('.hellotext--popup-field') + ?.querySelector('[data-error-container]') if (!container) return container.textContent = input.validity.valid ? '' : input.validationMessage @@ -378,7 +419,9 @@ export default class extends Controller { clearErrorMessages(inputs = this.inputTargets) { inputs.forEach(input => { - const container = input.closest('.hellotext--popup-field')?.querySelector('[data-error-container]') + const container = input + .closest('.hellotext--popup-field') + ?.querySelector('[data-error-container]') if (container) container.textContent = '' }) } @@ -477,7 +520,10 @@ export default class extends Controller { this._completionTextTemplates = [] while (walker.nextNode()) { - this._completionTextTemplates.push({ node: walker.currentNode, template: walker.currentNode.nodeValue }) + this._completionTextTemplates.push({ + node: walker.currentNode, + template: walker.currentNode.nodeValue, + }) } return this._completionTextTemplates @@ -502,7 +548,9 @@ export default class extends Controller { } pagePropertyRulePasses(condition) { - const expected = String(condition.value || '').trim().toLowerCase() + const expected = String(condition.value || '') + .trim() + .toLowerCase() if (!expected) return true const actual = this.pagePropertyValue(condition.field) @@ -577,7 +625,9 @@ export default class extends Controller { } get scrollRule() { - return this.conditions.find(condition => condition.group === 'actions' && condition.type === 'scroll_depth') + return this.conditions.find( + condition => condition.group === 'actions' && condition.type === 'scroll_depth', + ) } get scrollPercentage() { diff --git a/src/hellotext.js b/src/hellotext.js index 89bd6eeb..d6b49a20 100644 --- a/src/hellotext.js +++ b/src/hellotext.js @@ -21,8 +21,11 @@ class Hellotext { static forms static business static popup + static popups = [] static webchat static whatsapp + static initializationGeneration = 0 + static initializationBaseline /** * initialize the module. @@ -30,65 +33,242 @@ class Hellotext { * @param { Configuration } config */ static async initialize(business, config = {}) { - this.business = new Business(business) - this.page = new Page() - - Configuration.assign(config) - Session.initialize(this.page) - - this.forms = new FormCollection() - - this.query = new Query() - - const businessData = await this.business.hydrate() - const popupConfig = - config.popup === false - ? false - : this.mergePopupConfig( - (businessData && businessData.popup) || {}, - config.popup || {}, - ) - const webchatConfig = - config.webchat === false - ? false - : this.mergeWebchatConfig( - (businessData && businessData.webchat) || {}, - config.webchat || {}, - ) - const whatsappConfig = - config.whatsappWidget === false - ? false - : this.mergeWhatsAppConfig( - (businessData && businessData.whatsapp) || {}, - config.whatsappWidget || {}, - ) - - const hasExplicitBehaviourOverride = - config.webchat && - config.webchat !== false && - Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour') - Configuration.webchat.behaviourOverride = hasExplicitBehaviourOverride - - if (webchatConfig && webchatConfig.id) { - Configuration.webchat.assign(webchatConfig) - this.webchat = await Webchat.load(webchatConfig.id) + const generation = ++this.initializationGeneration + this.initializationBaseline ||= { + configuration: this.configurationSnapshot(), + runtime: this.runtimeSnapshot(), } + const { configuration, runtime: previous } = this.initializationBaseline + const staged = { popups: [] } + const nextBusiness = new Business(business) + + try { + const businessData = await nextBusiness.hydrate({ + apiRoot: config.apiRoot, + stylesheet: false, + }) + + if (!this.initializationIsCurrent(generation)) return + if (!businessData && this.hasMountedSurfaces(previous)) { + if (!this.hasExplicitSurface(config) && this.hasDisabledSurface(config)) { + this.restoreRuntime(this.runtimeWithoutDisabledSurfaces(previous, config)) + } else if (!this.hasExplicitSurface(config)) { + this.restoreRuntime(previous) + } + + if (!this.hasExplicitSurface(config)) { + this.restoreConfiguration(configuration) + return + } + } + + Configuration.assign(config) + this.business = nextBusiness + nextBusiness.loadStylesheet() + this.page = new Page() + Session.initialize(this.page) + this.forms = new FormCollection() + this.query = new Query() + this.popup = undefined + this.popups = [] + this.webchat = undefined + this.whatsapp = undefined + + const popupConfigs = + config.popup === false ? [] : this.popupConfigs(businessData, config.popup || {}) + const webchatConfig = + config.webchat === false + ? false + : this.mergeWebchatConfig( + (businessData && businessData.webchat) || {}, + config.webchat || {}, + ) + const whatsappConfig = + config.whatsappWidget === false + ? false + : this.mergeWhatsAppConfig( + (businessData && businessData.whatsapp) || {}, + config.whatsappWidget || {}, + ) + + const hasExplicitBehaviourOverride = + config.webchat && + config.webchat !== false && + Object.prototype.hasOwnProperty.call(config.webchat, 'behaviour') + Configuration.webchat.behaviourOverride = hasExplicitBehaviourOverride + + if (webchatConfig && webchatConfig.id) { + Configuration.webchat.assign(webchatConfig) + staged.webchat = await Webchat.load(webchatConfig.id) + if (!this.initializationIsCurrent(generation)) return + } + + if (whatsappConfig && whatsappConfig.id) { + Configuration.whatsapp.assign(whatsappConfig) + staged.whatsapp = await WhatsAppWidget.load(whatsappConfig.id) + if (!this.initializationIsCurrent(generation)) return + } + + if (popupConfigs.length > 0) { + Configuration.popup.assign(popupConfigs[0]) + for (const popupConfig of popupConfigs) { + const popup = await Popup.load(popupConfig.id) + staged.popups.push(popup) + if (!this.initializationIsCurrent(generation)) return + } + } + + this.unmountSurfaces(previous) + previous.business?.releaseStylesheet?.() + staged.webchat?.markCoexistingWidgets?.() + staged.whatsapp?.markCoexistingWidgets?.() + this.webchat = staged.webchat + this.whatsapp = staged.whatsapp + this.popups = staged.popups + this.popup = staged.popups[0] + + if (typeof MutationObserver !== 'undefined') { + this.forms.collectExistingFormsOnPage() + } + } catch (error) { + this.unmountSurfaces(staged) + nextBusiness.releaseStylesheet() + + if (this.initializationIsCurrent(generation)) { + this.restoreRuntime(previous) + this.restoreConfiguration(configuration) + } + + throw error + } finally { + if (!this.initializationIsCurrent(generation)) { + this.unmountSurfaces(staged) + nextBusiness.releaseStylesheet() + } else { + this.initializationBaseline = undefined + } + } + } + + static initializationIsCurrent(generation) { + return this.initializationGeneration === generation + } + + static unmountPopups() { + this.unmountSurfaces({ popups: this.popups }) + } + + static unmountSurfaces({ popups = [], webchat, whatsapp }) { + new Set([...popups, webchat, whatsapp]).forEach(surface => surface?.unmount?.()) + } - if (whatsappConfig && whatsappConfig.id) { - Configuration.whatsapp.assign(whatsappConfig) - this.whatsapp = await WhatsAppWidget.load(whatsappConfig.id) + static runtimeSnapshot() { + return { + business: this.business, + page: this.page, + forms: this.forms, + query: this.query, + popup: this.popup, + popups: this.popups, + webchat: this.webchat, + whatsapp: this.whatsapp, + } + } + + static hasExplicitSurface(config) { + return [config.popup, config.webchat, config.whatsappWidget].some( + surface => surface && surface !== false && surface.id, + ) + } + + static hasDisabledSurface(config) { + return config.popup === false || config.webchat === false || config.whatsappWidget === false + } + + static runtimeWithoutDisabledSurfaces(previous, config) { + const disabled = { + popups: config.popup === false ? previous.popups : [], + webchat: config.webchat === false ? previous.webchat : undefined, + whatsapp: config.whatsappWidget === false ? previous.whatsapp : undefined, } + this.unmountSurfaces(disabled) - if (popupConfig && popupConfig.id) { - Configuration.popup.assign(popupConfig) - this.popup = await Popup.load(popupConfig.id) + return { + ...previous, + popup: config.popup === false ? undefined : previous.popup, + popups: config.popup === false ? [] : previous.popups, + webchat: config.webchat === false ? undefined : previous.webchat, + whatsapp: config.whatsappWidget === false ? undefined : previous.whatsapp, } + } + + static hasMountedSurfaces({ popups = [], webchat, whatsapp }) { + return popups.length > 0 || !!webchat || !!whatsapp + } - if (typeof MutationObserver !== 'undefined') { - this.forms.collectExistingFormsOnPage() + static restoreRuntime(snapshot) { + Object.assign(this, snapshot) + } + + static configurationSnapshot() { + return { + apiRoot: Configuration.apiRoot, + actionCableUrl: Configuration.actionCableUrl, + autoGenerateSession: Configuration.autoGenerateSession, + session: Configuration.session, + locale: Configuration.locale, + forms: { + autoMount: Configuration.forms.autoMount, + successMessage: Configuration.forms.successMessage, + }, + popup: { + id: Configuration.popup.id, + container: Configuration.popup.container, + device: Configuration.popup.device, + }, + webchat: { + id: Configuration.webchat.id, + container: Configuration.webchat.container, + placement: Configuration.webchat.placement, + style: this.clone(Configuration.webchat.style), + appearance: this.clone(Configuration.webchat.appearance), + whatsapp: this.clone(Configuration.webchat.whatsapp), + mode: Configuration.webchat.mode, + behaviour: this.clone(Configuration.webchat.behaviour), + behaviourOverride: Configuration.webchat.hasBehaviourOverride, + strategy: Configuration.webchat._strategy, + }, + whatsapp: { + id: Configuration.whatsapp.id, + container: Configuration.whatsapp.container, + placement: Configuration.whatsapp.placement, + appearance: this.clone(Configuration.whatsapp.appearance), + number: Configuration.whatsapp.number, + body: Configuration.whatsapp.body, + }, } } + static restoreConfiguration(snapshot) { + Configuration.apiRoot = snapshot.apiRoot + Configuration.actionCableUrl = snapshot.actionCableUrl + Configuration.autoGenerateSession = snapshot.autoGenerateSession + Configuration.session = snapshot.session + Configuration.locale = snapshot.locale + Configuration.forms.assign(snapshot.forms) + Configuration.popup.assign(snapshot.popup) + Configuration.webchat.assign(snapshot.webchat) + Configuration.webchat.behaviourOverride = snapshot.webchat.behaviourOverride + Configuration.whatsapp.assign(snapshot.whatsapp) + } + + static clone(value) { + if (Array.isArray(value)) return value.map(item => this.clone(item)) + if (!this.isPlainObject(value)) return value + + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.clone(item)])) + } + static mergeWebchatConfig(dashboardConfig, localConfig) { return this.deepMergePlainObjects(dashboardConfig, localConfig) } @@ -101,6 +281,26 @@ class Hellotext { return this.deepMergePlainObjects(dashboardConfig, localConfig) } + static popupConfigs(businessData, localConfig) { + if (localConfig.id) { + return [localConfig] + } + + const configuredPopups = Array.isArray(businessData && businessData.popups) + ? businessData.popups.filter(config => config && config.id) + : [] + const dashboardConfigs = + configuredPopups.length > 0 ? configuredPopups : [(businessData && businessData.popup) || {}] + + return dashboardConfigs + .filter(config => config && config.id) + .map(config => this.mergePopupConfig(config, localConfig)) + .filter( + (config, index, configs) => + configs.findIndex(candidate => candidate.id === config.id) === index, + ) + } + static deepMergePlainObjects(base, override) { const result = { ...base } diff --git a/src/models/business.js b/src/models/business.js index 9abc3e8d..6f1e2ea8 100644 --- a/src/models/business.js +++ b/src/models/business.js @@ -27,6 +27,7 @@ const stylesheetLoadTimeout = 10000 * @property {String} [locale] - Default dashboard locale for the business. * @property {String} [style_url] - Stylesheet URL to inject for dashboard-managed surfaces. * @property {{id: String}|null} [popup] - Dashboard popup defaults. + * @property {Array<{id: String}>} [popups] - Dashboard popups for automatic loading. * @property {BusinessWebchat|null} [webchat] - Dashboard webchat defaults. * @property {{id: String}|null} [whatsapp] - Dashboard WhatsApp widget defaults. * @property {String|Array} [whitelist] - Domain whitelist configuration. @@ -45,6 +46,7 @@ class Business { this.data = null this.stylesheet = null this.stylesheetLoaded = Promise.resolve(false) + this.holdsStylesheet = false } /** @@ -55,9 +57,11 @@ class Business { * * @returns {Promise} */ - async hydrate() { + async hydrate({ apiRoot, stylesheet = true } = {}) { try { - const response = await BusinessesAPI.get(this.id) + const response = apiRoot + ? await BusinessesAPI.get(this.id, apiRoot) + : await BusinessesAPI.get(this.id) if (response.ok === false) { return null @@ -69,7 +73,7 @@ class Business { return null } - this.setData(business) + this.setData(business, { stylesheet }) if (business.locale) { this.setLocale(business.locale) @@ -85,16 +89,39 @@ class Business { * @param {BusinessData} data * @returns {void} */ - setData(data) { + setData(data, { stylesheet = true } = {}) { this.data = data - if (typeof document !== 'undefined' && data.style_url) { - this.stylesheet = this.constructor.ensureStylesheet(data.style_url) + if (stylesheet) this.loadStylesheet() + } + + loadStylesheet() { + if (typeof document !== 'undefined' && this.data?.style_url) { + const stylesheet = this.constructor.ensureStylesheet(this.data.style_url) + if (this.stylesheet !== stylesheet || !this.holdsStylesheet) { + this.releaseStylesheet() + this.stylesheet = stylesheet + this.holdsStylesheet = true + stylesheet._hellotextStylesheetUsers = (stylesheet._hellotextStylesheetUsers || 0) + 1 + } this.stylesheetLoaded = this.constructor.waitForStylesheet(this.stylesheet) - } else { - this.stylesheet = null - this.stylesheetLoaded = Promise.resolve(false) + return } + + this.releaseStylesheet() + this.stylesheet = null + this.stylesheetLoaded = Promise.resolve(false) + } + + releaseStylesheet() { + if (!this.stylesheet || !this.holdsStylesheet) return + + const stylesheet = this.stylesheet + stylesheet._hellotextStylesheetUsers -= 1 + if (stylesheet._hellotextStylesheetUsers <= 0) stylesheet.remove() + + this.holdsStylesheet = false + this.stylesheet = null } static get stylesheetSelector() { diff --git a/src/models/popup.js b/src/models/popup.js index b737b9b0..ad61838a 100644 --- a/src/models/popup.js +++ b/src/models/popup.js @@ -18,19 +18,24 @@ class Popup { constructor(data) { this.data = data this.mounted = false + this.unmounted = false this.rendered = Promise.resolve(false) } async render() { - if (!this.data.html) return false + if (!this.data.html || this.unmounted) return false const container = this.containerToAppendTo if (!container) { - console.warn(`Hellotext popup was not mounted because the container ${Configuration.popup.container} was not found.`) + console.warn( + `Hellotext popup was not mounted because the container ${Configuration.popup.container} was not found.`, + ) return false } - if (!await this.stylesheetLoaded) { + if (!(await this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false + console.warn('Hellotext popup was not mounted because its stylesheet failed to load.') return false } @@ -41,6 +46,12 @@ class Popup { return true } + unmount() { + this.unmounted = true + this.data.html?.remove() + this.mounted = false + } + get containerToAppendTo() { try { return document.querySelector(Configuration.popup.container) diff --git a/src/models/webchat.js b/src/models/webchat.js index 5a5115f8..3195d37f 100644 --- a/src/models/webchat.js +++ b/src/models/webchat.js @@ -18,13 +18,18 @@ class Webchat { constructor(data) { this.data = data this.mounted = false + this.unmounted = false this.rendered = Promise.resolve(false) } async render() { + if (!this.data.html || this.unmounted) return false + this.applyBehaviourOverride() - if (!await this.stylesheetLoaded) { + if (!(await this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false + console.warn('Hellotext webchat was not mounted because its stylesheet failed to load.') return false } @@ -36,6 +41,15 @@ class Webchat { return true } + unmount() { + this.unmounted = true + this.data.html?.remove() + document + .querySelector('.hellotext--whatsapp-widget') + ?.classList.remove('hellotext--with-webchat') + this.mounted = false + } + applyBehaviourOverride() { if (!Configuration.webchat.hasBehaviourOverride || !Configuration.webchat.behaviour) return diff --git a/src/models/whatsapp_widget.js b/src/models/whatsapp_widget.js index 9ecabe60..dd3887d1 100644 --- a/src/models/whatsapp_widget.js +++ b/src/models/whatsapp_widget.js @@ -7,7 +7,7 @@ class WhatsAppWidget { static async load(id) { const widget = new WhatsAppWidget({ id, - html: await API.whatsappWidgets.get(id) + html: await API.whatsappWidgets.get(id), }) widget.rendered = widget.render() @@ -18,20 +18,27 @@ class WhatsAppWidget { constructor(data) { this.data = data this.mounted = false + this.unmounted = false this.rendered = Promise.resolve(false) } async render() { - if (!this.data.html) return false + if (!this.data.html || this.unmounted) return false const container = this.containerToAppendTo if (!container) { - console.warn(`Hellotext WhatsApp widget was not mounted because the container ${Configuration.whatsapp.container} was not found.`) + console.warn( + `Hellotext WhatsApp widget was not mounted because the container ${Configuration.whatsapp.container} was not found.`, + ) return false } - if (!await this.stylesheetLoaded) { - console.warn('Hellotext WhatsApp widget was not mounted because its stylesheet failed to load.') + if (!(await this.stylesheetLoaded) || this.unmounted) { + if (this.unmounted) return false + + console.warn( + 'Hellotext WhatsApp widget was not mounted because its stylesheet failed to load.', + ) return false } @@ -42,6 +49,15 @@ class WhatsAppWidget { return true } + unmount() { + this.unmounted = true + this.data.html?.remove() + document + .querySelector('.hellotext--webchat:not(.hellotext--whatsapp-widget)') + ?.classList.remove('hellotext--with-whatsapp-widget') + this.mounted = false + } + get containerToAppendTo() { try { return document.querySelector(Configuration.whatsapp.container) From 4a238551d0fd1853143c721f205065d5acedd392 Mon Sep 17 00:00:00 2001 From: Anyelo Petit Date: Fri, 28 Aug 2026 20:02:54 -0400 Subject: [PATCH 11/11] popups: prepare runtime sdk release --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8c411149..abe3fa56 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hellotext/hellotext", - "version": "2.5.5", + "version": "2.5.7", "description": "Hellotext JavaScript Client", "source": "src/index.js", "main": "lib/index.cjs",