@xapp/form-widget 1.117.0 → 1.119.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../../chat-widget-core/dist/index.js","../src/utils/tracking.ts","../src/utils/index.ts","../src/utils/guards/isCarousel.ts","../src/utils/guards/isList.ts","../src/utils/guards/isForm.ts","../src/store/reducers/RootReducer.ts","../src/utils/guards/throwBadKind.ts","../src/store/SearchStoreContext.ts","../src/store/SearchStoreProvider.tsx","../src/store/useSearchStore.ts","../src/store/useSearchState.ts","../../../node_modules/style-inject/dist/style-inject.es.js","../src/components/ModalDialog/ModalDialog.tsx","../src/api/stentor-api.ts","../src/utils/getActionLabel.ts","../src/utils/SearchWidgetConfigContext.ts","../src/utils/useLoading.ts","../src/utils/useIsMounted.ts","../src/utils/useTrustedForm.ts","../src/utils/metaCookies.ts","../src/components/icons/LeftAngleIcon/LeftAngleIcon.tsx","../src/components/icons/RightAngleIcon/RightAngleIcon.tsx","../src/components/icons/SearchIcon/SearchIcon.tsx","../src/components/icons/SpinnerIcon/SpinnerIcon.tsx","../src/components/icons/FieldIcons/FieldIcons.tsx","../src/components/SearchResponseBubble/SearchResponseBubble.tsx","../src/components/Card/utils.ts","../src/components/Card/Card.tsx","../src/components/Carousel/CarouselItem.tsx","../src/components/Carousel/Carousel.tsx","../src/components/SearchResponseCarouselDisplay/SearchResponseCarouselDisplay.tsx","../src/components/Cards/Cards.tsx","../src/components/SearchResponseListDisplay/SearchResponseListDisplay.tsx","../src/utils/comparator.ts","../src/utils/templating.ts","../../../node_modules/dayjs/dayjs.min.js","../../../node_modules/dayjs/plugin/timezone.js","../../../node_modules/dayjs/plugin/utc.js","../src/utils/timeSlots.ts","../src/utils/useExternalWidget.ts","../src/components/FormFieldChips/FormFieldSelect.tsx","../src/components/FormFieldCard/FormFieldCard.tsx","../src/components/FormFieldChips/FormFieldChips.tsx","../src/utils/formatToInputProps.ts","../src/components/FormFieldTextInput/FormFieldTextInput.tsx","../src/components/FormFieldDropdown/FormFieldDropdown.tsx","../src/components/Calendar/Calendar.tsx","../src/utils/busyDays.ts","../src/components/FormFieldDate/dateAvailability.ts","../src/components/FormFieldDate/FormFieldDate.tsx","../src/components/FormFieldDateRange/FormFieldDateRange.tsx","../src/components/FormFieldDateTime/FormFieldDateTime.tsx","../../../node_modules/autosuggest-highlight/parse/index.js","../src/utils/AddressAutocompleteService.ts","../src/components/FormFieldTextInputAddress/FormFieldTextInputAddress.tsx","../src/components/FormStepDisplay/validators.ts","../src/components/FormStepDisplay/FormStepDisplay.tsx","../src/utils/guards/isField.ts","../src/components/FormFrame/FormFrame.tsx","../src/components/SimpleNavigationHeader/SimpleNavigationHeader.tsx","../src/utils/isInServiceArea.ts","../src/utils/extractZipFromAddress.ts","../src/components/FormDisplay/FormDisplay.tsx","../src/components/ResponseDisplay/ResponseDisplay.tsx","../src/components/SearchResponseHtml/SearchResponseHtml.tsx","../src/components/SearchResponseText/SearchResponseText.tsx","../src/components/SearchResponseAudio/SearchResponseAudio.tsx","../src/components/SearchResponseOutputSpeech/SearchResponseOutputSpeech.tsx","../src/utils/parseAudio.ts","../../../node_modules/stentor-guards/lib/isLinkoutSuggestion.js","../src/components/Button/Button.tsx","../src/components/SuggestedAction/SuggestedAction.tsx","../src/components/SuggestedActions/SuggestedActions.tsx","../src/components/FormResponse/SearchResponsePart.tsx","../src/components/FormResponse/FormResponse.tsx","../src/services/EventTrackingService.ts","../src/components/FormWidget/FormWidget.tsx","../src/components/WidgetStylesheet/WidgetStylesheet.tsx","../src/constants/variables.ts","../src/components/SideButton/SideButton.tsx","../src/hooks/useAutoOpenTriggers.ts","../src/hooks/useFormPageMarker.ts","../src/utils/isEmbedded.ts","../src/utils/earlyClicks.ts","../src/components/Form/Form.tsx","../src/store/useSearchDispatch.ts","../src/config/config.ts","../src/utils/parseWidgetEnv.ts","../src/utils/stylePreset.ts","../src/presets/costguide.ts"],"sourcesContent":["'use strict';\n\nvar jsxRuntime = require('react/jsx-runtime');\nvar react = require('react');\n\nvar IconButton = function (props) {\n var Icon = props.icon;\n return (jsxRuntime.jsx(\"div\", { tabIndex: props.tabIndex ? Number(props.tabIndex) : 0, className: \"xapp-search-icon-button \".concat(props.className || \"\"), onClick: props.onClick, children: jsxRuntime.jsx(\"div\", { className: \"xapp-search-icon-button__content\", children: jsxRuntime.jsx(Icon, {}) }) }));\n};\n\nvar MessageBubble = function (props) {\n return jsxRuntime.jsx(\"div\", { className: \"xappw-message-bubble\", children: props.children });\n};\n\n// compile time full switch-case verification\nfunction throwBadKind(x) {\n throw new Error(\"Unknown kind \" + x);\n}\n\nvar RichTextBoldSpan = function (props) {\n var format = props.format, text = props.text;\n return (jsxRuntime.jsx(\"span\", { \"data-rich-text-type\": \"bold\", className: \"xapp-search-rich-text-bold-span\", children: text.substring(format.start, format.end) }));\n};\n\nvar RichTextInputSpan = function (props) {\n var format = props.format, text = props.text, readOnly = props.readOnly, onClick = props.onClick;\n var defaultValue = format.text || text.substring(format.start, format.end);\n var _a = react.useState(defaultValue), value = _a[0], setValue = _a[1];\n var handleChange = react.useCallback(function (ev) {\n setValue(ev.target.value);\n }, []);\n var handleClick = react.useCallback(function (ev) {\n if (onClick) {\n var res = onClick(format);\n if (res === false) {\n ev.preventDefault();\n ev.stopPropagation();\n }\n }\n }, [onClick, format]);\n if (readOnly) {\n return (jsxRuntime.jsx(\"span\", { className: \"xapp-search-rich-text-input-span xapp-search-rich-text-input-span--readonly\", onClick: handleClick, children: defaultValue }));\n }\n return (jsxRuntime.jsx(\"input\", { type: \"text\", value: value, className: \"xapp-search-rich-text-input-span\", \"data-rich-text-type\": \"inputText\", onChange: handleChange, onClick: handleClick, readOnly: readOnly }));\n};\n\nvar RichTextNormalSpan = function (props) {\n var format = props.format, text = props.text;\n return (jsxRuntime.jsx(\"span\", { \"data-rich-text-type\": \"normal\", className: \"xapp-search-rich-text-normal-span\", children: text.substring(format.start, format.end) }));\n};\n\nvar RichTextSpan = function (props) {\n var format = props.format, text = props.text, readOnly = props.readOnly, onClick = props.onClick;\n var type = format.type;\n switch (type) {\n case \"normal\":\n return jsxRuntime.jsx(RichTextNormalSpan, { text: text, format: format, readOnly: readOnly });\n case \"bold\":\n return jsxRuntime.jsx(RichTextBoldSpan, { text: text, format: format, readOnly: readOnly });\n case \"inputText\":\n return (jsxRuntime.jsx(RichTextInputSpan, { text: text, format: format, readOnly: readOnly, onClick: onClick }));\n default:\n throwBadKind(type);\n }\n};\n\nfunction cleanRichTextValue(value) {\n var text = value.text, formats = value.formats;\n var newFormats = [];\n for (var _i = 0, formats_1 = formats; _i < formats_1.length; _i++) {\n var format = formats_1[_i];\n var type = format.type;\n switch (type) {\n case \"normal\":\n continue;\n case \"inputText\":\n newFormats.push(format);\n break;\n case \"bold\":\n if (newFormats.length > 0) {\n var prev = newFormats[newFormats.length - 1];\n if (prev.type === type && prev.end === format.start) {\n newFormats.pop();\n newFormats.push({\n type: type,\n start: prev.start,\n end: format.end\n });\n }\n }\n else {\n newFormats.push(format);\n }\n break;\n }\n }\n return {\n text: text,\n formats: newFormats\n };\n}\n\nfunction extendFormat(formats, length) {\n var res = [];\n var walkerIndex = 0;\n for (var _i = 0, formats_1 = formats; _i < formats_1.length; _i++) {\n var format = formats_1[_i];\n var start = format.start, end = format.end, type = format.type, text = format.text;\n if (walkerIndex < start) {\n res.push({\n type: \"normal\",\n start: walkerIndex,\n end: start\n });\n }\n res.push({\n type: type,\n start: start,\n end: end,\n text: text\n });\n walkerIndex = end;\n }\n if (walkerIndex < length) {\n res.push({\n type: \"normal\",\n start: walkerIndex,\n end: length\n });\n }\n return res;\n}\n\nfunction parseContent(node) {\n var children = node.childNodes;\n var formats = [];\n var text = \"\";\n children.forEach(function (child) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n var node_1 = child;\n var innerText = node_1.tagName === \"INPUT\" ? node_1.value : node_1.innerText;\n var type = node_1.dataset.richTextType;\n formats.push({\n type: type,\n start: text.length,\n end: text.length + innerText.length,\n });\n text += innerText;\n }\n if (child.nodeType === Node.TEXT_NODE) {\n var node_2 = child;\n var innerText = node_2.nodeValue;\n if (innerText) {\n formats.push({\n type: \"normal\",\n start: text.length,\n end: text.length + innerText.length,\n });\n text += innerText;\n }\n }\n });\n return cleanRichTextValue({\n text: text,\n formats: formats,\n });\n}\nfunction cleanContent(node) {\n var _a;\n var trash = [];\n var raw = node.childNodes;\n for (var i = 0; i < raw.length; i++) {\n var c = raw.item(i);\n if ((c === null || c === void 0 ? void 0 : c.nodeType) === Node.TEXT_NODE) {\n trash.push(c);\n }\n }\n for (var _i = 0, trash_1 = trash; _i < trash_1.length; _i++) {\n var c = trash_1[_i];\n try {\n (_a = c.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(c);\n }\n catch (_b) { }\n }\n}\nvar RichText = function (props) {\n var value = props.value, className = props.className, readOnly = props.readOnly, onInput = props.onInput, onChange = props.onChange, onSpanClick = props.onSpanClick;\n var formatsRaw = value.formats, text = value.text;\n var formats = react.useMemo(function () { return extendFormat(formatsRaw, text.length); }, [formatsRaw, text.length]);\n var handleInput = react.useCallback(function (ev) {\n var target = ev.currentTarget;\n var newValue = parseContent(target);\n if (onInput) {\n onInput(newValue);\n }\n }, [onInput]);\n var handleBlur = react.useCallback(function (ev) {\n var target = ev.currentTarget;\n var newValue = parseContent(target);\n cleanContent(target);\n if (onChange) {\n onChange(newValue);\n }\n }, [onChange]);\n return (jsxRuntime.jsx(\"div\", { id: props.id, className: \"xapp-search-rich-text \".concat(className || \"\"), contentEditable: !readOnly, suppressContentEditableWarning: true, onInput: handleInput, onBlur: handleBlur, onKeyDown: props.onKeyDown, children: formats.map(function (format, index) { return (jsxRuntime.jsx(RichTextSpan, { format: format, text: text, readOnly: readOnly, onClick: onSpanClick }, index)); }) }));\n};\n\nvar RichInput = function (props) {\n var id = props.id, value = props.value, type = props.type, autoFocus = props.autoFocus, spellCheck = props.spellCheck, tabIndex = props.tabIndex, maxLength = props.maxLength, enterKeyHint = props.enterKeyHint, onChange = props.onChange, onInput = props.onInput, onKeyDown = props.onKeyDown, onSearch = props.onSearch;\n var rich = value.formats.some(function (f) { return f.type === \"inputText\"; });\n var keyHint = enterKeyHint || (type === \"search\" ? \"search\" : \"send\");\n var handleChange = react.useCallback(function (ev) {\n if (onChange) {\n onChange({\n text: ev.target.value,\n formats: [],\n });\n }\n }, [onChange]);\n var handleRichChange = react.useCallback(function (val) {\n if (onChange) {\n onChange(val);\n }\n }, [onChange]);\n var handleInput = react.useCallback(function (ev) {\n if (onInput) {\n onInput({\n text: ev.target.value,\n formats: [],\n });\n }\n }, [onInput]);\n var handleRichInput = react.useCallback(function (val) {\n if (onInput) {\n onInput(val);\n }\n }, [onInput]);\n var handleKeyDown = react.useCallback(function (event) {\n if (onKeyDown) {\n onKeyDown(event);\n }\n }, [onKeyDown]);\n var inputRef = react.useRef(null);\n var inputNode = inputRef.current;\n react.useEffect(function () {\n if (inputNode && onSearch) {\n var handler_1 = function (ev) {\n var target = ev.target;\n if (target) {\n onSearch({\n text: target.value,\n formats: [],\n });\n }\n };\n inputNode.addEventListener(\"search\", handler_1);\n return function () {\n inputNode.removeEventListener(\"search\", handler_1);\n };\n }\n return undefined;\n }, [inputNode, onSearch]);\n return (jsxRuntime.jsx(\"div\", { className: \"xappw-rich-input \".concat(props.className), children: rich ? (jsxRuntime.jsx(RichText, { id: id, value: value, onChange: handleRichChange, onInput: handleRichInput, onKeyDown: handleKeyDown, className: \"xappw-rich-input__input \".concat(props.className, \"__input\") })) : (jsxRuntime.jsx(\"input\", { id: id, ref: inputRef, type: type, value: value.text, autoComplete: \"off\", enterKeyHint: keyHint, autoFocus: autoFocus, placeholder: props.placeholder, spellCheck: spellCheck, tabIndex: tabIndex ? Number(tabIndex) : 0, maxLength: maxLength, className: \"xappw-rich-input__input \".concat(props.className, \"__input\"), onFocus: props.onFocus, onChange: handleChange, onInput: handleInput, onKeyDown: handleKeyDown })) }));\n};\n\nvar SuggestionsGroupHeading = function (props) {\n return jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-group-heading\", children: props.label });\n};\n\nfunction getScrollContainer(node) {\n var walker = node;\n while (walker && !walker.classList.contains(\"xapp-search-result__suggestions\")) {\n walker = walker.parentElement;\n }\n return walker || undefined;\n}\nvar SuggestionsItem = function (props) {\n var data = props.data, current = props.current, ActionsComponent = props.actions, onClick = props.onClick, onHover = props.onHover, onSpanClick = props.onSpanClick;\n var handleClick = react.useCallback(function () {\n onClick(data);\n }, [data, onClick]);\n var handleHover = react.useCallback(function () {\n if (onHover) {\n onHover(data);\n }\n }, [data, onHover]);\n var handleSpanClick = react.useCallback(function (span) {\n if (onSpanClick) {\n return onSpanClick(data, span);\n }\n return undefined;\n }, [onSpanClick, data]);\n var ref = react.useRef(null);\n react.useEffect(function () {\n var node = ref.current;\n if (current && node) {\n var scrollContainer = getScrollContainer(node);\n if (scrollContainer) {\n var scrollBox = scrollContainer.getBoundingClientRect();\n var nodeBox = node.getBoundingClientRect();\n var maxTop = Math.max(scrollBox.top, nodeBox.top);\n var minBottom = Math.min(scrollBox.bottom, nodeBox.bottom);\n var visibleHeight = minBottom - maxTop;\n var actualHeight = nodeBox.height;\n if (visibleHeight < actualHeight * 0.99) {\n node.scrollIntoView({ behavior: \"smooth\" });\n }\n }\n }\n }, [current]);\n return (jsxRuntime.jsxs(\"div\", { ref: ref, className: \"xappw-suggestions-item \".concat(current ? \"xappw-suggestions-item--current\" : \"\"), onClick: handleClick, onMouseEnter: handleHover, children: [jsxRuntime.jsx(RichText, { value: data, className: \"xappw-suggestions-item__texts\", readOnly: true, onSpanClick: handleSpanClick }), ActionsComponent && (jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-item__actions\", children: jsxRuntime.jsx(ActionsComponent, { data: data, current: current }) }))] }));\n};\n\nvar SuggestionsGroup = function (props) {\n var group = props.group, currentIndex = props.currentIndex, itemActions = props.itemActions;\n var heading = group.heading, items = group.items;\n return (jsxRuntime.jsxs(\"div\", { className: \"xappw-suggestions-group\", children: [jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-group__heading\", children: jsxRuntime.jsx(SuggestionsGroupHeading, { label: heading }) }), jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-group__items\", children: items.map(function (item, itemIndex) { return (jsxRuntime.jsx(SuggestionsItem, { data: item, current: currentIndex === itemIndex, actions: itemActions, onClick: props.onItemClick, onHover: props.onItemHover, onSpanClick: props.onSpanClick }, itemIndex)); }) })] }));\n};\n\nfunction getItemsLength(result) {\n return result.reduce(function (prev, cur) { return prev + cur.items.length; }, 0);\n}\n\nvar SuggestionsList = function (props) {\n var suggestions = props.suggestions, itemActions = props.itemActions, className = props.className;\n var length = react.useMemo(function () {\n if (suggestions) {\n return getItemsLength(suggestions);\n }\n return 0;\n }, [suggestions]);\n var currentIndex = length >= 0 ? props.index : NaN;\n var indexWalker = 0;\n return (jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-list \".concat(className || \"\"), children: suggestions === null || suggestions === void 0 ? void 0 : suggestions.map(function (group, index) {\n var res = (jsxRuntime.jsx(SuggestionsGroup, { group: group, currentIndex: currentIndex - indexWalker, itemActions: itemActions, onItemClick: props.onItemClick, onItemHover: props.onItemHover, onSpanClick: props.onSpanClick }, index));\n indexWalker += group.items.length;\n return res;\n }) }));\n};\n\nfunction findItemByIndex(groups, index) {\n if (index >= 0) {\n for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {\n var group = groups_1[_i];\n for (var _a = 0, _b = group.items; _a < _b.length; _a++) {\n var item = _b[_a];\n if (index <= 0) {\n return item;\n }\n index--;\n }\n }\n }\n return undefined;\n}\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nfunction __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar order = [\"FAQ\", \"INTENT\", \"HISTORICAL\"];\nvar ordersMap = order.reduce(function (prev, cur, index) {\n prev[cur] = index;\n return prev;\n}, {});\nfunction compareSuggestionItems(left, right, direction) {\n return direction * (ordersMap[right.type] - ordersMap[left.type]);\n}\nfunction sortSuggestionItems(items, direction) {\n return __spreadArray([], items, true).sort(function (left, right) { return compareSuggestionItems(left, right, direction); });\n}\n\nfunction parseSuggestionsFormat(format) {\n var types = Object.keys(format);\n var type = types[0];\n var item = format[type];\n if (!item) {\n throw new Error();\n }\n return {\n type: type,\n start: item.start,\n end: item.end,\n };\n}\nfunction parseSuggestionsFormats(formats) {\n return formats.map(parseSuggestionsFormat);\n}\nfunction parseSuggestionsResponseItem(item) {\n return {\n text: item.suggestion,\n content: item.answer,\n formats: parseSuggestionsFormats(item.format),\n type: item.type,\n };\n}\nfunction getHeading(type) {\n switch (type) {\n case \"FAQ\":\n return \"FAQs\";\n case \"INTENT\":\n return \"Suggestions\";\n case \"HISTORICAL\":\n return \"Suggestions\";\n default:\n return type;\n }\n}\nfunction parseSuggestionsResponse(response, direction) {\n if (direction === void 0) { direction = 1; }\n if (!response) {\n return undefined;\n }\n var items = sortSuggestionItems(response.suggestions, direction);\n return items.reduce(function (result, current) {\n var mappedItem = parseSuggestionsResponseItem(current);\n if (result.length) {\n var prevGroup = result[result.length - 1];\n if (prevGroup.heading === getHeading(current.type)) {\n prevGroup.items.push(mappedItem);\n return result;\n }\n }\n result.push({\n heading: getHeading(current.type),\n items: [mappedItem],\n });\n return result;\n }, []);\n}\n\n/**\n * Append the provided query params to the URL\n *\n * It will overwrite existing params on the URL if there are conflicts\n * @param url\n * @param params\n */\nfunction addQueryParametersToURL(url, params) {\n var existingParams = new URL(url).searchParams;\n params.forEach(function (value, key) {\n existingParams.append(key, value);\n });\n var newUrl = new URL(url);\n newUrl.search = existingParams.toString();\n return newUrl;\n}\n\nvar defaultOptions = {};\nfunction noop() {\n}\nfunction useJsonFetch(url, options) {\n if (options === void 0) { options = defaultOptions; }\n var _a = react.useState({\n state: \"paused\"\n }), value = _a[0], setValue = _a[1];\n var pause = options.pause;\n react.useEffect(function () {\n if (pause) {\n setValue({\n state: \"paused\"\n });\n return noop;\n }\n var controller = new AbortController();\n var signal = controller.signal;\n var mounted = true;\n (function () {\n return __awaiter(this, void 0, void 0, function () {\n var response, json, e_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 4, , 5]);\n setValue({\n state: \"fetching\"\n });\n return [4 /*yield*/, fetch(url, { signal: signal })];\n case 1:\n response = _a.sent();\n if (!mounted) return [3 /*break*/, 3];\n return [4 /*yield*/, response.json()];\n case 2:\n json = _a.sent();\n if (response.ok) {\n setValue({\n state: \"success\",\n data: json\n });\n }\n else {\n setValue({\n state: \"error\",\n error: json\n });\n }\n _a.label = 3;\n case 3: return [3 /*break*/, 5];\n case 4:\n e_1 = _a.sent();\n if (e_1.name === \"AbortError\") {\n setValue({\n state: \"paused\"\n });\n return [2 /*return*/];\n }\n throw e_1;\n case 5: return [2 /*return*/];\n }\n });\n });\n })();\n return function () {\n mounted = false;\n controller.abort();\n };\n }, [url, pause]);\n return value;\n}\n\nfunction useSuggestionsFetch(options) {\n var baseUrl = options.url, context = options.context, query = options.query;\n var url = react.useMemo(function () {\n if (!baseUrl) {\n return undefined;\n }\n var params = new URLSearchParams();\n params.append(\"size\", \"5\");\n params.append(\"queryText\", query);\n if (context === null || context === void 0 ? void 0 : context.length) {\n params.append(\"activeContexts\", context.join(\",\"));\n }\n return addQueryParametersToURL(baseUrl, params);\n }, [query, context, baseUrl]);\n var response = useJsonFetch(url ? \"\".concat(url.toString()) : \"\", {\n pause: !query || !baseUrl\n });\n return response;\n}\n\n/**\n * Marketing attribution capture, shared by every widget surface.\n *\n * The chat widget historically sent only `currentUrl`, which meant attribution\n * survived only when the visitor opened the chat on the very page the ad landed\n * them on. Anyone who browsed first arrived unattributed. These helpers capture\n * the parameters on first sight and persist them, so a conversation started three\n * pages later still carries the click that paid for it.\n *\n * Only the parameters below are ever read or stored. The query string as a whole\n * is not, because it routinely carries session tokens and PII.\n */\n/** Standard UTM parameters. */\nvar UTM_PARAMETERS = [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\"\n];\n/**\n * Platform click ids.\n *\n * `gbraid` and `wbraid` are what Google substitutes for `gclid` when the click\n * cannot be tied to a cookie — iOS and consent-mode traffic. For home services,\n * where most paid traffic is mobile, omitting them loses attribution on the\n * majority of the spend.\n */\nvar CLICK_ID_PARAMETERS = [\n \"gclid\",\n \"gbraid\",\n \"wbraid\",\n \"msclkid\",\n \"fbclid\"\n];\nvar ATTRIBUTION_PARAMETERS = __spreadArray(__spreadArray([], UTM_PARAMETERS, true), CLICK_ID_PARAMETERS, true);\n/**\n * Params AI surfaces put on the links they send people to: Google AI Overviews\n * (`st_source=ai_overview`), Google's `srsltid` click id, and the generic `ref` / `source`\n * that ChatGPT, Perplexity and others use. Read only by the widget `load` event, never stored and\n * never sent with chat messages.\n */\nvar AI_REFERRAL_PARAMETERS = [\"st_source\", \"srsltid\", \"ref\", \"source\"];\nvar STORAGE_KEY_PREFIX = \"xa_tracking_\";\n/** Matches the 30 day window the form widget already uses. */\nvar DEFAULT_PERSISTENCE_DAYS = 30;\nvar MAX_VALUE_LENGTH$1 = 255;\n/**\n * Values land in a request body and, downstream, in a CRM. Cap the length and\n * reject anything carrying markup or control characters.\n */\nfunction isValidValue$1(value) {\n // eslint-disable-next-line no-control-regex\n return value.length <= MAX_VALUE_LENGTH$1 && !/[<>\"'\\x00-\\x1f]/.test(value);\n}\n/**\n * Reads the attribution parameters present on a URL. Never throws — a URL we\n * cannot parse simply contributes nothing.\n */\nfunction extractAttributionFromUrl(url) {\n var parsed;\n try {\n parsed = new URL(url);\n }\n catch (_a) {\n return {};\n }\n var attribution = {};\n ATTRIBUTION_PARAMETERS.forEach(function (parameter) {\n var value = parsed.searchParams.get(parameter);\n if (value && isValidValue$1(value)) {\n attribution[parameter] = value;\n }\n });\n return attribution;\n}\n/**\n * Persists attribution for later conversations. Existing values are overwritten,\n * so the most recent click wins, matching how the ad platforms attribute.\n */\nfunction storeAttribution(attribution, persistenceDays) {\n if (persistenceDays === void 0) { persistenceDays = DEFAULT_PERSISTENCE_DAYS; }\n var expires = Date.now() + persistenceDays * 24 * 60 * 60 * 1000;\n Object.entries(attribution).forEach(function (_a) {\n var key = _a[0], value = _a[1];\n if (!value) {\n return;\n }\n try {\n localStorage.setItem(\"\".concat(STORAGE_KEY_PREFIX).concat(key), JSON.stringify({ value: value, expires: expires }));\n }\n catch (_b) {\n // Storage can be full or blocked by the browser. Attribution is best\n // effort — never let it break the conversation.\n }\n });\n}\n/** Reads back unexpired stored attribution, cleaning up anything unreadable. */\nfunction getStoredAttribution() {\n var attribution = {};\n ATTRIBUTION_PARAMETERS.forEach(function (parameter) {\n var key = \"\".concat(STORAGE_KEY_PREFIX).concat(parameter);\n var stored;\n try {\n stored = localStorage.getItem(key);\n }\n catch (_a) {\n return;\n }\n if (!stored) {\n return;\n }\n try {\n var parsed = JSON.parse(stored);\n if (parsed && parsed.expires > Date.now() && typeof parsed.value === \"string\") {\n attribution[parameter] = parsed.value;\n }\n else {\n localStorage.removeItem(key);\n }\n }\n catch (_b) {\n localStorage.removeItem(key);\n }\n });\n return attribution;\n}\n/**\n * The attribution to send with a request: whatever is stored, with anything on\n * the current URL layered on top, and the current URL's values persisted for\n * subsequent pages.\n */\nfunction getAttribution(url) {\n if (url === void 0) { url = window.location.href; }\n var fromUrl = extractAttributionFromUrl(url);\n if (Object.keys(fromUrl).length > 0) {\n storeAttribution(fromUrl);\n }\n return __assign(__assign({}, getStoredAttribution()), fromUrl);\n}\n/**\n * Strips the query string from a URL, leaving origin + pathname.\n *\n * Referrers and page URLs routinely carry session tokens, email addresses and other\n * PII in their query strings, and a referrer captured at session start is sent with\n * every subsequent message — so the raw value must never be stored. Attribution is\n * read separately, by allowlist, before this is applied.\n *\n * Returns undefined for an empty or unparseable URL rather than passing it through.\n */\nfunction stripQueryString(url) {\n if (!url) {\n return undefined;\n }\n try {\n var parsed = new URL(url);\n return parsed.origin + parsed.pathname;\n }\n catch (_a) {\n return undefined;\n }\n}\n\n/**\n * Client-side detection of AI browsing agents (Meta Muse, OpenClaw, ChatGPT agent, Gemini,\n * Claude, Perplexity, ...) visiting a customer's site.\n *\n * Pure: it reads only what it is handed, so it can be tested without a browser. The verdict\n * is a hint, not an identity - it decides whether to show agents a pointer to the MCP server\n * and is reported with the widget `load` event so the server side can do the real classification.\n */\n/** User-agent tokens of agents that browse on a person's behalf. Matched case-insensitively. */\nvar AGENT_UA_TOKENS = [\n \"ChatGPT-User\",\n \"Claude-User\",\n \"Perplexity-User\",\n \"GoogleAgent\",\n \"Google-Agent\",\n \"MistralAI-User\",\n \"meta-externalagent\",\n \"HeadlessChrome\",\n];\n/** User-agent tokens of search-indexing crawlers, classic and AI search alike. */\nvar SEARCH_CRAWLER_UA_TOKENS = [\n \"Googlebot\",\n \"Google-InspectionTool\",\n \"Storebot-Google\",\n \"AdsBot-Google\",\n \"Mediapartners-Google\",\n \"bingbot\",\n \"BingPreview\",\n \"Applebot\",\n \"DuckDuckBot\",\n \"YandexBot\",\n \"Baiduspider\",\n \"OAI-SearchBot\",\n \"PerplexityBot\",\n];\n/**\n * Brands a real, branded Chromium browser adds next to \"Chromium\". An agent's headless or\n * stock Chromium carries \"Chromium\" alone - the observed Meta Muse fingerprint.\n */\nvar BRANDED_CHROMIUM = [\"Google Chrome\", \"Microsoft Edge\", \"Opera\", \"Brave\"];\nfunction includesToken(userAgent, token) {\n return userAgent.toLowerCase().indexOf(token.toLowerCase()) >= 0;\n}\nfunction isLinuxDesktop(nav, userAgent) {\n var data = nav.userAgentData;\n if (data === null || data === void 0 ? void 0 : data.mobile) {\n return false;\n }\n if (data === null || data === void 0 ? void 0 : data.platform) {\n return data.platform === \"Linux\";\n }\n return /\\bLinux\\b/.test(userAgent) && !/\\bAndroid\\b/.test(userAgent);\n}\nfunction isChromiumOnly(nav) {\n var _a;\n var names = (((_a = nav.userAgentData) === null || _a === void 0 ? void 0 : _a.brands) || []).map(function (b) { return b.brand; });\n return (names.indexOf(\"Chromium\") >= 0 && !names.some(function (name) { return BRANDED_CHROMIUM.indexOf(name) >= 0; }));\n}\nfunction detectBrowsingAgent(nav) {\n var userAgent = (nav === null || nav === void 0 ? void 0 : nav.userAgent) || \"\";\n var signals = [];\n if (!nav) {\n return { isAgent: false, isSearchCrawler: false, signals: signals };\n }\n if (nav.webdriver === true) {\n signals.push(\"webdriver\");\n }\n AGENT_UA_TOKENS.forEach(function (token) {\n if (includesToken(userAgent, token)) {\n signals.push(\"ua:\".concat(token));\n }\n });\n if (isChromiumOnly(nav) && isLinuxDesktop(nav, userAgent)) {\n signals.push(\"chromium-only-linux\");\n }\n var isSearchCrawler = SEARCH_CRAWLER_UA_TOKENS.some(function (token) {\n return includesToken(userAgent, token);\n });\n return { isAgent: !isSearchCrawler && signals.length > 0, isSearchCrawler: isSearchCrawler, signals: signals };\n}\n\n/**\n * Pointing AI browsing agents at the tenant's public MCP server.\n *\n * agent-server serves a public, unauthenticated, per-tenant homeowner MCP server at\n * `https://agentic.xapp.ai/{appId}/mcp` with a manifest at\n * `/{appId}/.well-known/mcp/manifest.json` and a server card at `/{appId}/mcp/server-card`. An agent that finds it can ask the business\n * questions and request a callback directly instead of scraping and form-filling.\n */\nvar DEFAULT_AGENT_MCP_HOST = \"https://agentic.xapp.ai\";\nvar APP_ID = /^[A-Za-z0-9_-]{1,128}$/;\nvar HOMEOWNER_PATHS = [\"/chat/stream\", \"/chat/close\"];\nfunction endpointsFor(origin, appId) {\n if (!APP_ID.test(appId)) {\n return undefined;\n }\n var base = \"\".concat(origin.replace(/\\/+$/, \"\"), \"/\").concat(appId);\n return {\n appId: appId,\n mcpUrl: \"\".concat(base, \"/mcp\"),\n manifestUrl: \"\".concat(base, \"/.well-known/mcp/manifest.json\"),\n serverCardUrl: \"\".concat(base, \"/mcp/server-card\"),\n };\n}\nfunction httpUrl(value) {\n try {\n var url = new URL(value);\n return url.protocol === \"https:\" || url.protocol === \"http:\" ? url : undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\n/** The first path segment of an http(s) URL, after removing a known endpoint suffix. */\nfunction firstSegment(url, suffixes) {\n var path = url.pathname.replace(/\\/+$/, \"\");\n suffixes.forEach(function (suffix) {\n if (path.endsWith(suffix)) {\n path = path.slice(0, -suffix.length);\n }\n });\n var segments = path.split(\"/\").filter(Boolean);\n return segments.length === 1 ? segments[0] : undefined;\n}\n/**\n * Resolves the tenant's public MCP endpoints. Order: explicit `agentMcpUrl`, then explicit\n * `appId` on the agent host, then the appId inside a homeowner MCP connection's serverUrl.\n * Undefined when none identifies the tenant.\n */\nfunction resolveAgentMcpEndpoints(source) {\n var _a;\n if (!source) {\n return undefined;\n }\n if (source.agentMcpUrl) {\n var url = httpUrl(source.agentMcpUrl);\n var appId = url && firstSegment(url, [\"/mcp\"]);\n return url && appId ? endpointsFor(url.origin, appId) : undefined;\n }\n if (source.appId) {\n var host = source.agentMcpHost && httpUrl(source.agentMcpHost);\n return endpointsFor(host ? host.origin : DEFAULT_AGENT_MCP_HOST, source.appId);\n }\n var connection = source.connection;\n if ((connection === null || connection === void 0 ? void 0 : connection.type) === \"mcp\" &&\n connection.serverUrl &&\n (((_a = connection.mcp) === null || _a === void 0 ? void 0 : _a.mode) || \"homeowner\") === \"homeowner\") {\n var url = httpUrl(connection.serverUrl);\n var appId = url && firstSegment(url, HOMEOWNER_PATHS);\n return url && appId ? endpointsFor(url.origin, appId) : undefined;\n }\n return undefined;\n}\nvar OWN_TAG = \"data-xapp-mcp\";\nfunction upsert(doc, tag, selector, attributes) {\n var existing = doc.head.querySelector(selector);\n if (existing && !existing.hasAttribute(OWN_TAG)) {\n // The site owner advertises their own - theirs wins.\n return;\n }\n var element = existing || doc.createElement(tag);\n element.setAttribute(OWN_TAG, \"\");\n Object.keys(attributes).forEach(function (name) { return element.setAttribute(name, attributes[name]); });\n if (!existing) {\n doc.head.appendChild(element);\n }\n}\n/** Adds (or refreshes) the MCP discovery tags in <head>. Idempotent. */\nfunction injectMcpDiscoveryTags(endpoints, doc) {\n if (doc === void 0) { doc = document; }\n if (!(doc === null || doc === void 0 ? void 0 : doc.head)) {\n return;\n }\n upsert(doc, \"link\", 'link[rel=\"mcp-server\"]', { rel: \"mcp-server\", href: endpoints.mcpUrl });\n upsert(doc, \"link\", 'link[rel=\"mcp-manifest\"]', {\n rel: \"mcp-manifest\",\n href: endpoints.manifestUrl,\n });\n upsert(doc, \"link\", 'link[rel=\"mcp-server-card\"]', {\n rel: \"mcp-server-card\",\n href: endpoints.serverCardUrl,\n });\n upsert(doc, \"meta\", 'meta[name=\"mcp-server\"]', {\n name: \"mcp-server\",\n content: endpoints.mcpUrl,\n });\n}\n/**\n * The note shown to AI assistants. Deliberately informational rather than imperative:\n * agents treat instruction-shaped page text as prompt injection and discard it.\n */\nfunction buildAgentNoticeText(mcpUrl, businessName) {\n var name = (businessName === null || businessName === void 0 ? void 0 : businessName.trim()) || \"this business\";\n return (\"AI assistant? You can talk to \".concat(name, \" directly over MCP: \").concat(mcpUrl, \" \") +\n \"\\u2014 ask questions, check services, and request a callback or quote for your user.\");\n}\nvar AGENT_NOTICE_ID = \"xapp-agent-notice\";\nvar AGENT_NOTICE_HIDDEN_ID = \"xapp-agent-notice-sr\";\n/** Text with the MCP URL as a link, built with DOM APIs so no value is parsed as markup. */\nfunction fillNotice(doc, container, options) {\n var text = buildAgentNoticeText(options.mcpUrl, options.businessName);\n var at = text.indexOf(options.mcpUrl);\n var link = doc.createElement(\"a\");\n link.href = options.mcpUrl;\n link.rel = \"nofollow\";\n link.textContent = options.mcpUrl;\n link.style.color = \"inherit\";\n container.appendChild(doc.createTextNode(text.slice(0, at)));\n container.appendChild(link);\n container.appendChild(doc.createTextNode(text.slice(at + options.mcpUrl.length)));\n}\n/**\n * Renders the agent notice: a small, dismissible note a person can ignore, plus a\n * visually-hidden copy for agents that read the DOM or accessibility tree rather than pixels.\n * Only call this for a detected agent. Renders once.\n */\nfunction renderAgentNotice(options, doc) {\n if (doc === void 0) { doc = document; }\n if (!(doc === null || doc === void 0 ? void 0 : doc.body)) {\n return;\n }\n if (!doc.getElementById(AGENT_NOTICE_HIDDEN_ID)) {\n var hidden = doc.createElement(\"div\");\n hidden.id = AGENT_NOTICE_HIDDEN_ID;\n hidden.style.cssText =\n \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;\" +\n \"clip:rect(0,0,0,0);white-space:nowrap;border:0;\";\n fillNotice(doc, hidden, options);\n doc.body.appendChild(hidden);\n }\n if (doc.getElementById(AGENT_NOTICE_ID)) {\n return;\n }\n var notice = doc.createElement(\"div\");\n notice.id = AGENT_NOTICE_ID;\n notice.setAttribute(\"role\", \"note\");\n notice.style.cssText =\n \"position:fixed;left:8px;bottom:8px;max-width:320px;z-index:2147483000;\" +\n \"padding:6px 24px 6px 8px;border-radius:4px;background:rgba(255,255,255,0.92);\" +\n \"color:#555;font:11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;\" +\n \"box-shadow:0 1px 3px rgba(0,0,0,0.15);word-break:break-word;\";\n fillNotice(doc, notice, options);\n var close = doc.createElement(\"button\");\n close.type = \"button\";\n close.setAttribute(\"aria-label\", \"Dismiss\");\n close.textContent = \"×\";\n close.style.cssText =\n \"position:absolute;top:2px;right:4px;border:0;background:none;color:#888;\" +\n \"font-size:14px;line-height:1;cursor:pointer;padding:2px;\";\n close.addEventListener(\"click\", function () { return notice.remove(); });\n notice.appendChild(close);\n doc.body.appendChild(notice);\n}\n\nfunction isModelContext(value) {\n return !!value && typeof value.registerTool === \"function\";\n}\n/** The page's model context, if this browser has WebMCP. */\nfunction findModelContext(doc, nav) {\n if (doc === void 0) { doc = typeof document !== \"undefined\"\n ? document\n : undefined; }\n if (nav === void 0) { nav = typeof navigator !== \"undefined\"\n ? navigator\n : undefined; }\n if (isModelContext(doc === null || doc === void 0 ? void 0 : doc.modelContext)) {\n return doc.modelContext;\n }\n if (isModelContext(nav === null || nav === void 0 ? void 0 : nav.modelContext)) {\n return nav.modelContext;\n }\n return undefined;\n}\n/**\n * A minimal client for the tenant's homeowner MCP endpoint: one `tools/call` per request, no\n * session. The endpoint is public and the server keeps no state we need, so the MCP\n * initialize handshake would only add a round trip (and a session the next App Runner\n * instance has never heard of).\n */\nvar HomeownerMcpClient = /** @class */ (function () {\n function HomeownerMcpClient(mcpUrl, fetchImpl) {\n this.mcpUrl = mcpUrl;\n this.nextId = 1;\n this.fetchImpl = fetchImpl || (typeof fetch === \"function\" ? fetch : undefined);\n }\n HomeownerMcpClient.prototype.callTool = function (name, args) {\n return __awaiter(this, void 0, void 0, function () {\n var response, body;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (typeof this.fetchImpl !== \"function\") {\n throw new Error(\"fetch is not available\");\n }\n return [4 /*yield*/, this.fetchImpl(this.mcpUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: this.nextId++,\n method: \"tools/call\",\n params: { name: name, arguments: args },\n }),\n })];\n case 1:\n response = _a.sent();\n if (!response.ok) {\n throw new Error(\"MCP endpoint answered \".concat(response.status));\n }\n return [4 /*yield*/, response.json()];\n case 2:\n body = (_a.sent());\n if (body.error) {\n throw new Error(body.error.message || \"MCP error \".concat(body.error.code));\n }\n return [2 /*return*/, toolResultToValue(body.result)];\n }\n });\n });\n };\n return HomeownerMcpClient;\n}());\n/**\n * MCP tool results are text parts; agents want a value. JSON text becomes the object it\n * encodes, prose stays `{ text }`, and a tool-level error becomes `{ ok: false, message }` so\n * the agent can read the validation message and try again rather than seeing a thrown call.\n */\nfunction toolResultToValue(result) {\n var text = ((result === null || result === void 0 ? void 0 : result.content) || [])\n .filter(function (part) { return part.type === \"text\" && typeof part.text === \"string\"; })\n .map(function (part) { return part.text; })\n .join(\"\\n\");\n if (result === null || result === void 0 ? void 0 : result.isError) {\n return { ok: false, message: text };\n }\n try {\n return JSON.parse(text);\n }\n catch (_a) {\n return { text: text };\n }\n}\nvar CALLBACK_FIELDS = [\n \"name\",\n \"phone\",\n \"email\",\n \"address\",\n \"zip\",\n \"serviceType\",\n \"message\",\n \"preferredContactTime\",\n \"urgency\",\n];\nfunction pick(input, keys) {\n var out = {};\n keys.forEach(function (key) {\n if (input && input[key] !== undefined && input[key] !== null && input[key] !== \"\") {\n out[key] = input[key];\n }\n });\n return out;\n}\n/**\n * The tools a visitor's agent gets. Names and descriptions are written for that agent, which\n * is helping a person on the business's site; the server's own tool descriptions address the\n * business owner and would mislead it.\n */\nfunction buildSiteTools(endpoints, caller, options) {\n var _a;\n if (options === void 0) { options = {}; }\n var business = ((_a = options.businessName) === null || _a === void 0 ? void 0 : _a.trim()) || \"this business\";\n var readOnly = {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n };\n return [\n {\n name: \"get_business_info\",\n description: \"What \".concat(business, \" offers: services, service area, hours, and how to reach them. \") +\n \"Call this first when the user asks what the business does or whether it can help.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: false,\n },\n annotations: readOnly,\n execute: function () { return caller.callTool(\"get_business_context\", {}); },\n },\n {\n name: \"search_business_knowledge\",\n description: \"Search \".concat(business, \"'s FAQs and website content to answer a question: services, \") +\n \"pricing, policies, scheduling, warranties, service area.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"The user's question, in their words.\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n annotations: readOnly,\n execute: function (input) { return caller.callTool(\"search_knowledge_base\", pick(input, [\"query\"])); },\n },\n {\n name: \"request_callback\",\n description: \"Ask \".concat(business, \" to contact the user about work they need. Sends the user's name, \") +\n \"phone or email, address and request to the business as a lead. Only call this after \" +\n \"the user has agreed to be contacted. Returns validation errors to fix, or confirmation.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"The user's full name.\" },\n phone: {\n type: \"string\",\n description: \"Phone number, at least 10 digits. Required if no email.\",\n },\n email: { type: \"string\", description: \"Email address. Required if no phone.\" },\n address: {\n type: \"string\",\n description: \"Street address where the work is needed.\",\n },\n zip: {\n type: \"string\",\n description: \"ZIP or postal code where the work is needed.\",\n },\n serviceType: {\n type: \"string\",\n description: \"The kind of work or service needed.\",\n },\n message: {\n type: \"string\",\n description: \"What the user needs, in their words.\",\n },\n preferredContactTime: {\n type: \"string\",\n description: \"When the user would like to be contacted.\",\n },\n urgency: {\n type: \"string\",\n description: 'How urgent: \"urgent\", \"this week\" or \"flexible\".',\n },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n execute: function (input) {\n return caller.callTool(\"collect_contact_info\", __assign(__assign({ appId: endpoints.appId, source: \"webmcp\", channel: \"mcp\" }, (options.channelId ? { channelId: options.channelId } : {})), pick(input, CALLBACK_FIELDS)));\n },\n },\n ];\n}\nvar registered = new WeakSet();\n/**\n * Registers the site tools on the page's model context. Resolves with how many were\n * registered: 0 in a browser without WebMCP, on a second call for the same context, or when\n * registration fails. Never rejects: this runs at widget start and must not take it down.\n */\nfunction registerSiteTools(options) {\n return __awaiter(this, void 0, void 0, function () {\n var context, client, tools, count, _i, tools_1, tool;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 5, , 6]);\n context = findModelContext(options.doc, options.nav);\n if (!context || registered.has(context)) {\n return [2 /*return*/, 0];\n }\n registered.add(context);\n client = new HomeownerMcpClient(options.endpoints.mcpUrl, options.fetchImpl);\n tools = buildSiteTools(options.endpoints, client, options);\n count = 0;\n _i = 0, tools_1 = tools;\n _b.label = 1;\n case 1:\n if (!(_i < tools_1.length)) return [3 /*break*/, 4];\n tool = tools_1[_i];\n return [4 /*yield*/, context.registerTool(tool)];\n case 2:\n _b.sent();\n count++;\n _b.label = 3;\n case 3:\n _i++;\n return [3 /*break*/, 1];\n case 4: return [2 /*return*/, count];\n case 5:\n _b.sent();\n return [2 /*return*/, 0];\n case 6: return [2 /*return*/];\n }\n });\n });\n}\n\nvar NO_VERDICT = { isAgent: false, isSearchCrawler: false, signals: [] };\n/**\n * What a widget does on load for AI browsing agents: detect one, advertise the tenant's MCP\n * server in <head>, and - when the tenant opted in - show a detected agent a short note\n * pointing at it, and register the server's tools as WebMCP site tools for the agent in the\n * visitor's own browser. Never throws.\n */\nfunction startAgentDiscovery(options, nav, doc) {\n if (nav === void 0) { nav = typeof navigator !== \"undefined\"\n ? navigator\n : undefined; }\n if (doc === void 0) { doc = typeof document !== \"undefined\" ? document : undefined; }\n var verdict = NO_VERDICT;\n var endpoints;\n var siteTools;\n try {\n verdict = detectBrowsingAgent(nav);\n }\n catch (_a) {\n // A navigator that throws tells us nothing; carry on as a person.\n }\n try {\n endpoints = resolveAgentMcpEndpoints(options.mcp);\n if (endpoints) {\n injectMcpDiscoveryTags(endpoints);\n if (verdict.isAgent && options.notice === true) {\n renderAgentNotice({\n mcpUrl: endpoints.mcpUrl,\n businessName: options.businessName,\n });\n }\n if (options.siteTools === true) {\n siteTools = registerSiteTools({\n endpoints: endpoints,\n doc: doc,\n nav: nav,\n businessName: options.businessName,\n channelId: options.channelId,\n });\n }\n }\n }\n catch (_b) {\n // Discovery is best effort.\n }\n return { verdict: verdict, endpoints: endpoints, siteTools: siteTools };\n}\n\n/** Distinct errors one page load may report; the server drops anything past its own cap too. */\nvar MAX_CLIENT_ERRORS_PER_PAGE = 5;\nvar MAX_MESSAGE_LENGTH = 1000;\nvar MAX_STACK_LENGTH = 8000;\nfunction clip(value, max) {\n if (typeof value !== \"string\") {\n return undefined;\n }\n var trimmed = value.trim();\n return trimmed ? trimmed.slice(0, max) : undefined;\n}\nfunction describeReason(reason) {\n if (reason === undefined || reason === null) {\n return undefined;\n }\n if (typeof reason === \"string\") {\n return reason;\n }\n try {\n var json = JSON.stringify(reason);\n return json && json !== \"{}\" ? json : String(reason);\n }\n catch (_a) {\n return String(reason);\n }\n}\n/**\n * The report for whatever was thrown: an Error's class, message and stack, a string as the\n * message, anything else described as best it can be. Undefined when there is nothing to say.\n */\nfunction describeClientError(input) {\n var error = input.error;\n var isErrorLike = !!error && typeof error === \"object\" && typeof error.message === \"string\";\n var message = clip(isErrorLike ? error.message : describeReason(input.error), MAX_MESSAGE_LENGTH) || clip(input.message, MAX_MESSAGE_LENGTH);\n if (!message) {\n return undefined;\n }\n var report = {\n message: message,\n name: isErrorLike ? clip(error.name, 120) : undefined,\n stack: isErrorLike ? clip(error.stack, MAX_STACK_LENGTH) : undefined,\n kind: input.kind,\n source: input.source,\n version: clip(input.version, 120),\n url: clip(input.url, 2048),\n line: typeof input.line === \"number\" && input.line > 0 ? input.line : undefined,\n column: typeof input.column === \"number\" && input.column > 0 ? input.column : undefined,\n };\n Object.keys(report).forEach(function (key) {\n if (report[key] === undefined) {\n delete report[key];\n }\n });\n return report;\n}\n/**\n * Whether an error came from one of our bundles: its own file, or any frame of its stack,\n * names one of the given script URLs (query strings ignored on both sides). Nothing matches\n * when the bundle URL is unknown, which is deliberate: the npm build inside someone else's\n * React app must not report that app's errors.\n */\nfunction isFromBundle(location, bundles) {\n var urls = bundles.map(function (b) { return stripQueryString(b); }).filter(function (b) { return !!b; });\n if (!urls.length) {\n return false;\n }\n var file = stripQueryString(location.file);\n if (file && urls.indexOf(file) >= 0) {\n return true;\n }\n var stack = location.stack || \"\";\n return !!stack && urls.some(function (url) { return stack.indexOf(url) >= 0; });\n}\n/**\n * POSTs one `error` event, fire-and-forget with keepalive, in the shape the server's\n * WidgetEvents endpoint reads (`data` is the report). Never throws.\n *\n * @returns true when the request was queued.\n */\nfunction sendWidgetErrorEvent(input) {\n if (!input.key || typeof fetch !== \"function\") {\n return false;\n }\n try {\n var body = {\n key: input.key,\n widgetType: input.widgetType,\n events: [\n {\n eventType: \"error\",\n metadata: __assign({ timestamp: new Date().toISOString() }, input.metadata),\n data: input.report,\n },\n ],\n };\n fetch(input.eventsUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n keepalive: true,\n }).catch(function () { return undefined; });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nvar NOOP_REPORTER = {\n report: function () { return false; },\n uninstall: function () { return undefined; },\n};\nfunction dedupeKey(report) {\n return \"\".concat(report.name || \"\", \"|\").concat(report.message.slice(0, 200));\n}\n/**\n * Installs the page's error reporter for a widget: window `error` and `unhandledrejection`\n * listeners filtered to our bundle, one report per distinct error, at most `maxPerPage` per\n * page load. Idempotent per `source` across every copy of the bundle on the page. Never throws.\n */\nfunction installClientErrorReporter(options) {\n var _a;\n try {\n if (!options.key || typeof window === \"undefined\") {\n return NOOP_REPORTER;\n }\n var w = window;\n var registry_1 = (w.__xappErrorReporters = w.__xappErrorReporters || {});\n var existing = registry_1[options.source];\n if (existing) {\n return existing;\n }\n var bundles_1 = options.bundles || [];\n var maxPerPage_1 = (_a = options.maxPerPage) !== null && _a !== void 0 ? _a : MAX_CLIENT_ERRORS_PER_PAGE;\n var seen_1 = {};\n var sent_1 = 0;\n var metadata_1 = function () {\n try {\n return typeof options.metadata === \"function\" ? options.metadata() : options.metadata || {};\n }\n catch (_a) {\n return {};\n }\n };\n var send_1 = function (report) {\n if (!report || sent_1 >= maxPerPage_1) {\n return false;\n }\n var key = dedupeKey(report);\n if (seen_1[key]) {\n return false;\n }\n seen_1[key] = true;\n var queued = sendWidgetErrorEvent({\n eventsUrl: options.eventsUrl,\n key: options.key,\n widgetType: options.widgetType,\n metadata: metadata_1(),\n report: report,\n });\n if (queued) {\n sent_1++;\n }\n return queued;\n };\n var describe_1 = function (error, kind, location) {\n if (location === void 0) { location = {}; }\n var url;\n try {\n url = window.location.href;\n }\n catch (_a) {\n url = undefined;\n }\n return describeClientError({\n error: error,\n message: location.message,\n kind: kind,\n source: options.source,\n version: options.version,\n url: url,\n line: location.line,\n column: location.column,\n });\n };\n var onError_1 = function (event) {\n var _a;\n try {\n var stack = (_a = event.error) === null || _a === void 0 ? void 0 : _a.stack;\n if (!isFromBundle({ file: event.filename, stack: typeof stack === \"string\" ? stack : undefined }, bundles_1)) {\n return;\n }\n send_1(describe_1(event.error, \"error\", { message: event.message, line: event.lineno, column: event.colno }));\n }\n catch (_b) {\n // Reporting must never break the page.\n }\n };\n var onRejection_1 = function (event) {\n try {\n var reason = event.reason;\n var stack = reason === null || reason === void 0 ? void 0 : reason.stack;\n if (!isFromBundle({ stack: typeof stack === \"string\" ? stack : undefined }, bundles_1)) {\n return;\n }\n send_1(describe_1(reason, \"unhandledrejection\"));\n }\n catch (_a) {\n // Reporting must never break the page.\n }\n };\n window.addEventListener(\"error\", onError_1);\n window.addEventListener(\"unhandledrejection\", onRejection_1);\n var reporter_1 = {\n report: function (error, kind) {\n if (kind === void 0) { kind = \"boundary\"; }\n try {\n return send_1(describe_1(error, kind));\n }\n catch (_a) {\n return false;\n }\n },\n uninstall: function () {\n try {\n window.removeEventListener(\"error\", onError_1);\n window.removeEventListener(\"unhandledrejection\", onRejection_1);\n if (registry_1[options.source] === reporter_1) {\n delete registry_1[options.source];\n }\n }\n catch (_a) {\n // Nothing left to undo.\n }\n },\n };\n registry_1[options.source] = reporter_1;\n return reporter_1;\n }\n catch (_b) {\n return NOOP_REPORTER;\n }\n}\n\n/** Page params whose VALUES the load event may send, each as its own metadata field. */\nvar LOAD_EVENT_PAGE_PARAMETERS = __spreadArray(__spreadArray([], ATTRIBUTION_PARAMETERS, true), AI_REFERRAL_PARAMETERS, true);\nvar DEFAULT_WIDGET_EVENTS_ORIGIN = \"https://api.xapp.ai\";\nvar EVENTS_PATH = \"/cms/widget/events\";\nvar MAX_REFERRER_LENGTH = 500;\nvar MAX_VALUE_LENGTH = 255;\nvar MAX_OTHER_KEYS = 20;\nvar MAX_OTHER_KEYS_LENGTH = 300;\nvar PLAIN_KEY = /^[A-Za-z0-9_.[\\]-]{1,64}$/;\n/**\n * The page global XAPP's own web scraper sets before any page script runs, so the crawler's\n * widget events are reported as `internal` traffic instead of as an AI agent. The crawler cannot\n * mark these events with a request header the way it marks the widget script load: a custom\n * header on the widget's cross-origin fetch would trigger a CORS preflight.\n */\nvar INTERNAL_TRAFFIC_GLOBAL = \"__xappInternal\";\nvar INTERNAL_TRAFFIC_VALUE = /^[a-z][a-z-]{0,31}$/;\n/** The page's internal traffic mark (e.g. `crawler`), or undefined. Never throws. */\nfunction readInternalTrafficMark() {\n try {\n var value = window[INTERNAL_TRAFFIC_GLOBAL];\n return typeof value === \"string\" && INTERNAL_TRAFFIC_VALUE.test(value) ? value : undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\nfunction isValidValue(value) {\n // eslint-disable-next-line no-control-regex\n return value.length <= MAX_VALUE_LENGTH && !/[<>\"'\\x00-\\x1f]/.test(value);\n}\nfunction pageFields(pageUrl) {\n var url;\n try {\n url = new URL(pageUrl);\n }\n catch (_a) {\n return {};\n }\n var fields = { currentUrl: url.origin + url.pathname };\n var otherKeys = [];\n var otherLength = 0;\n url.searchParams.forEach(function (value, name) {\n if (LOAD_EVENT_PAGE_PARAMETERS.indexOf(name) >= 0) {\n if (fields[name] === undefined && value && isValidValue(value)) {\n fields[name] = value;\n }\n return;\n }\n if (!PLAIN_KEY.test(name) || otherKeys.indexOf(name) >= 0) {\n return;\n }\n var added = (otherKeys.length ? 1 : 0) + name.length;\n if (otherKeys.length >= MAX_OTHER_KEYS || otherLength + added > MAX_OTHER_KEYS_LENGTH) {\n return;\n }\n otherKeys.push(name);\n otherLength += added;\n });\n if (otherKeys.length) {\n fields.pageQueryKeys = otherKeys.join(\",\");\n }\n return fields;\n}\n/**\n * The load event's page, browser and agent metadata. Callers add their own identity fields\n * (sessionId, userId, formId). Never throws.\n */\nfunction buildLoadEventMetadata(input) {\n var _a;\n var metadata = pageFields(input.pageUrl);\n var nav = input.nav;\n try {\n if (nav === null || nav === void 0 ? void 0 : nav.userAgent)\n metadata.userAgent = nav.userAgent;\n metadata.webdriver = (nav === null || nav === void 0 ? void 0 : nav.webdriver) === true ? \"1\" : \"0\";\n var brands = (_a = nav === null || nav === void 0 ? void 0 : nav.userAgentData) === null || _a === void 0 ? void 0 : _a.brands;\n if (brands && brands.length) {\n metadata.uaBrands = brands\n .map(function (b) { return \"\".concat(b.brand, \"/\").concat(String(b.version).split(\".\")[0]); })\n .join(\"|\");\n }\n if (nav === null || nav === void 0 ? void 0 : nav.language)\n metadata.language = nav.language;\n }\n catch (_b) {\n // A navigator that throws contributes nothing further.\n }\n var referrer = stripQueryString(input.referrer);\n if (referrer)\n metadata.referrer = referrer.slice(0, MAX_REFERRER_LENGTH);\n metadata.agentVerdict = input.verdict.isAgent ? \"1\" : \"0\";\n if (input.verdict.signals.length) {\n metadata.agentSignals = input.verdict.signals.join(\",\");\n }\n var internal = readInternalTrafficMark();\n if (internal)\n metadata.internal = internal;\n try {\n metadata.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n catch (_c) {\n // Intl unavailable - skip timezone\n }\n if (input.screen) {\n metadata.screenWidth = String(input.screen.width);\n metadata.screenHeight = String(input.screen.height);\n }\n if (input.viewport) {\n metadata.viewportWidth = String(input.viewport.width);\n metadata.viewportHeight = String(input.viewport.height);\n }\n return metadata;\n}\n/**\n * Where the widget events endpoint lives. A stentor-api run URL\n * (`https://api.xapp.ai/apps/{appId}/run`) names it by its origin - the same derivation the\n * form widget's StentorApi uses. Anything else (a chat router websocket, the agent server)\n * is not stentor-api, so the production API is used.\n */\nfunction resolveWidgetEventsUrl(serverUrl) {\n if (serverUrl) {\n try {\n var url = new URL(serverUrl);\n if ((url.protocol === \"https:\" || url.protocol === \"http:\") &&\n /\\/apps\\//.test(url.pathname)) {\n return \"\".concat(url.origin).concat(EVENTS_PATH);\n }\n }\n catch (_a) {\n // fall through\n }\n }\n return \"\".concat(DEFAULT_WIDGET_EVENTS_ORIGIN).concat(EVENTS_PATH);\n}\n/**\n * Claims this page load's `load` event for a widget type. True the first time per page load,\n * across every copy of the bundle on the page; false after that.\n */\nfunction claimPageLoadEvent(widgetType) {\n try {\n var w = window;\n var claimed = (w.__xappLoadEvents = w.__xappLoadEvents || {});\n if (claimed[widgetType]) {\n return false;\n }\n claimed[widgetType] = true;\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n/**\n * POSTs the `load` event, fire-and-forget with keepalive. Never throws.\n *\n * @returns true when the request was queued.\n */\nfunction sendWidgetLoadEvent(input) {\n if (!input.key || typeof fetch !== \"function\") {\n return false;\n }\n try {\n var body = {\n key: input.key,\n widgetType: input.widgetType,\n events: [\n {\n eventType: \"load\",\n metadata: __assign({ timestamp: new Date().toISOString() }, input.metadata),\n data: {},\n },\n ],\n };\n fetch(input.eventsUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n keepalive: true,\n }).catch(function () { return undefined; });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n\n/**\n * Stop the host page scrolling behind an open overlay.\n *\n * `body { overflow: hidden }` is the obvious way to do this, and is what both widgets used\n * to do — but **iOS Safari ignores `overflow: hidden` on the body**, so the customer's page\n * carried on scrolling under the modal. The technique that does work there is to take the\n * body out of flow at a negative offset equal to the current scroll position, then put it\n * back and re-scroll to that exact position on release.\n *\n * Reference counted rather than a plain on/off flag, and the count lives on the `<body>`\n * element rather than in module scope. That is deliberate: the chat widget's `FormModal`\n * loads the **standalone** form widget bundle, which carries its own copy of this module,\n * so the two overlays that can be open at once are not sharing any JS state. With a module\n * counter, the second lock would read the already-pinned scroll position (which the browser\n * reports as 0), the first release would unpin the body while the second overlay was still\n * open, and the second release would then re-apply `position: fixed` and leave the host page\n * stuck. The DOM is the only thing both bundles can agree on.\n */\n/** How many overlays currently hold the lock. Absent means unlocked. */\nvar COUNT_ATTRIBUTE$1 = \"data-xapp-scroll-lock\";\n/** What to put back when the last one lets go, as JSON. */\nvar RESTORE_ATTRIBUTE = \"data-xapp-scroll-lock-restore\";\nvar PINNED_PROPERTIES = [\"position\", \"top\", \"left\", \"right\", \"width\", \"overflow\"];\nfunction readCount$1(body) {\n var count = Number(body.getAttribute(COUNT_ATTRIBUTE$1));\n return Number.isFinite(count) && count > 0 ? count : 0;\n}\nfunction captureRestorePoint(body) {\n var inlineStyles = PINNED_PROPERTIES.reduce(function (styles, property) {\n styles[property] = body.style.getPropertyValue(property);\n return styles;\n }, {});\n return { scrollY: window.scrollY || window.pageYOffset || 0, inlineStyles: inlineStyles };\n}\nfunction takeRestorePoint(body) {\n var serialized = body.getAttribute(RESTORE_ATTRIBUTE);\n body.removeAttribute(RESTORE_ATTRIBUTE);\n try {\n var parsed = JSON.parse(serialized || \"\");\n if (parsed && typeof parsed.scrollY === \"number\" && parsed.inlineStyles) {\n return parsed;\n }\n }\n catch (_a) {\n // Fall through: something else rewrote the attribute. Better to clear our own\n // properties and leave the page usable than to throw and leave it pinned.\n }\n return { scrollY: 0, inlineStyles: {} };\n}\n/**\n * Lock the body and return the release function.\n *\n * The returned function is idempotent — calling it twice is a no-op, which matters because\n * React StrictMode runs an effect's cleanup more than once.\n */\nfunction lockBodyScroll() {\n if (typeof document === \"undefined\" || typeof window === \"undefined\") {\n return function () { return undefined; };\n }\n var body = document.body;\n if (readCount$1(body) === 0) {\n var restorePoint = captureRestorePoint(body);\n body.setAttribute(RESTORE_ATTRIBUTE, JSON.stringify(restorePoint));\n body.style.position = \"fixed\";\n body.style.top = \"-\".concat(restorePoint.scrollY, \"px\");\n body.style.left = \"0\";\n body.style.right = \"0\";\n body.style.width = \"100%\";\n // Redundant next to `position: fixed`, but harmless, and it keeps the behaviour the\n // widgets already had on the browsers that do honour it.\n body.style.overflow = \"hidden\";\n }\n body.setAttribute(COUNT_ATTRIBUTE$1, String(readCount$1(body) + 1));\n var released = false;\n return function releaseBodyScroll() {\n if (released) {\n return;\n }\n released = true;\n var remaining = readCount$1(body) - 1;\n if (remaining > 0) {\n body.setAttribute(COUNT_ATTRIBUTE$1, String(remaining));\n return;\n }\n if (remaining < 0) {\n return;\n }\n body.removeAttribute(COUNT_ATTRIBUTE$1);\n var _a = takeRestorePoint(body), scrollY = _a.scrollY, inlineStyles = _a.inlineStyles;\n PINNED_PROPERTIES.forEach(function (property) {\n if (inlineStyles[property]) {\n body.style.setProperty(property, inlineStyles[property]);\n }\n else {\n body.style.removeProperty(property);\n }\n });\n // An empty `style=\"\"` on the host page's body is untidy and is not what we found.\n if (!body.style.length) {\n body.removeAttribute(\"style\");\n }\n window.scrollTo(0, scrollY);\n };\n}\n/**\n * Lock the body scroll for as long as the calling component is mounted.\n *\n * The cleanup runs on unmount, so a modal that disappears without a clean close — a route\n * change, a parent re-render, an error boundary — still leaves the page scrollable.\n */\nfunction useBodyScrollLock(enabled) {\n if (enabled === void 0) { enabled = true; }\n react.useEffect(function () {\n if (!enabled) {\n return undefined;\n }\n return lockBodyScroll();\n }, [enabled]);\n}\n\n/**\n * Publish the visual viewport's geometry as CSS custom properties, so overlays can size\n * themselves around the soft keyboard.\n *\n * We are an **embedded** widget: the customer owns the host page's `<meta name=\"viewport\">`,\n * so we cannot add `interactive-widget=resizes-content` and let the browser solve this for\n * us. Reading `window.visualViewport` ourselves is the only mechanism we control. (Injecting\n * or mutating the host's viewport meta is not an option — it is not ours, and breaking it\n * breaks the whole page in ways nobody would attribute to us.)\n *\n * Three properties are published on `<html>`:\n *\n * --xapp-viewport-height the visible height, in px\n * --xapp-viewport-offset-top how far the visual viewport has been scrolled down within\n * the layout viewport — nonzero on iOS when the keyboard\n * pushes the page up\n * --xapp-keyboard-inset layout height minus visual height: how much the keyboard\n * (or any other browser UI) is covering\n *\n * `--xapp-keyboard-inset` is the one worth having. It is what a `padding-bottom` wants, and\n * deriving it here means the consuming CSS does not have to do arithmetic across two\n * variables that update at slightly different moments.\n *\n * Reference counted on the DOM, for the same reason `bodyScrollLock` is: chat-widget's\n * `FormModal` loads the **standalone** form-widget bundle, which carries its own copy of\n * this module. Two independent copies can be live at once, and a module-scope counter would\n * not see across them. Without counting, closing the form modal while the chat panel is\n * still open (with the keyboard still up) would clear the properties out from under the\n * panel and snap it back to its fallback height mid-interaction.\n */\nvar HEIGHT_PROPERTY = \"--xapp-viewport-height\";\nvar OFFSET_TOP_PROPERTY = \"--xapp-viewport-offset-top\";\nvar KEYBOARD_INSET_PROPERTY = \"--xapp-keyboard-inset\";\n/** How many subscribers currently want these properties maintained. */\nvar COUNT_ATTRIBUTE = \"data-xapp-viewport-subscribers\";\n/**\n * Below this, a shrunken viewport is treated as browser chrome rather than a keyboard.\n * Address bars collapse and expand by ~60-90px during normal scrolling, and reacting to\n * that would make the layout twitch while the user is only reading.\n */\nvar KEYBOARD_THRESHOLD_PX = 120;\nfunction readCount(root) {\n var count = Number(root.getAttribute(COUNT_ATTRIBUTE));\n return Number.isFinite(count) && count > 0 ? count : 0;\n}\n/**\n * Write the current geometry to `<html>`.\n *\n * Deliberately does nothing when `visualViewport` is unavailable: the consuming CSS falls\n * back to `100dvh`, which is correct-ish and certainly better than a zero height. Publishing\n * `0px` would collapse the widget entirely — a worse failure than the one being fixed.\n */\nfunction publish(root) {\n var viewport = typeof window === \"undefined\" ? undefined : window.visualViewport;\n if (!viewport) {\n return;\n }\n var height = viewport.height, offsetTop = viewport.offsetTop;\n if (!(height > 0)) {\n // Mid-transition, or a browser reporting nonsense. Keep the last good values.\n return;\n }\n // window.innerHeight is the LAYOUT viewport, which the keyboard does not shrink on iOS.\n // The difference between the two is the occluded strip.\n var layoutHeight = window.innerHeight || height;\n var rawInset = Math.max(0, layoutHeight - height);\n var inset = rawInset >= KEYBOARD_THRESHOLD_PX ? rawInset : 0;\n root.style.setProperty(HEIGHT_PROPERTY, \"\".concat(Math.round(height), \"px\"));\n root.style.setProperty(OFFSET_TOP_PROPERTY, \"\".concat(Math.round(offsetTop), \"px\"));\n root.style.setProperty(KEYBOARD_INSET_PROPERTY, \"\".concat(Math.round(inset), \"px\"));\n}\nfunction clear(root) {\n root.style.removeProperty(HEIGHT_PROPERTY);\n root.style.removeProperty(OFFSET_TOP_PROPERTY);\n root.style.removeProperty(KEYBOARD_INSET_PROPERTY);\n}\n/**\n * Start publishing viewport geometry. Returns a release function.\n *\n * Imperative twin of {@link useVisualViewportProperties}, for callers outside React.\n */\nfunction trackVisualViewport() {\n if (typeof document === \"undefined\") {\n return function () { return undefined; };\n }\n var root = document.documentElement;\n root.setAttribute(COUNT_ATTRIBUTE, String(readCount(root) + 1));\n publish(root);\n var viewport = typeof window === \"undefined\" ? undefined : window.visualViewport;\n var frame;\n var onChange = function () {\n // These fire many times per second through the keyboard animation. Coalescing to one\n // write per frame keeps us off the layout-thrash path.\n if (frame !== undefined) {\n return;\n }\n frame = window.requestAnimationFrame(function () {\n frame = undefined;\n publish(root);\n });\n };\n // `scroll` matters as much as `resize`: on iOS the keyboard scrolls the visual viewport\n // within the layout viewport, and offsetTop only changes on that event.\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"resize\", onChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"scroll\", onChange);\n var released = false;\n return function () {\n if (released) {\n return;\n }\n released = true;\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"resize\", onChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"scroll\", onChange);\n if (frame !== undefined) {\n window.cancelAnimationFrame(frame);\n frame = undefined;\n }\n var remaining = readCount(root) - 1;\n if (remaining > 0) {\n root.setAttribute(COUNT_ATTRIBUTE, String(remaining));\n return;\n }\n root.removeAttribute(COUNT_ATTRIBUTE);\n clear(root);\n };\n}\n/**\n * Publish viewport geometry for as long as this component is mounted.\n *\n * @param enabled pass `false` to opt out — e.g. above the mobile breakpoint, where there is\n * no soft keyboard to work around and the desktop sizing should stand.\n */\nfunction useVisualViewportProperties(enabled) {\n if (enabled === void 0) { enabled = true; }\n react.useEffect(function () {\n if (!enabled) {\n return undefined;\n }\n return trackVisualViewport();\n }, [enabled]);\n}\n/** Read the published inset, or 0 if nothing has published one. */\nfunction readInset() {\n var value = getComputedStyle(document.documentElement).getPropertyValue(KEYBOARD_INSET_PROPERTY);\n var inset = parseFloat(value);\n return Number.isFinite(inset) ? inset : 0;\n}\nfunction scrollIntoViewIfPossible(element) {\n if (element && \"scrollIntoView\" in element) {\n // block: \"nearest\" scrolls the minimum needed, so a field already in view does not\n // jump. Anything more aggressive fights the browser's own attempt and overshoots.\n element.scrollIntoView({ block: \"nearest\", behavior: \"smooth\" });\n }\n}\n/**\n * Scroll whatever the user has focused back into view when the keyboard covers it.\n *\n * Browsers mostly do this themselves, but not reliably inside a `position: fixed` overlay —\n * which is exactly what both widgets are. The failure looks like tapping the last field on a\n * step and having it disappear behind the keyboard.\n *\n * **The ordering is the whole problem.** On a device the sequence is: focus lands, *then*\n * the keyboard opens, *then* the viewport events fire. So reading the inset inside the\n * `focusin` handler sees `0` and does nothing — on precisely the case this exists for, the\n * first tap into a field near the bottom of a step. It has to react to the inset becoming\n * nonzero and scroll whatever is focused at that moment.\n *\n * Both directions are covered: focusing while the keyboard is already up (tabbing between\n * fields) scrolls immediately, and a keyboard that opens after focus scrolls on the\n * transition. Nothing happens when the keyboard closes, or for a mouse user on desktop where\n * the inset never leaves `0`.\n */\nfunction useScrollFocusedIntoView(enabled) {\n if (enabled === void 0) { enabled = true; }\n react.useEffect(function () {\n if (!enabled || typeof document === \"undefined\") {\n return undefined;\n }\n // Seeded from the current value so a hook mounted while the keyboard is already up\n // does not read that as a fresh transition and scroll unbidden.\n var lastInset = readInset();\n var onFocusIn = function (event) {\n if (readInset() > 0) {\n scrollIntoViewIfPossible(event.target);\n }\n };\n var onViewportChange = function () {\n // One frame late: the property is published from a rAF callback, so reading it\n // synchronously here would see the previous value. This assumes the publishing\n // hook mounted first, which it does at both call sites - and even if it did not,\n // a browser fires resize AND scroll for a keyboard, so the second event catches\n // what the first missed.\n window.requestAnimationFrame(function () {\n var inset = readInset();\n var opened = lastInset <= 0 && inset > 0;\n lastInset = inset;\n if (opened) {\n scrollIntoViewIfPossible(document.activeElement);\n }\n });\n };\n var viewport = typeof window === \"undefined\" ? undefined : window.visualViewport;\n document.addEventListener(\"focusin\", onFocusIn);\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"resize\", onViewportChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"scroll\", onViewportChange);\n return function () {\n document.removeEventListener(\"focusin\", onFocusIn);\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"resize\", onViewportChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"scroll\", onViewportChange);\n };\n }, [enabled]);\n}\n\n/**\n * A fake soft keyboard, for testing keyboard handling on a machine that has none.\n *\n * **This is a development harness, not a verifier.** It substitutes a stand-in for\n * `window.visualViewport` and fires the events a real browser would, so our own code cannot\n * tell the difference. What it proves is that the hook subscribes, does the arithmetic, and\n * that the consuming CSS responds. What it cannot prove is that a real iOS or Android\n * keyboard produces these events at all — iOS scrolls the visual viewport within the layout\n * viewport, Android may resize the layout viewport itself depending on the host page's\n * viewport meta, and as an embedded widget we do not control that meta. A mock we wrote can\n * only ever confirm our own assumptions.\n *\n * So: use this to iterate on a desktop, and verify on a real device with it switched off,\n * where the same instrumentation reads the numbers the device actually reports.\n *\n * Exported from the package because the Storybook stories that use it live in two different\n * packages, and duplicating a fake this fiddly is how the two copies drift apart.\n */\n/**\n * Roughly what the common keyboards occupy.\n *\n * The landscape entry is not optional garnish: a portrait keyboard is ~336px, and a\n * landscape phone viewport is only ~340px tall, so simulating a portrait keyboard sideways\n * leaves 4px of usable space and every layout assertion fails for a reason that has nothing\n * to do with the layout. Landscape keyboards are genuinely shorter.\n */\nvar KEYBOARD_PRESETS = {\n \"iOS (iPhone 14)\": 336,\n \"Android (Pixel 7)\": 312,\n \"iOS with autocomplete bar\": 380,\n \"Compact / numeric\": 260,\n \"Landscape phone\": 200,\n};\n/**\n * Stands in for VisualViewport. Only the members our code reads are real; the rest satisfy\n * the structural type so this can be assigned over `window.visualViewport`.\n */\nvar SimulatedViewport = /** @class */ (function () {\n function SimulatedViewport(height, width) {\n this.offsetTop = 0;\n this.offsetLeft = 0;\n this.pageTop = 0;\n this.pageLeft = 0;\n this.scale = 1;\n this.onresize = null;\n this.onscroll = null;\n this.listeners = {};\n this.height = height;\n this.width = width;\n }\n SimulatedViewport.prototype.addEventListener = function (type, listener) {\n var _a;\n ((_a = this.listeners)[type] || (_a[type] = new Set())).add(listener);\n };\n SimulatedViewport.prototype.removeEventListener = function (type, listener) {\n var _a;\n (_a = this.listeners[type]) === null || _a === void 0 ? void 0 : _a.delete(listener);\n };\n SimulatedViewport.prototype.dispatchEvent = function (event) {\n var _a;\n (_a = this.listeners[event.type]) === null || _a === void 0 ? void 0 : _a.forEach(function (listener) { return listener(event); });\n return true;\n };\n SimulatedViewport.prototype.fire = function () {\n // A real browser fires both, and offsetTop only lands on the scroll one.\n this.dispatchEvent(new Event(\"resize\"));\n this.dispatchEvent(new Event(\"scroll\"));\n };\n return SimulatedViewport;\n}());\n/**\n * Install the simulator, replacing `window.visualViewport` until `destroy()`.\n *\n * The real property is a readonly accessor on `window`, so this redefines it and puts the\n * original descriptor back on teardown. Confined to Storybook — nothing ships with this.\n */\nfunction installKeyboardSimulator() {\n var original = Object.getOwnPropertyDescriptor(window, \"visualViewport\");\n var layoutHeight = window.innerHeight;\n var simulated = new SimulatedViewport(layoutHeight, window.innerWidth);\n Object.defineProperty(window, \"visualViewport\", {\n value: simulated,\n writable: true,\n configurable: true,\n });\n return {\n open: function (height) {\n simulated.height = Math.max(0, layoutHeight - height);\n // iOS pushes the visual viewport down within the layout viewport as well as\n // shrinking it. Mirroring that is what makes offsetTop worth reading.\n simulated.offsetTop = height / 2;\n simulated.fire();\n },\n close: function () {\n simulated.height = layoutHeight;\n simulated.offsetTop = 0;\n simulated.fire();\n },\n destroy: function () {\n if (original) {\n Object.defineProperty(window, \"visualViewport\", original);\n }\n else {\n delete window.visualViewport;\n }\n },\n };\n}\n\n/**\n * Wraps a widget story with soft-keyboard instrumentation.\n *\n * Two modes, and the second is the one that matters:\n *\n * 1. **Simulate on** (desktop): substitutes a fake `visualViewport`, so you can raise and\n * lower a keyboard of a chosen height and watch the layout respond. Good for iterating.\n * It proves our code reacts correctly to the events; it cannot prove a real keyboard\n * produces them.\n *\n * 2. **Simulate off** (a real phone): leaves the browser alone. Tap a field, get the real\n * keyboard, and the readout shows what the device actually reports — which is the number\n * we have never had. If the fix misbehaves, this is what says why.\n *\n * Defaults to off so that opening the story on a phone does the right thing without anyone\n * having to remember to switch it.\n */\nvar READOUT_KEYS = [\n [\"--xapp-viewport-height\", \"viewport height\"],\n [\"--xapp-keyboard-inset\", \"keyboard inset\"],\n [\"--xapp-viewport-offset-top\", \"offset top\"],\n];\nfunction readMetrics() {\n var viewport = window.visualViewport;\n var style = getComputedStyle(document.documentElement);\n var published = {};\n READOUT_KEYS.forEach(function (_a) {\n var property = _a[0];\n published[property] = style.getPropertyValue(property).trim() || \"(unset)\";\n });\n return {\n visualHeight: viewport ? Math.round(viewport.height) : undefined,\n layoutHeight: window.innerHeight,\n offsetTop: viewport ? Math.round(viewport.offsetTop) : undefined,\n scale: viewport === null || viewport === void 0 ? void 0 : viewport.scale,\n published: published,\n };\n}\nvar KeyboardTestRig = function (_a) {\n var _b;\n var children = _a.children;\n var _c = react.useState(false), simulate = _c[0], setSimulate = _c[1];\n var _d = react.useState(KEYBOARD_PRESETS[\"iOS (iPhone 14)\"]), height = _d[0], setHeight = _d[1];\n var _e = react.useState(false), open = _e[0], setOpen = _e[1];\n var _f = react.useState(function () { return readMetrics(); }), metrics = _f[0], setMetrics = _f[1];\n var _g = react.useState(), simulator = _g[0], setSimulator = _g[1];\n /**\n * Whether the simulator is actually installed, as opposed to merely requested.\n *\n * The widget subscribes to whatever `window.visualViewport` was when it mounted, so\n * swapping the property under a mounted widget changes nothing — it is still listening\n * to the old object. The children are therefore unmounted while the swap happens and\n * remounted afterwards, against whichever viewport is now current. Found the hard way:\n * without this the toolbar worked, the readout updated, and the layout never moved.\n */\n var _h = react.useState(false), installed = _h[0], setInstalled = _h[1];\n // Poll rather than subscribe: the point is to observe what the page is doing, including\n // any update path we forgot to wire, so this deliberately does not depend on our own\n // event handling being correct.\n react.useEffect(function () {\n var id = window.setInterval(function () { return setMetrics(readMetrics()); }, 100);\n return function () { return window.clearInterval(id); };\n }, []);\n react.useEffect(function () {\n if (!simulate) {\n return undefined;\n }\n var active = installKeyboardSimulator();\n setSimulator(active);\n setInstalled(true);\n return function () {\n active.close();\n active.destroy();\n setSimulator(undefined);\n setInstalled(false);\n setOpen(false);\n };\n }, [simulate]);\n react.useEffect(function () {\n if (!simulator) {\n return;\n }\n if (open) {\n simulator.open(height);\n }\n else {\n simulator.close();\n }\n }, [simulator, open, height]);\n var hasRealViewport = typeof window !== \"undefined\" && !!window.visualViewport;\n return (jsxRuntime.jsxs(\"div\", { style: { font: \"13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace\" }, children: [jsxRuntime.jsxs(\"div\", { style: {\n position: \"fixed\",\n top: 0,\n left: 0,\n right: 0,\n zIndex: 2147483647,\n background: \"#14181a\",\n color: \"#edf1f1\",\n padding: \"8px 10px\",\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: \"10px\",\n alignItems: \"center\",\n }, children: [jsxRuntime.jsxs(\"label\", { style: { display: \"flex\", gap: 6, alignItems: \"center\" }, children: [jsxRuntime.jsx(\"input\", { type: \"checkbox\", checked: simulate, onChange: function (event) { return setSimulate(event.target.checked); } }), \"simulate keyboard\"] }), jsxRuntime.jsxs(\"button\", { type: \"button\", disabled: !simulate, onClick: function () { return setOpen(function (value) { return !value; }); }, \n // Do not take focus. On a device the keyboard opens *because* a field was\n // focused, and the field keeps focus throughout. A toolbar button that\n // steals it makes the interesting case - does the focused field survive\n // the keyboard arriving? - impossible to reproduce here.\n onMouseDown: function (event) { return event.preventDefault(); }, style: { padding: \"4px 10px\" }, children: [open ? \"hide\" : \"show\", \" keyboard\"] }), jsxRuntime.jsx(\"select\", { disabled: !simulate, value: height, onChange: function (event) { return setHeight(Number(event.target.value)); }, children: Object.entries(KEYBOARD_PRESETS).map(function (_a) {\n var label = _a[0], value = _a[1];\n return (jsxRuntime.jsxs(\"option\", { value: value, children: [label, \" \\u2014 \", value, \"px\"] }, label));\n }) }), jsxRuntime.jsxs(\"span\", { style: { opacity: 0.75 }, children: [\"visual \", (_b = metrics.visualHeight) !== null && _b !== void 0 ? _b : \"n/a\", \" / layout \", metrics.layoutHeight, metrics.offsetTop !== undefined && \" / offsetTop \".concat(metrics.offsetTop), metrics.scale !== undefined && \" / scale \".concat(metrics.scale.toFixed(2))] }), READOUT_KEYS.map(function (_a) {\n var property = _a[0], label = _a[1];\n return (jsxRuntime.jsxs(\"span\", { style: { opacity: 0.75 }, children: [label, \": \", jsxRuntime.jsx(\"strong\", { children: metrics.published[property] })] }, property));\n }), !hasRealViewport && !simulate && (jsxRuntime.jsx(\"span\", { style: { color: \"#d9a45f\" }, children: \"this browser has no visualViewport \\u2014 widgets fall back to 100dvh\" }))] }), installed === simulate && (jsxRuntime.jsx(\"div\", { children: children }, simulate ? \"simulated\" : \"real\")), simulate && open && (jsxRuntime.jsxs(\"div\", { style: {\n position: \"fixed\",\n bottom: 0,\n left: 0,\n right: 0,\n height: height,\n zIndex: 2147483646,\n background: \"repeating-linear-gradient(45deg, #2b3336 0 12px, #222a2b 12px 24px)\",\n color: \"#7f8c8e\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n borderTop: \"2px solid #58c4ac\",\n }, children: [\"simulated keyboard \\u2014 \", height, \"px\"] }))] }));\n};\n\n/**\n * Test-lead flag, shared by every widget surface.\n *\n * Studio opens a business's booking page with `?xa_test=1` so the owner can send\n * themselves a test lead. The booking page records that in sessionStorage — never\n * localStorage, so a later real visit is never tagged — and every submission from\n * that page view carries `xaTest: true`. stentor-api keeps such leads out of stats,\n * billing counts, CRM pushes and Google conversions.\n */\n/** The booking-page query parameter Studio sets. */\nvar TEST_LEAD_PARAMETER = \"xa_test\";\n/** The sessionStorage key the booking page writes the flag to. */\nvar TEST_LEAD_STORAGE_KEY = \"xa_test\";\n/** The attribute sent with a lead submission. */\nvar TEST_LEAD_ATTRIBUTE = \"xaTest\";\n/** True when the current browser session is a test-lead page view. */\nfunction isTestLeadSession() {\n try {\n return sessionStorage.getItem(TEST_LEAD_STORAGE_KEY) === \"1\";\n }\n catch (_a) {\n // Storage can be blocked by the browser; treat that as a real visit.\n return false;\n }\n}\n/**\n * Tags the attributes as a test lead when the session flag is set. A test must\n * never be counted as Google traffic, so any `rwg_token` is dropped as well.\n */\nfunction addTestLeadAttribute(attributes) {\n if (isTestLeadSession()) {\n attributes[TEST_LEAD_ATTRIBUTE] = true;\n delete attributes[\"rwg_token\"];\n }\n return attributes;\n}\n\n/**\n * Quicker configurable uuid\n *\n * @export\n * @returns {string}\n */\nfunction uuid() {\n var d = new Date().getTime();\n var newUuid = \"xxxxxxxx-xxxx-65xx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, function (c) {\n /* tslint:disable:no-magic-numbers */\n /* tslint:disable:no-bitwise */\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n /* tslint:enable:no-magic-numbers */\n /* tslint:disable:no-bitwise */\n });\n return newUuid;\n}\n\n/**\n * Who is on the page, shared by every XAPP widget on it.\n *\n * - `visitorId`: one per browser and site, kept in localStorage. The form widget's existing user\n * id is adopted when there is one, so a returning visitor keeps the id their leads carry.\n * - `visitId`: one per visit. A visit ends after VISIT_IDLE_MS without a widget event, the same\n * rule as a Google Analytics session, so the chat and form widgets on one page - and the pages a\n * visitor clicks through - share it.\n *\n * Both are kept in the host page's localStorage, which every widget bundle on the page reads, so\n * a chat and a form loaded as separate scripts agree. When storage throws (private mode, a\n * sandboxed frame, a storage policy) a page global stands in, so the page at least agrees with\n * itself. Never throws.\n */\nvar VISITOR_ID_STORAGE_KEY = \"__xapp_visitor_id\";\nvar VISIT_STORAGE_KEY = \"__xapp_visit\";\n/** The form widget's user id key before the shared visitor id existed. */\nvar LEGACY_FORM_USER_ID_KEY = \"__xapp_form_user_id\";\n/** A visit ends after this long without a widget event. */\nvar VISIT_IDLE_MS = 30 * 60 * 1000;\nvar ID = /^[A-Za-z0-9_-]{8,64}$/;\nfunction fallback() {\n try {\n var w = window;\n return (w.__xappVisitIdentity = w.__xappVisitIdentity || {});\n }\n catch (_a) {\n return {};\n }\n}\nfunction read(key) {\n try {\n return localStorage.getItem(key) || undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\n/** True when it was stored. */\nfunction write(key, value) {\n try {\n localStorage.setItem(key, value);\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction asId(value) {\n return value && ID.test(value) ? value : undefined;\n}\n/** This browser's visitor id on this site, minted on first use. */\nfunction visitorId() {\n var stored = asId(read(VISITOR_ID_STORAGE_KEY));\n if (stored) {\n return stored;\n }\n var page = fallback();\n var id = page.visitorId || asId(read(LEGACY_FORM_USER_ID_KEY)) || uuid();\n if (!write(VISITOR_ID_STORAGE_KEY, id)) {\n page.visitorId = id;\n }\n return id;\n}\nfunction parseVisit(raw) {\n if (!raw) {\n return undefined;\n }\n try {\n var visit = JSON.parse(raw);\n return visit && asId(visit.id) && typeof visit.at === \"number\"\n ? visit\n : undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\n/**\n * The visitor and their current visit, extending the visit to `now`. Call it for each event the\n * widget sends: the call is what keeps the visit alive.\n */\nfunction visitIdentity(now) {\n if (now === void 0) { now = Date.now(); }\n var page = fallback();\n var current = parseVisit(read(VISIT_STORAGE_KEY)) || page.visit;\n var active = current && current.at <= now && now - current.at <= VISIT_IDLE_MS;\n var visit = { id: active && current ? current.id : uuid(), at: now };\n if (!write(VISIT_STORAGE_KEY, JSON.stringify(visit))) {\n page.visit = visit;\n }\n return { visitorId: visitorId(), visitId: visit.id };\n}\n\nexports.AGENT_NOTICE_HIDDEN_ID = AGENT_NOTICE_HIDDEN_ID;\nexports.AGENT_NOTICE_ID = AGENT_NOTICE_ID;\nexports.AGENT_UA_TOKENS = AGENT_UA_TOKENS;\nexports.AI_REFERRAL_PARAMETERS = AI_REFERRAL_PARAMETERS;\nexports.ATTRIBUTION_PARAMETERS = ATTRIBUTION_PARAMETERS;\nexports.CLICK_ID_PARAMETERS = CLICK_ID_PARAMETERS;\nexports.DEFAULT_AGENT_MCP_HOST = DEFAULT_AGENT_MCP_HOST;\nexports.DEFAULT_WIDGET_EVENTS_ORIGIN = DEFAULT_WIDGET_EVENTS_ORIGIN;\nexports.HomeownerMcpClient = HomeownerMcpClient;\nexports.INTERNAL_TRAFFIC_GLOBAL = INTERNAL_TRAFFIC_GLOBAL;\nexports.IconButton = IconButton;\nexports.KEYBOARD_PRESETS = KEYBOARD_PRESETS;\nexports.KeyboardTestRig = KeyboardTestRig;\nexports.LEGACY_FORM_USER_ID_KEY = LEGACY_FORM_USER_ID_KEY;\nexports.LOAD_EVENT_PAGE_PARAMETERS = LOAD_EVENT_PAGE_PARAMETERS;\nexports.MAX_CLIENT_ERRORS_PER_PAGE = MAX_CLIENT_ERRORS_PER_PAGE;\nexports.MessageBubble = MessageBubble;\nexports.RichInput = RichInput;\nexports.RichText = RichText;\nexports.SEARCH_CRAWLER_UA_TOKENS = SEARCH_CRAWLER_UA_TOKENS;\nexports.SuggestionsGroup = SuggestionsGroup;\nexports.SuggestionsGroupHeading = SuggestionsGroupHeading;\nexports.SuggestionsItem = SuggestionsItem;\nexports.SuggestionsList = SuggestionsList;\nexports.TEST_LEAD_ATTRIBUTE = TEST_LEAD_ATTRIBUTE;\nexports.TEST_LEAD_PARAMETER = TEST_LEAD_PARAMETER;\nexports.TEST_LEAD_STORAGE_KEY = TEST_LEAD_STORAGE_KEY;\nexports.UTM_PARAMETERS = UTM_PARAMETERS;\nexports.VISITOR_ID_STORAGE_KEY = VISITOR_ID_STORAGE_KEY;\nexports.VISIT_IDLE_MS = VISIT_IDLE_MS;\nexports.VISIT_STORAGE_KEY = VISIT_STORAGE_KEY;\nexports.addQueryParametersToURL = addQueryParametersToURL;\nexports.addTestLeadAttribute = addTestLeadAttribute;\nexports.buildAgentNoticeText = buildAgentNoticeText;\nexports.buildLoadEventMetadata = buildLoadEventMetadata;\nexports.buildSiteTools = buildSiteTools;\nexports.claimPageLoadEvent = claimPageLoadEvent;\nexports.describeClientError = describeClientError;\nexports.detectBrowsingAgent = detectBrowsingAgent;\nexports.extendFormat = extendFormat;\nexports.extractAttributionFromUrl = extractAttributionFromUrl;\nexports.findItemByIndex = findItemByIndex;\nexports.findModelContext = findModelContext;\nexports.getAttribution = getAttribution;\nexports.getItemsLength = getItemsLength;\nexports.getStoredAttribution = getStoredAttribution;\nexports.injectMcpDiscoveryTags = injectMcpDiscoveryTags;\nexports.installClientErrorReporter = installClientErrorReporter;\nexports.installKeyboardSimulator = installKeyboardSimulator;\nexports.isFromBundle = isFromBundle;\nexports.isTestLeadSession = isTestLeadSession;\nexports.lockBodyScroll = lockBodyScroll;\nexports.parseSuggestionsResponse = parseSuggestionsResponse;\nexports.readInternalTrafficMark = readInternalTrafficMark;\nexports.registerSiteTools = registerSiteTools;\nexports.renderAgentNotice = renderAgentNotice;\nexports.resolveAgentMcpEndpoints = resolveAgentMcpEndpoints;\nexports.resolveWidgetEventsUrl = resolveWidgetEventsUrl;\nexports.sendWidgetErrorEvent = sendWidgetErrorEvent;\nexports.sendWidgetLoadEvent = sendWidgetLoadEvent;\nexports.sortSuggestionItems = sortSuggestionItems;\nexports.startAgentDiscovery = startAgentDiscovery;\nexports.storeAttribution = storeAttribution;\nexports.stripQueryString = stripQueryString;\nexports.trackVisualViewport = trackVisualViewport;\nexports.useBodyScrollLock = useBodyScrollLock;\nexports.useJsonFetch = useJsonFetch;\nexports.useScrollFocusedIntoView = useScrollFocusedIntoView;\nexports.useSuggestionsFetch = useSuggestionsFetch;\nexports.useVisualViewportProperties = useVisualViewportProperties;\nexports.uuid = uuid;\nexports.visitIdentity = visitIdentity;\nexports.visitorId = visitorId;\n//# sourceMappingURL=index.js.map\n","import {\n CLICK_ID_PARAMETERS as CORE_CLICK_ID_PARAMETERS,\n UTM_PARAMETERS as CORE_UTM_PARAMETERS\n} from \"@xapp/chat-widget-core\";\n\n/**\n * Utility functions for handling UTM parameters and tracking data\n * Following industry standards for marketing attribution tracking\n */\n\nexport interface TrackingParameters {\n // Standard UTM parameters (Google Analytics standard)\n utm_source?: string; // Traffic source (e.g., \"google\", \"facebook\", \"newsletter\")\n utm_medium?: string; // Marketing medium (e.g., \"cpc\", \"email\", \"social\")\n utm_campaign?: string; // Campaign name (e.g., \"spring_sale\", \"product_launch\")\n utm_term?: string; // Paid keywords (for paid search)\n utm_content?: string; // Ad content (for A/B testing different ads)\n\n // Platform-specific click IDs\n gclid?: string; // Google Click ID (Google Ads auto-tagging)\n gbraid?: string; // Google Click ID for web-to-app, iOS (no gclid available)\n wbraid?: string; // Google Click ID for app-to-web, iOS (no gclid available)\n fbclid?: string; // Facebook Click ID\n msclkid?: string; // Microsoft Click ID (Bing Ads)\n\n // Custom tracking parameters with configurable prefix\n [key: `track_${string}`]: string;\n}\n\n/**\n * Configuration for tracking parameter extraction\n */\nexport interface TrackingConfig {\n /**\n * Whether to extract UTM parameters from the URL\n * @default true\n */\n extractUtmParameters?: boolean;\n\n /**\n * Whether to extract platform-specific click IDs\n * @default true\n */\n extractClickIds?: boolean;\n\n /**\n * Custom parameter prefix to look for (in addition to utm_)\n * @default \"track_\"\n */\n customParameterPrefix?: string;\n\n /**\n * Whether to persist parameters to localStorage\n * @default true\n */\n persistToLocalStorage?: boolean;\n\n /**\n * How long to persist parameters in localStorage (in days)\n * @default 30\n */\n persistenceDays?: number;\n\n /**\n * Whether to prefer URL parameters over stored ones when both exist\n * @default true\n */\n preferUrlParameters?: boolean;\n\n /**\n * Which form the parameters belong to, from {@link trackingScope}. Scoped values are\n * stored and read back only for that form; omit it for the legacy page-wide keys.\n */\n scope?: string;\n}\n\nconst DEFAULT_CONFIG: Required<Omit<TrackingConfig, \"scope\">> = {\n extractUtmParameters: true,\n extractClickIds: true,\n customParameterPrefix: \"track_\",\n persistToLocalStorage: true,\n persistenceDays: 30,\n preferUrlParameters: true,\n};\n\n/**\n * UTM and click ID parameter names.\n *\n * Sourced from chat-widget-core so this widget, the submit path in api/stentor-api.ts\n * and the event path in services/EventTrackingService.ts cannot disagree about which\n * parameters exist. The three previously kept separate lists, and adding a parameter\n * here alone meant it was persisted to localStorage but never sent to the server.\n */\nconst UTM_PARAMETERS = CORE_UTM_PARAMETERS;\n\nconst CLICK_ID_PARAMETERS = CORE_CLICK_ID_PARAMETERS;\n\n\n/**\n * Storage key prefix for localStorage\n */\nconst STORAGE_KEY_PREFIX = 'xa_tracking_';\n\n/**\n * Prefix shared by every key this module writes, scoped or not.\n */\nconst STORAGE_KEY_ROOT = 'xa_tracking';\n\n/**\n * Identifies one form for stored attribution: the app key plus the form's intentId,\n * the same pair StentorApi keys its instances by.\n *\n * Unscoped, a utm_source picked up on one form's landing URL was sent with every form\n * the browser opened for the next 30 days - on form.xapp.ai that is every tenant's form.\n */\nexport function trackingScope(key: string | undefined, intentId?: string): string {\n return `${key ?? ''}|${intentId ?? ''}`;\n}\n\n/**\n * The localStorage key prefix for a scope; the legacy page-wide prefix when there is none.\n * The scope is URI-encoded so it can never read as a param name, or as another scope.\n */\nfunction storageKeyPrefix(scope?: string): string {\n return scope === undefined ? STORAGE_KEY_PREFIX : `${STORAGE_KEY_ROOT}@${encodeURIComponent(scope)}:`;\n}\n\n/**\n * Snapshot of every localStorage key, via length/key() rather than Object.keys, which\n * not every Storage implementation enumerates. A snapshot, so callers can remove keys.\n */\nfunction storageKeys(): string[] {\n const keys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key) {\n keys.push(key);\n }\n }\n return keys;\n}\n\n/**\n * Validates if a parameter value is safe to store and use\n */\nfunction isValidParameterValue(value: string): boolean {\n // Check length limit and basic XSS prevention\n return value.length <= 255 && !/[<>\"'\\x00-\\x1f]/.test(value);\n}\n\n/**\n * Extracts tracking parameters from a URL\n */\nexport function extractTrackingParametersFromUrl(\n url: string = window.location.href,\n config: TrackingConfig = {}\n): TrackingParameters {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (error) {\n console.warn('Invalid URL provided to tracking parameter extraction:', url);\n return {};\n }\n\n const searchParams = urlObj.searchParams;\n const parameters: TrackingParameters = {};\n\n // Extract UTM parameters\n if (finalConfig.extractUtmParameters) {\n UTM_PARAMETERS.forEach(param => {\n const value = searchParams.get(param);\n if (value && isValidParameterValue(value)) {\n parameters[param] = value;\n }\n });\n }\n\n // Extract platform-specific click IDs\n if (finalConfig.extractClickIds) {\n CLICK_ID_PARAMETERS.forEach(param => {\n const value = searchParams.get(param);\n if (value && isValidParameterValue(value)) {\n parameters[param] = value;\n }\n });\n }\n\n // Extract custom tracking parameters\n if (finalConfig.customParameterPrefix) {\n searchParams.forEach((value, key) => {\n if (key.startsWith(finalConfig.customParameterPrefix) && isValidParameterValue(value)) {\n // Type-safe assignment for custom parameters\n (parameters as Record<string, string>)[key] = value;\n }\n });\n }\n\n return parameters;\n}\n\n/**\n * Gets tracking parameters from localStorage\n */\nexport function getStoredTrackingParameters(scope?: string): TrackingParameters {\n const parameters: TrackingParameters = {};\n const prefix = storageKeyPrefix(scope);\n\n // Check each potential parameter in localStorage\n [...UTM_PARAMETERS, ...CLICK_ID_PARAMETERS].forEach(param => {\n const stored = localStorage.getItem(`${prefix}${param}`);\n if (stored) {\n try {\n const data = JSON.parse(stored);\n // Check if data hasn't expired\n if (data.expires > Date.now()) {\n parameters[param] = data.value;\n }\n } catch (e) {\n // Clean up invalid data\n localStorage.removeItem(`${prefix}${param}`);\n }\n }\n });\n\n // Check for custom tracking parameters\n storageKeys().forEach(key => {\n if (key.startsWith(`${prefix}track_`)) {\n try {\n const data = JSON.parse(localStorage.getItem(key) || '{}');\n if (data.expires > Date.now()) {\n const paramName = key.slice(prefix.length) as keyof TrackingParameters;\n parameters[paramName] = data.value;\n }\n } catch (e) {\n localStorage.removeItem(key);\n }\n }\n });\n\n return parameters;\n}\n\n/**\n * Stores tracking parameters in localStorage with expiration\n */\nexport function storeTrackingParameters(\n parameters: TrackingParameters,\n config: TrackingConfig = {}\n): void {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n\n if (!finalConfig.persistToLocalStorage) {\n return;\n }\n\n const expirationTime = Date.now() + (finalConfig.persistenceDays * 24 * 60 * 60 * 1000);\n const prefix = storageKeyPrefix(config.scope);\n\n Object.entries(parameters).forEach(([key, value]) => {\n if (value) {\n const data = {\n value,\n expires: expirationTime,\n stored: Date.now()\n };\n localStorage.setItem(`${prefix}${key}`, JSON.stringify(data));\n }\n });\n}\n\n/**\n * Main function to get all tracking parameters, combining URL and stored parameters\n */\nexport function getAllTrackingParameters(\n url: string = window.location.href,\n config: TrackingConfig = {}\n): TrackingParameters {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n\n const urlParameters = extractTrackingParametersFromUrl(url, config);\n const storedParameters = getStoredTrackingParameters(config.scope);\n\n // Combine parameters, with URL parameters taking precedence if configured\n const parameters: TrackingParameters = finalConfig.preferUrlParameters\n ? { ...storedParameters, ...urlParameters }\n : { ...urlParameters, ...storedParameters };\n\n // Store any new URL parameters\n if (Object.keys(urlParameters).length > 0) {\n storeTrackingParameters(urlParameters, config);\n }\n\n return parameters;\n}\n\n/**\n * Clears all stored tracking parameters, for every form\n */\nexport function clearStoredTrackingParameters(): void {\n storageKeys().forEach(key => {\n if (key.startsWith(STORAGE_KEY_ROOT)) {\n localStorage.removeItem(key);\n }\n });\n}\n\n/**\n * Gets tracking parameters formatted for form widget attributes\n */\nexport function getTrackingParametersForWidget(\n url: string = window.location.href,\n config: TrackingConfig = {}\n): Record<string, string> {\n const parameters = getAllTrackingParameters(url, config);\n const attributes: Record<string, string> = {};\n\n // Convert to string attributes for widget consumption\n Object.entries(parameters).forEach(([key, value]) => {\n if (value) {\n attributes[key] = String(value);\n }\n });\n\n return attributes;\n}\n","\nexport const EMAIL_REGEX = \"^\\\\w+([\\\\.-]?\\\\w+)*@\\\\w+([\\\\.-]?\\\\w+)*(\\\\.\\\\w{2,3})+$\";\n\n// Returns current timestamp\nfunction getCurrentDateString() {\n return (new Date()).toISOString() + \" ::\";\n}\n\ntype LogParam = unknown;\n\nexport function log(...args: readonly LogParam[]): void {\n if (window.xaLogLevel === \"debug\") {\n console.log(getCurrentDateString(), ...args);\n }\n}\n\nexport function err(...args: readonly LogParam[]): void {\n console.error(getCurrentDateString(), ...args);\n}\n\nexport const logOnce = (key: string, ...args: readonly LogParam[]): void => {\n const map = {};\n if (!map[key]) {\n map[key] = true;\n log(...args);\n }\n}\n\nexport * from \"./useIsMounted\";\nexport * from \"./tracking\";","import { Display, List } from \"stentor-models\";\n\nexport function isCarousel(display: Display): display is List {\n return !!display && ((display as List).type === \"CAROUSEL\");\n}","import { Display, List } from \"stentor-models\";\n\nexport function isList(display: Display): display is List {\n return !!display && ((display as List).type === \"LIST\");\n}","import { Display, MultistepForm } from \"stentor-models\";\n\nexport function isForm(display: Display): display is MultistepForm {\n return !!display && display[\"type\"] === \"FORM\";\n}\n","import { throwBadKind } from \"../../utils/guards\";\nimport { SearchAction } from \"../actions\";\nimport { SearchState } from \"../SearchState\";\n\nexport function RootReducer(state: SearchState, action: SearchAction): SearchState {\n const { type } = action;\n switch (type) {\n case \"set-query\":\n return {\n ...state,\n query: action.query || \"\"\n };\n case \"set-response\":\n return {\n ...state,\n responseQuery: action.query,\n responseIntentId: action.intentId\n };\n case \"set-context\":\n return {\n ...state,\n context: action.context\n };\n case \"new-search\":\n return {\n ...state,\n query: \"\",\n };\n case \"set-modal-state\":\n return {\n ...state,\n active: action.active,\n minimized: action.minimized,\n sendRequest: action.sendRequest\n };\n case \"open-modal-state\":\n if (state.active) {\n return state;\n }\n return {\n ...state,\n active: true,\n minimized: false,\n sendRequest: true\n };\n default:\n throwBadKind(type);\n }\n}","// compile time full switch-case verification\nexport function throwBadKind(x: never): never {\n throw new Error(\"Unknown kind \" + x);\n}\n","import React from \"react\";\nimport { SearchDispatch } from \"./SearchDispatch\";\nimport { SearchState } from \"./SearchState\";\nimport { SearchStore } from \"./SearchStore\";\n\nexport const DEFAULT_SEARCH_STATE: SearchState = {\n query: \"\",\n active: false,\n minimized: false,\n sendRequest: true\n};\n\nconst DEFAULT_SEARCH_DISPATCH: SearchDispatch = () => { };\n\nconst DEFAULT_SEARCH_STORE: SearchStore = [DEFAULT_SEARCH_STATE, DEFAULT_SEARCH_DISPATCH];\n\nexport const SearchStoreContext = React.createContext<SearchStore>(DEFAULT_SEARCH_STORE);","import React, { FC, useReducer, PropsWithChildren } from \"react\";\nimport { RootReducer } from \"./reducers\";\nimport { SearchState } from \"./SearchState\";\nimport { SearchStore } from \"./SearchStore\";\nimport { DEFAULT_SEARCH_STATE, SearchStoreContext } from \"./SearchStoreContext\";\n\nexport interface SearchStoreProviderProps {\n readonly initialState?: SearchState;\n}\n\nexport const SearchStoreProvider: FC<PropsWithChildren<SearchStoreProviderProps>> = props => {\n\n const reducer: SearchStore = useReducer(RootReducer, props.initialState || DEFAULT_SEARCH_STATE);\n\n return (\n <SearchStoreContext.Provider value={reducer}>\n {props.children}\n </SearchStoreContext.Provider>\n );\n};","import { useContext } from \"react\";\nimport { SearchStore } from \"./SearchStore\";\nimport { SearchStoreContext } from \"./SearchStoreContext\";\n\nexport function useSearchStore(): SearchStore {\n return useContext(SearchStoreContext);\n}\n","import { SearchState } from \"./SearchState\";\nimport { useSearchStore } from \"./useSearchStore\";\n\nexport function useSearchState(): SearchState {\n return useSearchStore()[0];\n}\n","function styleInject(css, ref) {\n if ( ref === void 0 ) ref = {};\n var insertAt = ref.insertAt;\n\n if (!css || typeof document === 'undefined') { return; }\n\n var head = document.head || document.getElementsByTagName('head')[0];\n var style = document.createElement('style');\n style.type = 'text/css';\n\n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild);\n } else {\n head.appendChild(style);\n }\n } else {\n head.appendChild(style);\n }\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(document.createTextNode(css));\n }\n}\n\nexport default styleInject;\n","import {\n useBodyScrollLock,\n useScrollFocusedIntoView,\n useVisualViewportProperties,\n} from \"@xapp/chat-widget-core\";\nimport React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./ModalDialog.module.scss\";\n\nexport interface ModalDialogProps {\n /**\n * Removes the backdrop overlay\n *\n * Setting this to true will then disable the click backdrop to close functionality\n */\n readonly disableBackdrop?: boolean;\n /**\n * Callback when the user requests to close the modal by clicking the backdrop.\n */\n onClose(): void;\n /**\n * Rendering inside a container the host page provided and sized (see `isEmbedded`).\n *\n * The customer's div is then the frame, so everything this component does for the\n * floating case -- a fixed full-viewport overlay, a backdrop over the host page, and\n * locking the host page's scroll -- is dropped.\n */\n readonly embedded?: boolean;\n}\n\nexport const ModalDialog: FC<PropsWithChildren<ModalDialogProps>> = (props) => {\n const { embedded } = props;\n\n // This used to add a class that set `body { overflow: hidden }`, which iOS Safari\n // ignores — the host page scrolled on underneath the open modal. Embedded there is no\n // overlay to scroll underneath: the form sits in the page flow, and pinning the body\n // around it would freeze the customer's whole page.\n useBodyScrollLock(!embedded);\n\n // Keeps the step's action row clear of the soft keyboard — see the calc() on\n // .xapp_search_modal's mobile padding. Reference counted, so the chat widget's own\n // subscription survives this modal closing while its keyboard is still up. Embedded,\n // nothing consumes --xapp-keyboard-inset, so there is nothing to publish it for.\n useVisualViewportProperties(!embedded);\n\n // Browsers do this themselves, but not reliably inside a position: fixed overlay -\n // tapping the last field on a step could leave it behind the keyboard. Kept on when\n // embedded: the customer's container is commonly a scroll box with the same problem.\n useScrollFocusedIntoView();\n\n if (embedded) {\n return <div className={styles.xapp_search_modal_embedded}>{props.children}</div>;\n }\n\n return (\n <div className={styles.xapp_search_modal}>\n {!props.disableBackdrop && (\n <div\n data-testid=\"xapp-modal-backdrop\"\n className={styles[\"xapp_search_modal__backdrop\"]}\n onClick={props.onClose}\n />\n )}\n <div className={styles[\"xapp_search_modal__body\"]}>{props.children}</div>\n </div>\n );\n};\n","import { uuid, visitorId } from \"@xapp/chat-widget-core\";\nimport {\n ChannelActionRequest,\n IntentRequest,\n LaunchRequest,\n OptionSelectRequest,\n PermissionRequest,\n Response,\n} from \"stentor-models\";\nimport { StentorApiConfig } from \"../config\";\nimport { WidgetEvent, WidgetEventsRequest, WidgetEventsResponse } from \"../types/events\";\nimport { err, log } from \"../utils\";\nimport { addTestLeadAttribute } from \"@xapp/chat-widget-core\";\nimport { getStoredTrackingParameters, trackingScope } from \"../utils/tracking\";\n\nexport type StentorRequest =\n | IntentRequest\n | LaunchRequest\n | OptionSelectRequest\n | PermissionRequest\n | ChannelActionRequest;\n\nconst delay = (waitTimeInMs: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, waitTimeInMs);\n });\n\n/**\n * Marks a response for a channel action that was suppressed because a final submit had\n * already gone out on this session, rather than one that was actually sent.\n */\nconst DROPPED_AFTER_FINAL = \"__xappDroppedAfterFinal\";\n\n/**\n * True when the response came from the post-final suppression path rather than the\n * server. Callers use it to tell \"we deliberately did not send this\" apart from \"the\n * server returned nothing\" -- the two were indistinguishable before issue #1373.\n */\nexport function wasDroppedAfterFinal(response: unknown): boolean {\n return !!response && (response as Record<string, unknown>)[DROPPED_AFTER_FINAL] === true;\n}\n\n// One cached StentorApi per distinct widget config. A page can host multiple form widgets, each\n// bound to a different handler via its own intentId (see issue #1482), and each is an independent\n// conversation with its own session — so a single process-wide instance would make the second\n// widget send the first's intentId as overrideKey. Keyed by the fields that define a widget's\n// identity; the Form/FormWidget pair within one tree passes matching config and so shares one entry.\nconst API_INSTANCES = new Map<string, StentorApi>();\n\nconst apiCacheKey = (config: StentorApiConfig): string =>\n // demoMode is part of the identity, not just behaviour: a page can host a\n // live widget and a preview of the same handler, and sharing one instance\n // between them would let the preview submit through the live instance.\n `${config.url} ${config.key} ${config.intentId ?? \"\"} ${config.demoMode ? \"demo\" : \"live\"}`;\n\n/**\n * The only request types demo mode lets through.\n *\n * An **allowlist**, deliberately. A denylist of write types would let any\n * request type added later — OPTION_SELECT and PERMISSION_REQUEST already\n * exist unused in the StentorRequest union — through by default, and the\n * guarantee would quietly weaken as the request surface grows. Failing closed\n * means a new type is blocked until someone decides it is a read.\n *\n * These two only fetch the form definition; without them there is no form to\n * preview at all. Everything else, CHANNEL_ACTION_REQUEST above all, can\n * create a lead, notify the business, or land in reporting.\n *\n * So the guarantee is precisely \"a preview cannot create a lead or a tracked\n * event\", not \"a preview makes no requests\".\n */\nconst DEMO_READ_REQUEST_TYPES = new Set<string>([\"LAUNCH_REQUEST\", \"INTENT_REQUEST\"]);\n\nconst RESPONSE_TTL_MS = 900 * 1000; // 15 minutes\n\nconst TRACKING_CACHE_DURATION = 5 * 60 * 1000; // 5 minutes\n\nexport class StentorApi {\n private responseCache: {\n [key: string]: {\n ts: number;\n value: Response;\n };\n };\n\n private readonly config: StentorApiConfig;\n private session: StentorApiSession | undefined;\n /** Whether a request has gone out on the current session (visitSession can start one earlier). */\n private sessionSent = false;\n\n private prefetchSemaphore = Promise.resolve();\n\n // Cached tracking parameters to avoid repeated localStorage access. Per instance, since\n // each instance is one form and reads only that form's stored attribution.\n private cachedTrackingParams: { ts: number; value: Record<string, string> } | undefined;\n\n private constructor(config: StentorApiConfig) {\n this.config = config;\n this.responseCache = {};\n }\n\n /**\n * Which form this instance's stored attribution belongs to. See {@link trackingScope}.\n */\n public get trackingScope(): string {\n return trackingScope(this.config.key, this.config.intentId);\n }\n\n /**\n * Gets this form's tracking parameters with memory caching to reduce localStorage access\n */\n private getCachedTrackingParameters(): Record<string, string> {\n const now = Date.now();\n if (this.cachedTrackingParams && now - this.cachedTrackingParams.ts < TRACKING_CACHE_DURATION) {\n return this.cachedTrackingParams.value;\n }\n\n const value = getStoredTrackingParameters(this.trackingScope) as Record<string, string>;\n this.cachedTrackingParams = { ts: now, value };\n return value;\n }\n\n /**\n * Returns the cached API instance for this widget config, creating it on first use.\n *\n * Instances are keyed by url + key + intentId, so two widgets on one page with different\n * intentIds each get their own instance (and their own session) instead of colliding on a\n * single process-wide one. The Form/FormWidget pair within a single widget tree passes matching\n * config and so shares one entry.\n */\n public static getApi(config: StentorApiConfig): StentorApi {\n const cacheKey = apiCacheKey(config);\n const existing = API_INSTANCES.get(cacheKey);\n if (existing) {\n return existing;\n }\n\n const api = new StentorApi(config);\n API_INSTANCES.set(cacheKey, api);\n\n if (config.prefetchQuery) {\n api.prefetch(config.prefetchQuery);\n }\n\n return api;\n }\n\n public launchRequest(query: string): Promise<Response> {\n return this.send({\n type: \"LAUNCH_REQUEST\",\n rawQuery: query,\n intentId: \"LaunchRequest\",\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n } as StentorRequest);\n }\n\n public intentRequest(request: { query?: string; intentId?: string }): Promise<Response> {\n // if we have the intentId, use that and set rawQuery to be undefined\n // so that stentor doesn't try to resolve it again\n // otherwise, use the query and set intentId to be \"NLU_RESULT_PLACEHOLDER\"\n const rawQuery: string | undefined = request?.intentId ? undefined : request.query;\n const intentId: string = request?.intentId ? request.intentId : \"NLU_RESULT_PLACEHOLDER\";\n\n return this.send({\n type: \"INTENT_REQUEST\",\n rawQuery,\n intentId,\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n } as StentorRequest);\n }\n\n public channelActionRequest(data: unknown, action: string): Promise<Response> {\n const isFinal = !!(data as any).final;\n\n if (this.session) {\n if (this.session.hadFinal) {\n log(`Had final submit. Not sending action request: ${action}`);\n // Flagged rather than a bare {}: suppressing a duplicate after the final\n // submit is correct, but an indistinguishable empty response meant a\n // caller could not tell a dropped submit from a delivered one -- so a\n // wrongly-latched session looked exactly like success (issue #1373).\n // A plain string key, not a Symbol: the module is re-required per test\n // and Symbol identity would not survive that.\n return Promise.resolve({ [DROPPED_AFTER_FINAL]: true } as unknown as Response);\n }\n\n this.session.hadFinal = isFinal;\n }\n\n return this.send({\n type: \"CHANNEL_ACTION_REQUEST\",\n action,\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n ...(this.config.intentId ? { overrideKey: this.config.intentId } : {}),\n attributes: {\n data,\n },\n // The double cast is required: ChannelActionRequest requires userId, which send() fills\n // in below. It is NOT about overrideKey — that is a declared optional field on the\n // request type. A single `as StentorRequest` does not compile here.\n } as unknown as StentorRequest).catch((error) => {\n // The latch goes up synchronously above so a double-click cannot put two\n // finals in flight. But a final that never reached the server must not keep\n // it up: leaving it latched turns every retry into an instant\n // DROPPED_AFTER_FINAL \"success\", which is precisely how a lead goes missing\n // (issue #1373). Unlatch and let the caller retry for real.\n if (this.session && isFinal) {\n this.session.hadFinal = false;\n }\n throw error;\n });\n }\n\n /**\n * Track form widget interaction events\n * Sends events to POST /cms/widget/events\n *\n * Authentication uses the widget key in the request body (not headers).\n *\n * @param eventType - Type of event (next_step, submit, partial_data)\n * @param event - The widget event to track\n * @returns The response with processed count, or undefined on error\n */\n public async trackEvent(\n eventType: string,\n event: WidgetEvent\n ): Promise<WidgetEventsResponse | undefined> {\n try {\n const { key } = this.config;\n if (this.config.demoMode) {\n // A preview interaction must not show up in funnel analytics as\n // a real form open/submit.\n log(\"[demoMode] suppressed tracking event\", eventType);\n return undefined;\n }\n if (!key) {\n err(\"[EventTracking] No widget key configured, skipping event tracking\");\n return undefined;\n }\n const trackingUrl = this.getTrackingUrl();\n\n // Request body includes key for authentication (no Authorization header needed)\n const requestBody: WidgetEventsRequest = {\n key,\n events: [event],\n };\n\n const params: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(requestBody),\n mode: \"cors\",\n };\n\n const response = await fetch(trackingUrl, params);\n\n if (!response.ok) {\n err(`Event tracking failed: ${response.status} ${response.statusText}`);\n // Don't throw - we don't want to block user flow\n return undefined;\n }\n\n const result: WidgetEventsResponse = await response.json();\n log(`Event tracking succeeded: ${eventType}, processed: ${result.processed}`);\n return result;\n } catch (error) {\n // Log error but don't throw - events should never block user flow\n err(`Event tracking error: ${error}`);\n return undefined;\n }\n }\n\n /**\n * Track form widget interaction events for page unload scenarios.\n *\n * Uses fetch with keepalive instead of sendBeacon because:\n * - sendBeacon with Content-Type: application/json triggers CORS preflight\n * - sendBeacon doesn't properly wait for preflight response before firing\n * - fetch with keepalive handles the preflight handshake correctly\n *\n * @param event - The widget event to track\n * @param widgetType - Names the sending widget, for event types the server shares between\n * widgets (e.g. \"load\"). Omitted from the body when not given.\n * @returns true if the request was queued (not necessarily delivered), false if queuing failed\n */\n public trackEventBeacon(event: WidgetEvent, widgetType?: WidgetEventsRequest[\"widgetType\"]): boolean {\n const { key } = this.config;\n if (this.config.demoMode) {\n // The beacon fires on beforeunload and on the midnight timeout, and\n // its payload is `partialData` — the values the visitor actually\n // typed. A preview that gets abandoned would otherwise post real\n // form data to the events endpoint, which is exactly what demo mode\n // exists to prevent.\n log(\"[demoMode] suppressed tracking beacon\", event.eventType);\n return false;\n }\n if (!key) {\n err(\"[EventTracking] No widget key configured, skipping event beacon\");\n return false;\n }\n\n try {\n const trackingUrl = this.getTrackingUrl();\n const requestBody: WidgetEventsRequest = {\n key,\n ...(widgetType ? { widgetType } : {}),\n events: [event],\n };\n\n // Use fetch with keepalive for proper CORS handling during page unload.\n // keepalive allows the request to outlive the page.\n // Note: This is fire-and-forget - we return true once queued, regardless of\n // eventual success/failure, since the page may be gone by the time it completes.\n fetch(trackingUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(requestBody),\n keepalive: true,\n }).catch(() => {\n // Silently ignore errors - page may already be unloaded\n });\n\n return true;\n } catch (error) {\n err(`Event beacon error: ${error}`);\n return false;\n }\n }\n\n /**\n * Build the tracking endpoint URL: /cms/widget/events\n */\n private getTrackingUrl(): string {\n const { url } = this.config;\n\n try {\n const parsedUrl = new URL(url);\n // Extract origin (protocol + host) and build the tracking endpoint\n return `${parsedUrl.origin}/cms/widget/events`;\n } catch (e) {\n // Fallback for invalid URLs - try to extract origin manually\n err(`[EventTracking] Failed to parse URL: ${url}`);\n const match = url.match(/^(https?:\\/\\/[^/]+)/);\n if (match) {\n return `${match[1]}/cms/widget/events`;\n }\n // Last resort: append to the URL\n return `${url.replace(/\\/$/, \"\")}/cms/widget/events`;\n }\n }\n\n public resetSession(): void {\n this.session = undefined;\n this.sessionSent = false;\n }\n\n /**\n * This visit's session and the visitor's user id (the shared visitor id), starting the session if no request has\n * yet. The load event calls it before the form has sent anything, so the load carries the\n * same ids as the visit's open and submit events. The first request on it still goes out\n * as the new session.\n */\n public visitSession(): { readonly sessionId: string; readonly userId: string } {\n if (!this.session) {\n this.session = {\n sessionId: `stentor-form-session-${uuid()}`,\n // The visitor id every XAPP widget on the site shares, so a lead's user id is\n // the one the chat widget's events report too.\n userId: visitorId(),\n hadFinal: false,\n };\n }\n const { sessionId, userId } = this.session;\n return { sessionId, userId };\n }\n\n private getCachedResponse(query: string | undefined): Response | undefined {\n if (!query) {\n return;\n }\n\n const now = new Date().getTime();\n const hit = this.responseCache[query];\n\n if (hit) {\n if (now - hit.ts < RESPONSE_TTL_MS) {\n log(`Returning cached response for \"${query}\"`);\n return hit.value;\n }\n\n log(`Deleting expired cached response for \"${query}\"`);\n delete this.responseCache[query];\n }\n\n return;\n }\n\n private async send(\n data: Omit<StentorRequest, \"sessionId\" | \"userId\" | \"isNewSession\">\n ): Promise<Response> {\n await this.prefetchSemaphore;\n\n if (this.config.demoMode && !DEMO_READ_REQUEST_TYPES.has(data.type)) {\n // Only reads are allowed through: the form's entire step structure\n // arrives on the INTENT_REQUEST response and is stashed in\n // formDisplayRef, and that handler applies the response\n // unconditionally. Blocking reads too would clobber state with an\n // empty response and render a form with no steps — the opposite of\n // \"behaves exactly like production\".\n log(\"[demoMode] suppressed request\", data.type);\n // Deliberately partial. Every field on Response that callers read\n // — outputSpeech, displays, context — is optional, and they all\n // guard before use, so absent means \"nothing to apply\" rather than\n // a missing value. The cast is what makes that intent explicit; if\n // a caller ever starts requiring a field, this is where to add it.\n return {} as Response;\n }\n\n const hit = this.getCachedResponse(data.rawQuery);\n if (hit) {\n return Promise.resolve(hit);\n }\n\n const { url, key } = this.config;\n\n const newSession = !this.sessionSent;\n const { sessionId, userId } = this.visitSession();\n this.sessionSent = true;\n\n const attributes: Record<string, unknown> = {};\n\n // Add current URL for analytics (exclude localhost for privacy)\n try {\n const href = new URL(window.location.href);\n if (href?.host.toLowerCase().startsWith(\"localhost\")) {\n // Indicate localhost without exposing the full URL\n attributes[\"isLocal\"] = true;\n } else {\n // Not localhost, include the full URL\n attributes[\"currentUrl\"] = window.location.href;\n }\n } catch (e) {\n // If URL parsing fails, skip currentUrl\n }\n\n // look for certain attributes on the browser and add them.\n // get xa_rwg_token from local storage\n const rwgToken = localStorage.getItem(\"xa_rwg_token\");\n if (rwgToken) {\n attributes[\"rwg_token\"] = rwgToken;\n }\n const merchantId = localStorage.getItem(\"xa_merchant_id\");\n if (merchantId) {\n attributes[\"merchant_id\"] = merchantId;\n }\n const environment = localStorage.getItem(\"xa_environment\");\n if (environment) {\n attributes[\"environment\"] = environment;\n }\n const enablePreferredTime = localStorage.getItem(\"xa_enablePreferredTime\");\n if (enablePreferredTime) {\n attributes[\"enablePreferredTime\"] = enablePreferredTime;\n }\n const service = localStorage.getItem(\"xa_service\");\n if (service) {\n attributes[\"service\"] = service;\n }\n const origin = localStorage.getItem(\"xa_origin\");\n if (origin) {\n attributes[\"origin\"] = origin;\n }\n\n // Read placeId from URL parameters on every request (not cached like UTM params).\n // This is intentional: in multi-location / SPA scenarios (e.g. Reserve with Google),\n // the URL may change between requests within a session and the routing must always\n // reflect the current placeId. The value is forwarded to the backend as-is; the\n // backend is responsible for validating and using the value safely.\n try {\n const urlParams = new URLSearchParams(window.location.search);\n const placeId = urlParams.get(\"placeId\");\n if (placeId) {\n attributes[\"placeId\"] = placeId;\n }\n } catch (e) {\n // If URL parsing fails, skip placeId\n }\n\n // Extract tracking parameters using cached approach for better performance\n const trackingParams = this.getCachedTrackingParameters();\n Object.assign(attributes, trackingParams);\n\n // A test lead from Studio's \"send yourself a test lead\" booking page\n addTestLeadAttribute(attributes);\n\n // Add current time for accurate date/time responses\n attributes[\"currentTime\"] = new Date().toISOString();\n\n const request = {\n ...data,\n sessionId,\n userId,\n isNewSession: newSession,\n attributes: {\n ...data.attributes,\n ...attributes,\n },\n } as StentorRequest;\n const body = JSON.stringify(request);\n\n const params: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${key}`,\n },\n body,\n mode: \"cors\",\n };\n\n let response = await fetch(url, params);\n\n if (!response.ok) {\n err(`Stentor call failed: ${response.statusText}`);\n\n await delay(1000);\n response = await fetch(url, params); // once more\n if (!response.ok) {\n err(`Stentor call failed again: ${response.statusText}`);\n throw new Error(`Status ${response.status}, Text: ${response.statusText}`);\n }\n }\n\n return response.json();\n }\n\n private async prefetch(query: string): Promise<void> {\n if (this.config.demoMode) {\n return;\n }\n\n const hit = this.getCachedResponse(query);\n if (hit) {\n return;\n }\n\n let resolver: (value: void | PromiseLike<void>) => void;\n\n this.prefetchSemaphore = new Promise((resolve) => {\n resolver = resolve;\n });\n\n const { url, key } = this.config;\n\n const newSession = !this.sessionSent;\n const { sessionId, userId } = this.visitSession();\n this.sessionSent = true;\n\n\n const data = {\n type: \"INTENT_REQUEST\",\n rawQuery: query,\n intentId: \"NLU_RESULT_PLACEHOLDER\",\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n };\n\n const attributes: Record<string, unknown> = {\n currentTime: new Date().toISOString(),\n };\n\n const request = {\n ...data,\n sessionId,\n userId,\n isNewSession: newSession,\n attributes,\n } as StentorRequest;\n\n const body = JSON.stringify(request);\n\n const params: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${key}`,\n },\n body,\n mode: \"cors\",\n };\n\n const start = new Date().getTime();\n\n fetch(url, params)\n .then(async (fetchResponse) => {\n if (!fetchResponse.ok) {\n err(`Stentor prefetch failed: ${fetchResponse.statusText}`);\n return;\n }\n\n const now = new Date().getTime();\n\n this.responseCache[query] = {\n ts: now,\n value: await fetchResponse.json(),\n };\n\n log(`Stentor prefetch took: ${now - start} ms`);\n })\n .finally(() => {\n resolver();\n });\n\n return;\n }\n}\n\nexport interface StentorApiSession {\n readonly sessionId: string;\n readonly userId: string;\n hadFinal: boolean;\n}\n","import { SuggestionTypes } from \"stentor-models\";\n\nexport function getActionLabel(action: SuggestionTypes): string {\n if (typeof action === \"string\") {\n return action;\n }\n return action.title;\n}\n","import React from \"react\";\nimport { FormWidgetConfig } from \"../config\";\n\nconst defaultValue: FormWidgetConfig = {\n api: {\n key: \"\",\n url: \"\"\n },\n suggestionsUrl: \"\",\n isVoiceEnabled: false,\n autoGreeting: \"schedule\" // default utterance to trigger the form if not set in config\n};\n\nexport const SearchWidgetConfigContext = React.createContext<FormWidgetConfig>(defaultValue);","import { useCallback, useMemo, useState } from \"react\";\nimport { useIsMounted } from \"./useIsMounted\";\n\nexport type LoadingAction<TResult> = () => Promise<TResult>;\n\nexport type LoadingRunAction<TResult> = (action: LoadingAction<TResult>) => Promise<TResult>;\n\nexport interface LoadingState {\n readonly loading: boolean;\n run<TResult>(action: LoadingAction<TResult>): Promise<TResult>;\n}\n\nfunction runCounter<TResult>(action: LoadingAction<TResult>, shift: (delta: number) => void): Promise<TResult> {\n shift(1);\n return action().finally(() => {\n shift(-1);\n });\n}\n\nexport function useLoading(): LoadingState {\n\n const [state, setState] = useState<number>(0);\n\n const mounted = useIsMounted();\n\n const run = useCallback(<TResult>(action: LoadingAction<TResult>) => {\n return runCounter(action, delta => {\n if (mounted()) {\n setState(prev => prev + delta);\n }\n });\n }, [mounted]);\n\n return useMemo(() => ({\n loading: !!state,\n run\n }), [state, run]);\n\n}","import { useCallback, useEffect, useRef } from \"react\";\n\nexport function useIsMounted(): () => boolean {\n const ref = useRef(false);\n useEffect(() => {\n ref.current = true;\n return () => {\n ref.current = false;\n };\n }, []);\n\n return useCallback(() => ref.current, []);\n};\n","import { useEffect, useCallback } from \"react\";\nimport { err } from \".\";\n\nconst TRUSTED_FORM_CERT_FIELD = \"xxTrustedFormCertUrl\";\nconst TRUSTED_FORM_PING_FIELD = \"xxTrustedFormPingUrl\";\nconst TRUSTED_FORM_ORIGIN = \"https://api.trustedform.com\";\n\nfunction isValidTrustedFormUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n return parsed.origin === TRUSTED_FORM_ORIGIN;\n } catch {\n return false;\n }\n}\n\nexport function useTrustedForm(scriptUrl: string | undefined): () => Record<string, string> | undefined {\n useEffect(() => {\n if (!scriptUrl) {\n return;\n }\n\n if (!isValidTrustedFormUrl(scriptUrl)) {\n err(\"[TrustedForm] Rejected script URL from unexpected origin\");\n return;\n }\n\n const existingScript = document.querySelector(`script[src=\"${scriptUrl}\"]`);\n if (existingScript) {\n return;\n }\n\n const script = document.createElement(\"script\");\n script.async = true;\n script.src = scriptUrl;\n\n script.onerror = () => {\n err(\"[TrustedForm] Failed to load script\");\n };\n\n // Intentionally no cleanup on unmount — TrustedForm must remain active for the page session\n document.head.appendChild(script);\n }, [scriptUrl]);\n\n const getTrustedFormData = useCallback((): Record<string, string> | undefined => {\n if (!scriptUrl) {\n return undefined;\n }\n\n const data: Record<string, string> = {};\n\n const certInput = document.querySelector<HTMLInputElement>(\n `input[name=\"${TRUSTED_FORM_CERT_FIELD}\"], input[id=\"${TRUSTED_FORM_CERT_FIELD}\"]`\n );\n const pingInput = document.querySelector<HTMLInputElement>(\n `input[name=\"${TRUSTED_FORM_PING_FIELD}\"], input[id=\"${TRUSTED_FORM_PING_FIELD}\"]`\n );\n\n if (certInput?.value) {\n data[TRUSTED_FORM_CERT_FIELD] = certInput.value;\n }\n if (pingInput?.value) {\n data[TRUSTED_FORM_PING_FIELD] = pingInput.value;\n }\n\n if (Object.keys(data).length === 0) {\n err(\"[TrustedForm] No certificate data found in DOM\");\n return undefined;\n }\n\n return data;\n }, [scriptUrl]);\n\n return getTrustedFormData;\n}\n","/**\n * Reads a single cookie value by name, or undefined when unavailable\n * (no document, empty cookie jar, or the cookie is not set).\n */\nexport function getCookie(name: string): string | undefined {\n if (typeof document === \"undefined\" || !document.cookie) {\n return undefined;\n }\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = document.cookie.match(new RegExp(\"(?:^|; )\" + escaped + \"=([^;]*)\"));\n if (!match) {\n return undefined;\n }\n try {\n return decodeURIComponent(match[1]);\n } catch {\n // decodeURIComponent throws a URIError on malformed percent-encoding\n // (e.g. a stray \"%\" written by another script). getMetaCookies runs\n // during FORM_SUBMIT, so never let a bad tracking cookie break the lead:\n // fall back to the raw value (fbp/fbc are normally not percent-encoded).\n return match[1];\n }\n}\n\n/**\n * Meta's browser cookies used for Conversions API match quality and dedup:\n * `_fbp` (browser id) and `_fbc` (click id). Forwarded to the backend with the\n * lead so the server-side CAPI event carries the same signals as the browser\n * pixel. Only keys that are actually present are returned.\n */\nexport function getMetaCookies(): { fbp?: string; fbc?: string } {\n const fbp = getCookie(\"_fbp\");\n const fbc = getCookie(\"_fbc\");\n return {\n ...(fbp ? { fbp } : {}),\n ...(fbc ? { fbc } : {}),\n };\n}\n","import React, { FC } from \"react\";\n\nexport const LeftAngleIcon: FC = () => {\n return (\n <svg viewBox=\"0 0 15 15\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M10 14L3 7.5L10 1\" stroke=\"currentColor\" fill=\"none\" strokeLinecap=\"square\" />\n </svg>\n );\n}","import React, { FC } from \"react\";\n\nexport const RightAngleIcon: FC = () => {\n return (\n <svg viewBox=\"0 0 15 15\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M5 14L12 7.5L5 1\" stroke=\"currentColor\" fill=\"none\" strokeLinecap=\"square\" />\n </svg>\n );\n}","import React, { FC } from \"react\";\n\nexport const SearchIcon: FC = () => {\n return (\n <svg\n fill=\"#000000\"\n height=\"300px\"\n width=\"30px\"\n version=\"1.1\"\n id=\"Capa_1\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 382.163 382.163\">\n <g>\n <path\n d=\"M344.89,215.855c0-50.602-24.567-95.57-62.396-123.618l2.982-5.326l46.258,25.92c1.16,0.65,2.418,0.958,3.659,0.958\n\t\tc2.626,0,5.175-1.381,6.55-3.835c8.883-15.853,11.061-34.216,6.132-51.706c-4.243-15.059-13.327-27.91-25.887-36.864l5.722-10.22\n\t\tc2.023-3.614,0.733-8.185-2.881-10.208c-3.614-2.023-8.184-0.734-10.208,2.88l-5.72,10.216\n\t\tc-31.487-13.349-68.758-1.123-85.857,29.391c-0.972,1.735-1.215,3.786-0.676,5.7s1.817,3.536,3.553,4.509l46.268,25.925\n\t\tl-2.406,4.297c-23.084-13.853-50.078-21.83-78.903-21.83c-28.825,0-55.818,7.977-78.902,21.829l-2.408-4.296l46.269-25.926\n\t\tc3.614-2.025,4.902-6.595,2.877-10.209c-8.883-15.853-23.407-27.297-40.897-32.226c-15.061-4.244-30.765-3.205-44.96,2.833\n\t\tL67.342,3.838c-2.023-3.615-6.593-4.904-10.208-2.881c-3.614,2.023-4.904,6.594-2.881,10.208l5.721,10.22\n\t\tc-12.559,8.954-21.643,21.804-25.886,36.864c-4.929,17.49-2.751,35.854,6.132,51.706c1.375,2.454,3.924,3.835,6.55,3.835\n\t\tc1.241,0,2.5-0.309,3.659-0.958l46.257-25.919l2.984,5.324c-37.83,28.047-62.397,73.016-62.397,123.619\n\t\tc0,45.21,19.61,85.924,50.767,114.091l-9.427,43.114c-0.885,4.047,1.678,8.044,5.725,8.929c0.54,0.118,1.078,0.175,1.609,0.175\n\t\tc3.448,0,6.553-2.393,7.32-5.899l7.818-35.757c25.321,18.332,56.416,29.157,89.996,29.157c33.58,0,64.676-10.825,89.997-29.158\n\t\tl7.818,35.758c0.767,3.507,3.871,5.899,7.319,5.899c0.531,0,1.07-0.057,1.609-0.175c4.046-0.885,6.61-4.882,5.725-8.929\n\t\tl-9.427-43.115C325.281,301.778,344.89,261.065,344.89,215.855z M308.517,30.436c12.357,6.924,21.279,18.246,25.121,31.88\n\t\tc3.155,11.198,2.574,22.853-1.57,33.507l-91.609-51.331C256.211,23.856,285.228,17.387,308.517,30.436z M50.096,95.824\n\t\tc-4.145-10.654-4.726-22.31-1.57-33.507c3.842-13.634,12.763-24.956,25.121-31.88c8.179-4.583,17.064-6.758,25.833-6.758\n\t\tc16.201,0,32.005,7.425,42.225,20.814L50.096,95.824z M52.273,215.855c0-76.54,62.269-138.809,138.809-138.809\n\t\tS329.89,139.315,329.89,215.855s-62.27,138.809-138.809,138.809S52.273,292.394,52.273,215.855z\"\n />\n <path\n d=\"M191.081,107.685c-59.645,0-108.17,48.525-108.17,108.17c0,59.645,48.525,108.17,108.17,108.17\n\t\tc59.646,0,108.17-48.525,108.17-108.17C299.252,156.21,250.727,107.685,191.081,107.685z M191.081,309.025\n\t\tc-51.374,0-93.17-41.796-93.17-93.17c0-51.374,41.796-93.17,93.17-93.17c51.375,0,93.17,41.796,93.17,93.17\n\t\tC284.252,267.229,242.456,309.025,191.081,309.025z\"\n />\n <path\n d=\"M198.585,190.081v-36.262c0-4.142-3.358-7.5-7.5-7.5s-7.5,3.358-7.5,7.5v36.26c-8.784,2.559-15.718,9.492-18.279,18.276\n\t\th-16.941c-4.142,0-7.5,3.358-7.5,7.5s3.358,7.5,7.5,7.5h16.941c3.254,11.165,13.574,19.349,25.775,19.349\n\t\tc14.805,0,26.849-12.044,26.849-26.849C217.93,203.655,209.748,193.337,198.585,190.081z M191.081,227.704\n\t\tc-6.533,0-11.849-5.315-11.849-11.849s5.315-11.849,11.849-11.849c6.534,0,11.849,5.315,11.849,11.849\n\t\tS197.615,227.704,191.081,227.704z\"\n />\n </g>\n </svg>\n );\n};\n","import React, { FC } from \"react\";\n\nconst strokeWidth = 16;\nconst strokeWidthHalf = strokeWidth / 2;\nconst strokeWidthQuarter = strokeWidth / 4;\n\nexport const SpinnerIcon:FC = () => {\n return (\n <svg\n viewBox=\"0 0 200 200\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <defs>\n <linearGradient id=\"spinner-secondHalf\">\n <stop offset=\"0%\" stopOpacity=\"0\" stopColor=\"currentColor\" />\n <stop offset=\"100%\" stopOpacity=\"0.5\" stopColor=\"currentColor\" />\n </linearGradient>\n <linearGradient id=\"spinner-firstHalf\">\n <stop offset=\"0%\" stopOpacity=\"1\" stopColor=\"currentColor\" />\n <stop offset=\"100%\" stopOpacity=\"0.5\" stopColor=\"currentColor\" />\n </linearGradient>\n </defs>\n \n <g strokeWidth={strokeWidth}>\n <path stroke=\"url(#spinner-secondHalf)\" d={`M${strokeWidthHalf} 100 A${100 - strokeWidthHalf} ${100 - strokeWidthHalf} 0 0 1 ${200 - strokeWidthHalf} 100`} />\n <path stroke=\"url(#spinner-firstHalf)\" d={`M${200 - strokeWidthHalf} 100 A${100 - strokeWidthHalf} ${100 - strokeWidthHalf} 0 0 1 ${strokeWidthHalf} 100`} />\n \n <path\n stroke=\"currentColor\"\n strokeLinecap=\"round\"\n d={`M${strokeWidthHalf} 100 A${100 - strokeWidthHalf} ${100 - strokeWidthHalf} 0 0 1 ${strokeWidthHalf} ${100 - strokeWidthQuarter}`}\n />\n </g>\n \n <animateTransform\n from=\"0 0 0\"\n to=\"360 0 0\"\n attributeName=\"transform\"\n type=\"rotate\"\n repeatCount=\"indefinite\"\n dur=\"1300ms\"\n />\n </svg>\n );\n};","import React, { FC } from \"react\";\n\n/**\n * The handful of Material glyphs the form fields draw, inlined so the fields do not pull in\n * @mui/icons-material (and SvgIcon, and emotion) for six paths. Same 24x24 artwork as the\n * Material icons they replace, and decorative: the control they sit in carries the name.\n */\ninterface FieldIconProps {\n readonly className?: string;\n}\n\nconst icon = (path: string): FC<FieldIconProps> => {\n const FieldIcon: FC<FieldIconProps> = ({ className }) => (\n <svg\n className={className}\n viewBox=\"0 0 24 24\"\n width=\"1em\"\n height=\"1em\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n focusable=\"false\">\n <path d={path} />\n </svg>\n );\n return FieldIcon;\n};\n\nexport const CheckIcon = icon(\"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z\");\n\nexport const CheckBoxIcon = icon(\n \"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z\"\n);\n\nexport const CheckBoxOutlineIcon = icon(\n \"M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z\"\n);\n\nexport const RadioCheckedIcon = icon(\n \"M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z\"\n);\n\nexport const RadioUncheckedIcon = icon(\n \"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z\"\n);\n\nexport const ArrowDropDownIcon = icon(\"M7 10l5 5 5-5z\");\n\nexport const ChevronLeftIcon = icon(\"M15.41 16.59 10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z\");\n\nexport const ChevronRightIcon = icon(\"M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z\");\n","import { MessageBubble } from \"@xapp/chat-widget-core\";\nimport React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./SearchResponseBubble.module.scss\";\n\nexport interface SearchResponseBubbleProps { }\n\nexport const SearchResponseBubble: FC<PropsWithChildren<SearchResponseBubbleProps>> = props => {\n return (\n <div className={styles.xapp_search_response_bubble}>\n <MessageBubble>\n {props.children}\n </MessageBubble>\n </div>\n );\n};","// Note: This is great code that we should move to stentor-utils to help reduce URLs\n// Right now I just copy and pasted this from the widget channel\n\ndeclare type Parser = (rest: string, all: string) => number;\n\nfunction firstIndex(val: string, patterns: readonly string[]) {\n let res = -1;\n for (const pattern of patterns) {\n const index = val.indexOf(pattern);\n if (index >= 0) {\n if (res < 0 || ((res >= 0) && (index < res))) {\n res = index;\n }\n }\n }\n return res;\n}\n\nconst schemeParser: Parser = rest => {\n const next = rest.indexOf(\"://\");\n if (next < 0) return next;\n return next + 3;\n};\n\nconst domainEnds: readonly string[] = [\":\", \"/\"];\nconst portEnds: readonly string[] = [\"/\"];\nconst pathEnds: readonly string[] = [\"?\", \"#\"];\nconst queryEnds: readonly string[] = [\"#\"];\n\nconst domainParser: Parser = rest => {\n return firstIndex(rest, domainEnds);\n};\n\nconst portParser: Parser = rest => {\n if (rest.charAt(0) !== \":\") {\n return -1;\n }\n return firstIndex(rest, portEnds);\n};\n\nconst pathParser: Parser = rest => {\n const res = firstIndex(rest, pathEnds);\n if (res >= 0) {\n return res;\n }\n return rest.length;\n};\n\nconst queryParser: Parser = rest => {\n return firstIndex(rest, queryEnds);\n};\n\nconst parsers: Parser[] = [\n schemeParser,\n domainParser,\n portParser,\n pathParser,\n queryParser\n];\n\nfunction parse(val: string): string[] {\n const parts: string[] = [];\n let rest = val;\n for (const parser of parsers) {\n const newIndex = Math.max(0, parser(rest, val));\n const part = rest.substring(0, newIndex);\n parts.push(part);\n rest = rest.substring(newIndex);\n }\n if (rest) {\n parts.push(rest);\n }\n return parts;\n}\n\nconst ellipsis = \"/...\";\n\nexport function reduceLink(url: string, maxLength: number): string {\n if (!url) return url;\n\n if (url.length < maxLength) return url;\n\n const parts = parse(url); // [scheme, domain, port, path, query, hash]\n\n function getText() {\n return parts.join(\"\");\n }\n\n function overflows() {\n return getText().length > maxLength;\n }\n\n function tryReduce(index: number) {\n if (overflows()) {\n parts[index] = \"\";\n }\n }\n\n if (parts[2] === \":80\" && parts[0] === \"http://\") {\n tryReduce(2);\n }\n if (parts[2] === \":443\" && parts[0] === \"https://\") {\n tryReduce(2);\n }\n\n tryReduce(5);\n tryReduce(4);\n tryReduce(2);\n tryReduce(0);\n\n if (overflows()) {\n const path = parts[3];\n const allButPathLength = getText().length - path.length;\n const available = maxLength - allButPathLength;\n if (available < 0) {\n parts[3] = \"\";\n } else if (available < path.length) {\n const newPathStart = path.length - available + ellipsis.length;\n parts[3] = ellipsis + path.substring(newPathStart)\n }\n }\n\n return getText();\n}\n","import React, { FC } from \"react\";\nimport { ListItem } from \"stentor-models\";\nimport { reduceLink } from \"./utils\";\nimport styles from \"./Card.module.scss\";\n\nexport interface CardProps {\n readonly item: ListItem;\n readonly className?: string;\n}\n\nexport const Card: FC<CardProps> = props => {\n const { item } = props;\n\n const imageUrl = item.image?.url;\n\n return (\n <div className={`${styles.xapp_search_card} ${props.className || \"\"}`}>\n {!!imageUrl &&\n <div className={styles['xapp_search_card__featured']}>\n <div className={styles['xapp_search_card__featured_box']}>\n <img\n src={item.image?.url}\n className={styles['xapp_search_card__img']}\n alt={item.image?.accessibilityText}\n />\n </div>\n </div>\n }\n <div className={styles['xapp_search_card__content']}>\n {!!item.url && <a href={item.url} className={styles['xapp_search_card__title']}>\n {item.title}\n </a>}\n {!!item.url && <div className={styles['xapp_search_card__link']}>{reduceLink(item.url, 40)}</div>}\n <div className={styles['xapp_search_card__description']}>\n {item.description}\n </div>\n </div>\n </div>\n );\n};","import React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./CarouselItem.module.scss\";\n\nexport interface CarouselItemProps {\n readonly className?: string;\n}\n\nexport const CarouselItem: FC<PropsWithChildren<CarouselItemProps>> = props => {\n return (\n <div className={`${styles.xapp_search_carousel_item} ${props.className || \"\"}`}>\n {props.children}\n </div>\n );\n};\n\n","import { IconButton } from \"@xapp/chat-widget-core\";\nimport React, { FC, useCallback, useRef } from \"react\";\nimport { List } from \"stentor-models\";\nimport { Card } from \"../Card\";\nimport { LeftAngleIcon, RightAngleIcon } from \"../icons\";\nimport styles from \"./Carousel.module.scss\";\nimport { CarouselItem } from \"./CarouselItem\";\n\nexport interface CarouselProps {\n readonly list: List;\n}\n\nexport const Carousel: FC<CarouselProps> = props => {\n const { list } = props;\n\n const listRef = useRef<HTMLDivElement>(null);\n\n const scrollIterate = useCallback((func: (item: { position: number, size: number }) => number | undefined) => {\n const container = listRef.current;\n\n if (container) {\n const items = container.getElementsByClassName(\"xapp_search_carousel-item\");\n\n const containerRect = container.getBoundingClientRect();\n\n const length = items.length;\n\n for (let index = 0; index < length; index++) {\n const item = items.item(index);\n if (item) {\n const itemRect = item.getBoundingClientRect();\n const pos = itemRect.left - containerRect.left;\n const res = func({ position: pos, size: itemRect.width });\n if (res !== undefined) {\n container.scrollLeft += res;\n return;\n }\n }\n }\n }\n }, []);\n\n const handlePrev = useCallback(() => {\n let prevPos: undefined | number;\n scrollIterate(item => {\n const threshold = 10;\n if (item.position > -threshold) {\n return prevPos;\n }\n prevPos = item.position;\n return undefined;\n });\n }, [scrollIterate]);\n\n const handleNext = useCallback(() => {\n scrollIterate(item => {\n const threshold = 10;\n if (item.position > threshold) {\n return item.position;\n }\n return undefined;\n });\n }, [scrollIterate]);\n\n return (\n <div className={styles.xapp_search_carousel}>\n <IconButton icon={LeftAngleIcon} className={styles['xapp_search_carousel__prev']} onClick={handlePrev} />\n <div ref={listRef} className={styles['xapp_search_carousel__items']}>\n {list.items.map((item, index) => (\n <CarouselItem key={index} >\n <Card item={item} className={styles['xapp_search_carousel__content']} />\n </CarouselItem>\n ))}\n </div>\n <IconButton icon={RightAngleIcon} className={styles['xapp_search_carousel__next']} onClick={handleNext} />\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { List } from \"stentor-models\";\nimport { Carousel } from \"../Carousel\";\n\nexport interface SearchResponseCarouselDisplayProps {\n readonly carousel: List;\n}\n\nexport const SearchResponseCarouselDisplay: FC<SearchResponseCarouselDisplayProps> = props => {\n const { carousel } = props;\n return (\n <div>\n <Carousel list={carousel} />\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { List } from \"stentor-models\";\nimport { Card } from \"../Card\";\nimport styles from \"./Cards.module.scss\";\n\nexport interface CardsProps {\n readonly list: List;\n}\n\nexport const Cards: FC<CardsProps> = props => {\n const { list } = props;\n\n return (\n <div className={styles.xapp_search_cards}>\n {list.items.map((item, index) => (\n <Card key={index} item={item} />\n ))}\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { SuggestionsGroupHeading } from \"@xapp/chat-widget-core\";\nimport { List } from \"stentor-models\";\nimport { Cards } from \"../Cards\";\n\nexport interface SearchResponseListDisplayProps {\n readonly list: List;\n}\n\nexport const SearchResponseListDisplay: FC<SearchResponseListDisplayProps> = props => {\n const { list } = props;\n\n const title = list?.title;\n\n return (\n <div>\n {title ? <SuggestionsGroupHeading label={title} /> : <></>}\n\n <Cards list={list} />\n </div>\n );\n};\n","type BooleanMap = { [x: string]: boolean };\n\nexport const shallowEqualBooleanMap = (objA: BooleanMap, objB: BooleanMap): boolean => {\n // Get keys\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n\n // Check if number of keys is different\n if (keysA.length !== keysB.length) return false;\n\n // Check if keys or values are different\n for (const key of keysA) {\n if (objA[key] !== objB[key]) return false;\n }\n\n // If passed all checks, objects are considered shallowly equal\n return true;\n};\n\n/**\n *\n * @param input Prefix javascript variables in simple logical expression with \".this\"\n * @returns\n */\nexport const addContextPrefix = (input: string, prefix = \"this\", ignore: string[] = []): string => {\n const functionNames = ignore.map((fn) => fn.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")).join(\"|\");\n const pattern = new RegExp(\n `\\\\b(?<!')(?!(?:if|else|length|for|while|includes|function|var|let|const|return|switch|case|do|true|false|null|undefined|typeof|new|this|void|delete|in|instanceof|export|import${\n functionNames ? `|${functionNames}` : \"\"\n })\\\\b)([a-zA-Z_$][a-zA-Z0-9_$]*)\\\\b`,\n \"g\"\n );\n return input.replace(pattern, `${prefix}.$1`);\n};\n","// Matches the custom `#{key}` delimiter previously configured via lodash.template's\n// `interpolate` option. Only bare key lookups are supported (no expression evaluation)\n// since that is the only form used by templates in this codebase.\nconst TEMPLATE_REGEX = /#{([\\s\\S]+?)}/g;\n\nexport function replaceValues<T>(o: T, data: object): T {\n const values = data as Record<string, unknown>;\n try {\n const json = JSON.stringify(o).replace(TEMPLATE_REGEX, (_match, key) => {\n const trimmedKey = key.trim();\n if (!(trimmedKey in values)) {\n // Matches lodash.template's behavior of throwing when a key is\n // missing from the data object, which the outer catch turns into\n // \"leave the whole object unchanged\".\n throw new Error(`Missing template key \"${trimmedKey}\"`);\n }\n const value = values[trimmedKey];\n return value === null || value === undefined ? \"\" : String(value);\n });\n const escaped = json.replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\\\\r\").replace(/\\t/g, \"\\\\t\");\n return JSON.parse(escaped);\n } catch (error) {\n // Let it go\n // console.error(`Template replace failed: ${error}`);\n }\n\n return o;\n}\n\nfunction getOrdinalSuffix(number: number) {\n if (number >= 11 && number <= 13) {\n return 'th';\n }\n const lastDigit = number % 10;\n switch (lastDigit) {\n case 1:\n return 'st';\n case 2:\n return 'nd';\n case 3:\n return 'rd';\n default:\n return 'th';\n }\n }\n \n export function reformatDate(inputDate: string | number | Date) {\n const date = new Date(inputDate);\n const day = date.getDate();\n const month = date.toLocaleString('default', { month: 'long' });\n const year = date.getFullYear();\n const ordinalSuffix = getOrdinalSuffix(day);\n \n return `${month} ${day}${ordinalSuffix}, ${year}`;\n }\n \n export function joinWithAnd(arr: string[]) {\n if (arr.length === 0) {\n return '';\n } else if (arr.length === 1) {\n return arr[0];\n } else if (arr.length === 2) {\n return arr.join(' and ');\n } else {\n const lastElement = arr.pop(); // Remove the last element\n const joinedString = arr.join(', ') + ', and ' + lastElement;\n return joinedString;\n }\n }\n\n// Tests\n\n// const data = {\n// foo: 3,\n// d: new Date().toDateString(),\n// name: \"Joe Bloe\",\n// a: [\"x\", \"y\", \"z\"]\n// };\n\n// const T = {\n// // eslint-disable-next-line no-template-curly-in-string\n// x: \"${foo} ${a}\"\n// }\n\n// console.log(JSON.stringify(replaceValues(T, data)));","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||\"\").toLowerCase().replace(/s$/,\"\")},u:function(t){return void 0===t}},g=\"en\",D={};D[g]=M;var p=\"$isDayjsObject\",S=function(t){return t instanceof _||!(!t||!t[p])},w=function t(e,n,r){var i;if(!e)return g;if(\"string\"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split(\"-\");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<O(t)},m.$g=function(t,e,n){return b.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!b.u(e)||e,f=b.p(t),l=function(t,e){var i=b.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return b.w(n.toDate()[t].apply(n.toDate(\"s\"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v=\"set\"+(this.$u?\"UTC\":\"\");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+\"Hours\",0);case u:return $(v+\"Minutes\",1);case s:return $(v+\"Seconds\",2);case i:return $(v+\"Milliseconds\",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=b.p(t),f=\"set\"+(this.$u?\"UTC\":\"\"),l=(n={},n[a]=f+\"Date\",n[d]=f+\"Date\",n[c]=f+\"Month\",n[h]=f+\"FullYear\",n[u]=f+\"Hours\",n[s]=f+\"Minutes\",n[i]=f+\"Seconds\",n[r]=f+\"Milliseconds\",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[b.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=b.p(f),y=function(t){var e=O(l);return b.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return b.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||\"YYYY-MM-DDTHH:mm:ssZ\",i=b.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},d=function(t){return b.s(s%12||12,t,\"0\")},$=f||function(t,e,n){var r=t<12?\"AM\":\"PM\";return n?r.toLowerCase():r};return r.replace(y,(function(t,r){return r||function(t){switch(t){case\"YY\":return String(e.$y).slice(-2);case\"YYYY\":return b.s(e.$y,4,\"0\");case\"M\":return a+1;case\"MM\":return b.s(a+1,2,\"0\");case\"MMM\":return h(n.monthsShort,a,c,3);case\"MMMM\":return h(c,a);case\"D\":return e.$D;case\"DD\":return b.s(e.$D,2,\"0\");case\"d\":return String(e.$W);case\"dd\":return h(n.weekdaysMin,e.$W,o,2);case\"ddd\":return h(n.weekdaysShort,e.$W,o,3);case\"dddd\":return o[e.$W];case\"H\":return String(s);case\"HH\":return b.s(s,2,\"0\");case\"h\":return d(1);case\"hh\":return d(2);case\"a\":return $(s,u,!0);case\"A\":return $(s,u,!1);case\"m\":return String(u);case\"mm\":return b.s(u,2,\"0\");case\"s\":return String(e.$s);case\"ss\":return b.s(e.$s,2,\"0\");case\"SSS\":return b.s(e.$ms,3,\"0\");case\"Z\":return i}return null}(t)||i.replace(\":\",\"\")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=this,M=b.p(d),m=O(r),v=(m.utcOffset()-this.utcOffset())*e,g=this-m,D=function(){return b.m(y,m)};switch(M){case h:$=D()/12;break;case c:$=D();break;case f:$=D()/3;break;case o:$=(g-v)/6048e5;break;case a:$=(g-v)/864e5;break;case u:$=g/n;break;case s:$=g/e;break;case i:$=g/t;break;default:$=g}return l?$:b.a($)},m.daysInMonth=function(){return this.endOf(c).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=w(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return b.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),Y=_.prototype;return O.prototype=Y,[[\"$ms\",r],[\"$s\",i],[\"$m\",s],[\"$H\",u],[\"$W\",a],[\"$M\",c],[\"$y\",h],[\"$D\",d]].forEach((function(t){Y[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),O.extend=function(t,e){return t.$i||(t(e,_,O),t.$i=!0),O},O.locale=w,O.isDayjs=S,O.unix=function(t){return O(1e3*t)},O.en=D[g],O.Ls=D,O.p={},O}));","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_timezone=e()}(this,(function(){\"use strict\";var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,r){var o,a=function(t,n,i){void 0===i&&(i={});var r=new Date(t),o=function(t,n){void 0===n&&(n={});var i=n.timeZoneName||\"short\",r=t+\"|\"+i,o=e[r];return o||(o=new Intl.DateTimeFormat(\"en-US\",{hour12:!1,timeZone:t,year:\"numeric\",month:\"2-digit\",day:\"2-digit\",hour:\"2-digit\",minute:\"2-digit\",second:\"2-digit\",timeZoneName:i}),e[r]=o),o}(n,i);return o.formatToParts(r)},u=function(e,n){for(var i=a(e,n),o=[],u=0;u<i.length;u+=1){var f=i[u],s=f.type,m=f.value,c=t[s];c>=0&&(o[c]=parseInt(m,10))}var l=o[3],d=24===l?0:l,h=o[0]+\"-\"+o[1]+\"-\"+o[2]+\" \"+d+\":\"+o[4]+\":\"+o[5]+\":000\",v=+e;return(r.utc(h).valueOf()-(v-=v%1e3))/6e4},f=i.prototype;f.tz=function(t,e){if(void 0===t&&(t=o),!this.isValid())return this;var n,i=this.utcOffset(),a=this.toDate(),f=a.toLocaleString(\"en-US\",{timeZone:t}),s=u(+a,t);if(!Number(s))n=this.utcOffset(0,e);else if(n=r(f,{locale:this.$L}).$set(\"millisecond\",this.$ms).utcOffset(s,!0),e){var m=n.utcOffset();n=n.add(i-m,\"minute\")}return n.$x.$timezone=t,n},f.offsetName=function(t){var e=this.$x.$timezone||r.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find((function(t){return\"timezonename\"===t.type.toLowerCase()}));return n&&n.value};var s=f.startOf;f.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return s.call(this,t,e);var n=r(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\"),{locale:this.$L});return s.call(n,t,e).tz(this.$x.$timezone,!0)},r.tz=function(t,e,n){var i=n&&e,a=n||e||o,f=u(+r(),a);if(\"string\"!=typeof t)return r(t).tz(a);var s=r.utc(t,i).valueOf();if(Number.isNaN(s)){var m=r(NaN);return m.$x.$timezone=a,m}var c=function(t,e,n){var i=t-60*e*1e3,r=u(i,n);if(e===r)return[i,e];var o=u(i-=60*(r-e)*1e3,n);return r===o?[i,r]:[t-60*Math.min(r,o)*1e3,Math.max(r,o)]}(s,f,a),l=c[0],d=c[1],h=r(l).utcOffset(d);return h.$x.$timezone=a,h},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(t){o=t}}}));","!function(t,i){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=i():\"function\"==typeof define&&define.amd?define(i):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_utc=i()}(this,(function(){\"use strict\";var t=\"minute\",i=/[+-]\\d\\d(?::?\\d\\d)?/g,e=/([+-]|\\d\\d)/g;return function(s,f,n){var u=f.prototype;n.utc=function(t){var i={date:t,utc:!0,args:arguments};return new f(i)},u.utc=function(i){var e=n(this.toDate(),{locale:this.$L,utc:!0});return i?e.add(this.utcOffset(),t):e},u.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var r=u.parse;u.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),r.call(this,t)};var o=u.init;u.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else o.call(this)};var a=u.utcOffset;u.utcOffset=function(s,f){var n=this.$utils().u;if(n(s))return this.$u?0:n(this.$offset)?a.call(this):this.$offset;if(\"string\"==typeof s&&(s=function(t){void 0===t&&(t=\"\");var s=t.match(i);if(!s)return null;var f=(\"\"+s[0]).match(e)||[\"-\",0,0],n=f[0],u=60*+f[1]+ +f[2];return 0===u?0:\"+\"===n?u:-u}(s),null===s))return this;var u=Math.abs(s)<=16?60*s:s;if(0===u)return this.utc(f);var r=this.clone();if(f)return r.$offset=u,r.$u=!1,r;var o=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();return(r=this.local().add(u+o,t)).$offset=u,r.$x.$localOffset=o,r};var h=u.format;u.format=function(t){var i=t||(this.$u?\"YYYY-MM-DDTHH:mm:ss[Z]\":\"\");return h.call(this,i)},u.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},u.isUTC=function(){return!!this.$u},u.toISOString=function(){return this.toDate().toISOString()},u.toString=function(){return this.toDate().toUTCString()};var l=u.toDate;u.toDate=function(t){return\"s\"===t&&this.$offset?n(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\")).toDate():l.call(this)};var c=u.diff;u.diff=function(t,i,e){if(t&&this.$u===t.$u)return c.call(this,t,i,e);var s=this.local(),f=n(t).local();return c.call(s,f,i,e)}}}));","import dayjs from \"dayjs\";\nimport timezonePlugin from \"dayjs/plugin/timezone\";\nimport utcPlugin from \"dayjs/plugin/utc\";\n\nimport {\n ClockTime,\n DayOfWeek,\n FormDateTimeInput,\n ScheduleException,\n TimeOffering,\n TimeSlotSchedule,\n} from \"stentor-models\";\n\ndayjs.extend(utcPlugin);\ndayjs.extend(timezonePlugin);\n\n/**\n * Minutes between generated starts when the schedule does not say.\n */\nexport const DEFAULT_SLOT_MINUTES = 30;\n\n/**\n * How far ahead the calendar reaches when the schedule does not say.\n */\nexport const DEFAULT_HORIZON_DAYS = 60;\n\n/**\n * Field name the chosen date is submitted under when the field does not say.\n *\n * Deliberately fixed rather than derived from the field's own name: every existing lead\n * consumer already reads `preferred_date`, and namespacing it per field would break all of\n * them to solve a problem only a two-DATETIME step has. A step carrying two of these must\n * set `dateFieldName` on at least one, or the second silently overwrites the first.\n */\nexport const DEFAULT_DATE_FIELD_NAME = \"preferred_date\";\n\n/**\n * Field name the combined ISO timestamp is submitted under when the field does not say.\n *\n * Fixed for the same reason as {@link DEFAULT_DATE_FIELD_NAME}, and additionally because\n * `datetime` is the name the lead analyzer already recognises and ISO-validates. See\n * `dateTimeFieldName` to move it.\n */\nexport const DEFAULT_DATE_TIME_FIELD_NAME = \"datetime\";\n\n/**\n * Field name the schedule's timezone is submitted under when the field does not say.\n *\n * Fixed for the same reason as {@link DEFAULT_DATE_FIELD_NAME}. It exists so a consumer\n * can tell a picker-produced `datetime` from a scraped one: an abandoned form contributes\n * fields literally named `date` or `appointment_time` straight into the lead with no\n * validation, and \"carries an offset\" cannot say who produced the value. This can.\n */\nexport const DEFAULT_TIME_ZONE_FIELD_NAME = \"preferred_time_zone\";\n\n/**\n * `FormDateTimeInput` with the name its timezone field is submitted under.\n *\n * Declared here rather than read off the model because `timeZoneFieldName` is newer than\n * the `stentor-models` pinned by this package; it collapses back into `FormDateTimeInput`\n * once that version lands.\n */\nexport interface FormDateTimeInputWithTimeZone extends FormDateTimeInput {\n /**\n * Field name the schedule's IANA timezone is submitted under. Defaults to\n * \"preferred_time_zone\".\n */\n timeZoneFieldName?: string;\n}\n\nconst MS_PER_DAY = 86400000;\n\n/**\n * A fixed offset rather than a zone, e.g. \"-04:00\". Also catches a bare offset like \"-4\".\n */\nconst FIXED_OFFSET = /^[+-]?\\d/;\n\n/**\n * An arbitrary instant, only ever used to ask whether a zone identifier resolves at all.\n */\nconst ZONE_PROBE = \"2026-01-01T00:00\";\n\n// Indexed to match Date#getUTCDay().\nconst WEEKDAYS: DayOfWeek[] = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n];\n\nconst CLOCK_TIME = /^(\\d{1,2}):(\\d{2})/;\n\n/**\n * Minutes past midnight for a \"HH:MM\" clock time, or -1 for anything unparseable.\n *\n * A schedule is authored by hand in Studio, so a malformed time is a real possibility\n * and has to drop the span rather than generate slots at NaN.\n */\nfunction clockToMinutes(clock: ClockTime): number {\n const match = CLOCK_TIME.exec(clock || \"\");\n\n if (!match) {\n return -1;\n }\n\n const hours = Number(match[1]);\n const minutes = Number(match[2]);\n\n if (hours > 23 || minutes > 59) {\n return -1;\n }\n\n return hours * 60 + minutes;\n}\n\nfunction pad(value: number): string {\n return value < 10 ? `0${value}` : `${value}`;\n}\n\nfunction minutesToClock(minutes: number): ClockTime {\n // Past midnight wraps, so a duration that runs over the end of the day still reads\n // as a time rather than as \"24:30\".\n const wrapped = ((minutes % 1440) + 1440) % 1440;\n\n return `${pad(Math.floor(wrapped / 60))}:${pad(wrapped % 60)}`;\n}\n\n/**\n * The calendar date a `Date` represents, as \"YYYY-MM-DD\".\n *\n * Read off the local fields rather than through `toISOString`, which converts to UTC and\n * so reports the next day for an evening selection anywhere west of Greenwich.\n */\nexport function toCalendarDate(date: Date): string {\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n}\n\n/**\n * The weekday a \"YYYY-MM-DD\" calendar date falls on.\n */\nfunction weekdayOf(calendarDate: string): DayOfWeek | undefined {\n const parsed = new Date(`${calendarDate}T00:00:00Z`);\n\n return isNaN(parsed.getTime()) ? undefined : WEEKDAYS[parsed.getUTCDay()];\n}\n\n/**\n * Whole days from one calendar date to another, ignoring time of day entirely - so a\n * daylight-saving transition in between cannot make the answer come out fractional.\n */\nfunction daysBetween(from: string, to: string): number {\n return Math.round(\n (Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / MS_PER_DAY\n );\n}\n\n/**\n * Whether a zone can actually be used to place a wall-clock time.\n *\n * A schedule's zone is typed in by hand in Studio, so \"Eastern\" or \"America/New York\"\n * reaches the picker as readily as a real IANA identifier does. Matching is case\n * insensitive, so \"America/New_york\" is fine.\n */\nexport function isUsableTimezone(timezone?: string): boolean {\n if (!timezone) {\n return false;\n }\n\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n\n return true;\n } catch (err) {\n return false;\n }\n}\n\n/**\n * The zone the visitor's own browser is in, or \"\" where that cannot be determined.\n */\nexport function hostTimezone(): string {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"\";\n } catch (err) {\n return \"\";\n }\n}\n\n// Generic first, so a zone reads as \"Eastern Time\" rather than as whichever side of a\n// daylight-saving transition today happens to fall on - the times below it span both.\n// \"long\" is the fallback for a platform too old to know the generic form.\nconst TIMEZONE_NAME_STYLES = [\"longGeneric\", \"long\"];\n\n/**\n * A zone named the way a visitor reads it, e.g. \"America/New_York\" to \"Eastern Time\".\n *\n * Falls back to the identifier itself rather than to nothing, because an unnamed zone\n * still tells a visitor more than silence does.\n */\nexport function formatTimezoneLabel(timezone?: string): string {\n if (!timezone) {\n return \"\";\n }\n\n for (const timeZoneName of TIMEZONE_NAME_STYLES) {\n try {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n timeZoneName,\n } as Intl.DateTimeFormatOptions).formatToParts(new Date());\n const named = parts.find((part) => part.type === \"timeZoneName\");\n\n if (named && named.value) {\n return named.value;\n }\n } catch (err) {\n // Either the zone or the naming style is unsupported here. Try the next\n // style, then give up on naming it at all.\n }\n }\n\n return timezone;\n}\n\n/**\n * The instant a wall-clock time on a calendar date happens, in the schedule's zone.\n *\n * An unknown zone falls back to the host's, because a picker that renders slightly wrong\n * times is better than one that throws while the visitor is looking at it.\n */\nfunction zonedInstant(calendarDate: string, clock: ClockTime, timezone: string): number {\n const local = `${calendarDate}T${clock}`;\n\n try {\n return dayjs.tz(local, timezone).valueOf();\n } catch (err) {\n return dayjs(local).valueOf();\n }\n}\n\n/**\n * An offset-bearing ISO 8601 timestamp for a wall-clock time in the given zone, e.g.\n * \"2026-08-24T09:30:00-04:00\". The offset is the one in force on that date, so the value\n * survives a daylight-saving transition.\n */\nexport function toOffsetIso(calendarDate: string, clock: ClockTime, timezone: string): string {\n const minutes = clockToMinutes(clock);\n const normalized = minutes < 0 ? clock : minutesToClock(minutes);\n const local = `${calendarDate}T${normalized}`;\n\n try {\n return dayjs.tz(local, timezone).format();\n } catch (err) {\n return dayjs(local).format();\n }\n}\n\n/**\n * The zone the picker really built its times in, as the IANA identifier the schedule\n * authored - or nothing at all when it did not.\n *\n * {@link zonedInstant} and {@link toOffsetIso} both fall back to the host's zone rather\n * than throwing at a visitor mid-form, so an absent or unrecognised `timezone` still\n * produces a full column of times: they are simply the wrong ones. Naming the business's\n * zone beside those would hand a consumer a marker it cannot trust, and a wrong marker is\n * worse than none - the entire point of the field is that it can be trusted - so nothing\n * is reported instead.\n *\n * A fixed offset is refused for the same reason. `Intl` accepts \"-04:00\", so the times\n * generated from it are self-consistent, but an offset does not survive a daylight-saving\n * transition and so cannot stand in for the zone.\n */\nexport function timeZoneOf(schedule: TimeSlotSchedule): string | undefined {\n const timezone = schedule?.timezone;\n\n if (!timezone || typeof timezone !== \"string\" || FIXED_OFFSET.test(timezone)) {\n return undefined;\n }\n\n try {\n // The same call zonedInstant makes, so the two cannot disagree about which zones\n // are usable and the marker cannot outlive the fallback it is meant to detect.\n if (!dayjs.tz(ZONE_PROBE, timezone).isValid()) {\n return undefined;\n }\n } catch (err) {\n return undefined;\n }\n\n return timezone;\n}\n\n/**\n * A 12-hour rendering of a clock time, e.g. \"09:30\" to \"9:30 AM\".\n */\nfunction formatClock(clock: ClockTime): string {\n const minutes = clockToMinutes(clock);\n\n if (minutes < 0) {\n return clock;\n }\n\n const hours24 = Math.floor(minutes / 60);\n const hours12 = hours24 % 12 === 0 ? 12 : hours24 % 12;\n\n return `${hours12}:${pad(minutes % 60)} ${hours24 < 12 ? \"AM\" : \"PM\"}`;\n}\n\n/**\n * What an offering reads as in the time column - and, because the label is what the field\n * submits, what a CRM or lead consumer receives for it.\n */\nexport function formatOfferingLabel(offering: TimeOffering): string {\n if (!offering) {\n return \"\";\n }\n\n if (offering.label) {\n return offering.label;\n }\n\n const start = formatClock(offering.start);\n\n return offering.end ? `${start} - ${formatClock(offering.end)}` : start;\n}\n\n/**\n * How far ahead the calendar reaches, so the picker's own maxDate and the selectability\n * rules cannot drift apart.\n */\nexport function horizonDaysOf(schedule: TimeSlotSchedule): number {\n const horizon = schedule?.horizonDays;\n\n // 0 is a real answer here - \"today only\" - unlike slotMinutes or durationMinutes where\n // it is meaningless. Testing truthiness handed a same-day-only business the 60 day\n // default instead, which is the opposite of what they asked for.\n return typeof horizon === \"number\" && horizon >= 0 ? horizon : DEFAULT_HORIZON_DAYS;\n}\n\n/**\n * The open booking windows a CRM reported, per calendar date (\"YYYY-MM-DD\"), as wall-clock\n * times in the schedule's zone.\n *\n * Arrives as `offeringsByDate` on the BusyDays context. When present it is the whole truth\n * about which dates are open: a date absent from it, or mapped to an empty list, is closed.\n */\nexport interface OfferingsByDate {\n readonly [date: string]: readonly TimeOffering[];\n}\n\nfunction isOffering(value: unknown): value is TimeOffering {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as TimeOffering).start === \"string\"\n );\n}\n\n/**\n * Narrow the untyped `offeringsByDate` context parameter into a map the picker can trust.\n *\n * Context parameters are typed as strings but carry whatever the handler put there, so an\n * object and its JSON serialisation are both accepted. Entries without a `start` are dropped,\n * and a date whose value is not a list reads as closed rather than as \"use the schedule\".\n *\n * @param raw The parameter exactly as it came off the context.\n */\nexport function parseOfferingsByDate(raw: unknown): OfferingsByDate | undefined {\n let value = raw;\n\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch (err) {\n return undefined;\n }\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const map: { [date: string]: TimeOffering[] } = {};\n\n Object.entries(value as Record<string, unknown>).forEach(([date, offerings]) => {\n map[date] = Array.isArray(offerings) ? offerings.filter(isOffering) : [];\n });\n\n return map;\n}\n\nfunction findException(\n schedule: TimeSlotSchedule,\n calendarDate: string\n): ScheduleException | undefined {\n return (schedule.exceptions || []).find((exception) => exception.date === calendarDate);\n}\n\n/**\n * Drop the offerings that have already passed, measured in the schedule's zone rather than\n * the visitor's.\n *\n * A time earlier today is never bookable, whether or not the schedule sets a lead time —\n * `leadTimeMinutes` pushes the cutoff further out, it does not create it. Treating lead time\n * as the only mechanism let a schedule that omitted it offer 9:00 AM at 3 in the afternoon.\n */\nfunction filterElapsed(\n offerings: TimeOffering[],\n schedule: TimeSlotSchedule,\n calendarDate: string,\n now: Date\n): TimeOffering[] {\n const lead = schedule.leadTimeMinutes;\n const buffer = lead && lead > 0 ? lead : 0;\n const cutoff = now.getTime() + buffer * 60000;\n\n return offerings.filter(\n (offering) => zonedInstant(calendarDate, offering.start, schedule.timezone) >= cutoff\n );\n}\n\n/**\n * The times a schedule offers on one calendar date.\n *\n * Slots come from the schedule alone - there is no availability lookup behind this, so a\n * date change repaints the column without a round trip. The rules, in order:\n *\n * 1. `offerings` present replaces generation. `days`, `slotMinutes` and `durationMinutes`\n * are not consulted. A closing exception still closes the date, because that is the\n * only way a fixed offering list can express a holiday.\n * 2. Otherwise the weekday's spans, or the spans of an `exceptions` entry for this exact\n * date, which *replace* the weekday's rather than adding to them. No spans is closed.\n * 3. Each span is walked in `slotMinutes` steps, up to but not including its end.\n * 4. `durationMinutes` gives every offering an `end`; without it they are discrete starts.\n * A start whose appointment would run past the span's end is not offered at all.\n * 5. Whatever survives is filtered against now, plus `leadTimeMinutes` if the schedule\n * sets one. A time earlier today is never offered.\n *\n * `offeringsByDate`, when given, comes before all of these: the date's entry is offered as\n * is, and a date without one is closed. Only the elapsed filter of rule 5 still applies.\n *\n * @param schedule The schedule to read.\n * @param date The calendar day being offered, read off its local fields.\n * @param now The current moment. Injectable so the lead-time filter is testable.\n * @param offeringsByDate The CRM's own windows per date, replacing the schedule's.\n */\nexport function generateOfferings(\n schedule: TimeSlotSchedule,\n date: Date,\n now: Date = new Date(),\n offeringsByDate?: OfferingsByDate\n): TimeOffering[] {\n if (!schedule || !date || isNaN(date.getTime())) {\n return [];\n }\n\n const calendarDate = toCalendarDate(date);\n\n if (offeringsByDate) {\n return filterElapsed([...(offeringsByDate[calendarDate] || [])], schedule, calendarDate, now);\n }\n const exception = findException(schedule, calendarDate);\n\n if (Array.isArray(schedule.offerings)) {\n // No spans reads as closed here exactly as it does on the generated path below.\n // `spans` is required by the type, but a schedule is authored in Studio and arrives\n // as config, so `{ date: \"2026-12-25\" }` used as a holiday marker has to close the\n // date rather than quietly fall through to the normal offerings.\n if (exception && (!exception.spans || exception.spans.length === 0)) {\n return [];\n }\n\n return filterElapsed(schedule.offerings, schedule, calendarDate, now);\n }\n\n const weekday = weekdayOf(calendarDate);\n const spans = exception\n ? exception.spans || []\n : (weekday && (schedule.days || {})[weekday]) || [];\n\n const step =\n schedule.slotMinutes && schedule.slotMinutes > 0\n ? schedule.slotMinutes\n : DEFAULT_SLOT_MINUTES;\n const duration =\n schedule.durationMinutes && schedule.durationMinutes > 0\n ? schedule.durationMinutes\n : undefined;\n\n const offerings: TimeOffering[] = [];\n\n for (const span of spans) {\n const start = clockToMinutes(span?.start);\n const end = clockToMinutes(span?.end);\n\n if (start < 0 || end < 0) {\n continue;\n }\n\n for (let minutes = start; minutes < end; minutes += step) {\n // The whole appointment has to fit inside the span, which is what Calendly does:\n // 9:00-12:00 at 60 minutes offers 11:00 last, never 11:30. Clipping the end\n // instead would keep the slot but advertise a length the business is not open\n // for, and a span exists precisely to protect what follows it - a lunch break,\n // or closing time.\n if (duration && minutes + duration > end) {\n break;\n }\n\n const offering: TimeOffering = { start: minutesToClock(minutes) };\n\n if (duration) {\n offering.end = minutesToClock(minutes + duration);\n }\n\n offerings.push(offering);\n }\n }\n\n return filterElapsed(offerings, schedule, calendarDate, now);\n}\n\n/**\n * Whether the calendar should let a date be picked.\n *\n * False for anything outside the horizon - in the past, or further ahead than\n * `horizonDays` - and for any date the schedule generates no offerings for, so a closed\n * day greys out rather than opening onto an empty column.\n *\n * @param schedule The schedule to read.\n * @param date The calendar day being tested, read off its local fields.\n * @param now The current moment. Injectable so the horizon is testable.\n * @param offeringsByDate The CRM's own windows per date, see {@link generateOfferings}.\n */\nexport function isDateSelectable(\n schedule: TimeSlotSchedule,\n date: Date,\n now: Date = new Date(),\n offeringsByDate?: OfferingsByDate\n): boolean {\n if (!schedule || !date || isNaN(date.getTime())) {\n return false;\n }\n\n const calendarDate = toCalendarDate(date);\n const horizon = horizonDaysOf(schedule);\n\n // Today is the business's today, not the visitor's - they are frequently different days.\n const today = todayInZone(schedule.timezone, now);\n const offset = daysBetween(today, calendarDate);\n\n if (offset < 0 || offset > horizon) {\n return false;\n }\n\n return generateOfferings(schedule, date, now, offeringsByDate).length > 0;\n}\n\n/**\n * The soonest day the calendar would let someone pick, or nothing.\n *\n * Deliberately expressed as a walk over {@link isDateSelectable} rather than by\n * reasoning about the schedule's shape: the answer must be a day the calendar\n * itself would enable, and duplicating that rule is how the two drift into\n * offering a date that then greys out.\n *\n * Bounded by the schedule's own horizon, so an empty schedule -- or one whose\n * every remaining day is full -- terminates and returns undefined rather than\n * searching forever.\n *\n * @param schedule The schedule to read.\n * @param now The current moment. Injectable so the horizon is testable.\n * @param isBusy Days the CRM has declared full, tested one at a time.\n * @param offeringsByDate The CRM's own windows per date, see {@link generateOfferings}.\n */\nexport function firstSelectableDate(\n schedule: TimeSlotSchedule,\n now: Date = new Date(),\n isBusy: (date: Date) => boolean = () => false,\n offeringsByDate?: OfferingsByDate\n): Date | undefined {\n if (!schedule) {\n return undefined;\n }\n\n // From the business's today, not the visitor's -- frequently a different day,\n // and starting from the wrong one can skip a day that is still bookable.\n const today = todayInZone(schedule.timezone, now);\n\n for (let offset = 0; offset <= horizonDaysOf(schedule); offset++) {\n const day = dayjs(`${today}T00:00:00`).add(offset, \"day\").toDate();\n\n if (isDateSelectable(schedule, day, now, offeringsByDate) && !isBusy(day)) {\n return day;\n }\n }\n\n return undefined;\n}\n\n/**\n * The calendar date it currently is in the given zone.\n */\nfunction todayInZone(timezone: string, now: Date): string {\n try {\n return dayjs(now).tz(timezone).format(\"YYYY-MM-DD\");\n } catch (err) {\n return toCalendarDate(now);\n }\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport { err } from \".\";\n\n/**\n * Shape of the `externalWidget` block on a booking-handoff form step.\n *\n * This mirrors `FormStepExternalWidget[\"externalWidget\"]` from\n * `stentor-models@1.75.0`. See the local type-extension note in\n * `FormStepDisplay.tsx` for why it is redeclared here instead of imported.\n */\nexport interface ExternalWidgetConfig {\n anchorId: string;\n scriptSrc: string;\n configGlobal: string;\n config: Record<string, string | number | boolean>;\n successCallbackKey?: string;\n cacheBust?: boolean;\n renderTimeoutMs?: number;\n fallbackStep?: string;\n}\n\nexport type ExternalWidgetOutcome = \"pending\" | \"rendered\" | \"no_render\" | \"error\";\n\nexport interface UseExternalWidgetOptions {\n /**\n * Fired once the anchor renders a bookable `#step-*` (any step other than a\n * no-match or loading step, e.g. `step-schedule` or the returning-visitor\n * `step-review`).\n */\n onRendered?: (provider: string) => void;\n /**\n * Fired when the anchor renders a no-match step (no coverage), or stays empty\n * with no `#step-loading` past the backstop `renderTimeoutMs`.\n */\n onNoRender?: (provider: string) => void;\n /**\n * Fired at most once per mounted handoff, the first time the partner script invokes\n * the configured success callback. Later invocations within the same handoff are\n * suppressed, reported to the console and counted (see `suppressedScheduledCount`)\n * -- CostGuide confirmed (2026-08-13) that it fires \"whenever an appointment gets\n * scheduled\", so a single handoff can produce more than one fire and a duplicate\n * dispatch double-counts the booking downstream.\n *\n * Suppression is deliberately NOT its own analytics event: a new eventType needs a\n * matching server-side eventName mapping in stentor-api, which is out of scope here.\n * The console error is the signal that works today in a visitor's browser, and\n * `suppressedScheduledCount` is there for a caller that wants to act on it.\n *\n * `payload` is whatever (if anything) the partner passes to it. CostGuide passes\n * nothing today -- it is a bare trigger with no appointment id, time or contractor --\n * but the parameter is kept tolerant in case that changes.\n */\n onScheduled?: (provider: string, payload?: unknown) => void;\n /**\n * Fired when the script fails to load, or the scriptSrc is rejected.\n */\n onError?: (provider: string) => void;\n /**\n * Fired alongside onNoRender/onError when `externalWidget.fallbackStep` is set,\n * so the caller can navigate there. Not fired when fallbackStep is unset --\n * the caller is expected to render an inline fallback message instead.\n */\n onFallback?: (fallbackStep: string) => void;\n}\n\nconst DEFAULT_RENDER_TIMEOUT_MS = 8000;\n\n// The partner form renders exactly one `#step-*` container at a time with stable\n// ids, so the step id -- not a blind \"anchor has children\" check -- is the render\n// signal. Render timing was measured at 111ms-18.7s against the same endpoint, so\n// a fixed timer can only ever be a backstop for \"the script never arrived\".\nconst LOADING_STEP_ID = \"step-loading\";\nconst NO_MATCH_STEP_IDS = [\n \"step-nomatch\",\n \"step-nomatchaggregator\",\n \"step-no-match-financing\",\n \"step-payPerCallNoneAvailable\",\n];\n// While the anchor still shows `#step-loading` at timeout we extend rather than\n// fail (the 18.7s worst case would otherwise dead-end a homeowner after we already\n// took their details). Bounded so a stuck loader eventually settles as no_render.\nconst MAX_RENDER_TIMEOUT_EXTENSIONS = 3;\n\ntype AnchorState = \"rendered\" | \"no_coverage\" | \"loading\" | \"empty\";\n\n/**\n * Classifies the current state of the anchor from the partner step id it shows.\n *\n * - a no-match step id -> \"no_coverage\" (a real screen, but no bookable coverage)\n * - `step-loading` -> \"loading\" (still working; do not fail yet)\n * - any other `step-*` -> \"rendered\" (e.g. `step-schedule`, or the\n * returning-visitor `step-review` -- do NOT assume one)\n * - no `step-*` present -> \"empty\" (not rendered yet)\n */\nexport function classifyAnchor(anchor: HTMLElement): AnchorState {\n const stepEls = anchor.querySelectorAll('[id^=\"step-\"]');\n if (stepEls.length === 0) {\n return \"empty\";\n }\n let hasLoading = false;\n for (let i = 0; i < stepEls.length; i++) {\n const id = stepEls[i].id;\n if (NO_MATCH_STEP_IDS.indexOf(id) !== -1) {\n return \"no_coverage\";\n }\n if (id === LOADING_STEP_ID) {\n hasLoading = true;\n continue;\n }\n return \"rendered\";\n }\n return hasLoading ? \"loading\" : \"empty\";\n}\n\n/**\n * Derives the analytics `provider` string from the partner script's hostname.\n */\nexport function getExternalWidgetProvider(scriptSrc: string | undefined): string {\n if (!scriptSrc) {\n return \"unknown\";\n }\n try {\n return new URL(scriptSrc).hostname;\n } catch {\n return \"unknown\";\n }\n}\n\nfunction isValidScriptSrc(scriptSrc: string): boolean {\n try {\n const parsed = new URL(scriptSrc);\n return parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n}\n\n// Scripts are appended to document.body and never removed. A module-level guard\n// (mirroring useTrustedForm's existingScript check) ensures the same partner\n// origin is only loaded once per page, even across separate mounted instances.\nconst SCRIPT_ORIGIN_ATTRIBUTE = \"data-xapp-external-widget-origin\";\n\n/**\n * Drives the mount sequence for a third-party booking-widget handoff step:\n * assigns the merged config to `window[configGlobal]` (including the wired-up\n * success callback), appends the partner's embed script, and watches the\n * anchor for a render-timeout outcome.\n *\n * The mount sequence runs at most once per component lifetime (guarded by a\n * ref) the first time `externalWidget` is defined. If the config object is\n * later replaced with a new reference (e.g. a slower FORM_SUBMIT response\n * merging server values in after the step already rendered), the global is\n * re-assigned with the latest values but the script is not re-appended and\n * the timer is not restarted.\n */\nexport function useExternalWidget(\n externalWidget: ExternalWidgetConfig | undefined,\n options: UseExternalWidgetOptions = {}\n): { outcome: ExternalWidgetOutcome; suppressedScheduledCount: number } {\n // onScheduled is read from optionsRef inside the mount effect (so a late\n // callback change is picked up without re-running the effect), not destructured here.\n const { onRendered, onNoRender, onError, onFallback } = options;\n\n const [outcome, setOutcome] = useState<ExternalWidgetOutcome>(\"pending\");\n // Repeats are suppressed, not discarded: if the partner starts firing twice for every\n // booking we want that visible rather than merely harmless.\n const [suppressedScheduledCount, setSuppressedScheduledCount] = useState(0);\n\n const hasMountedRef = useRef(false);\n // Per mounted handoff, so a genuine re-mount (the visitor returns and books again) is a\n // new handoff and may fire again. Survives a refreshed config replacing the global.\n const scheduledFiredRef = useRef(false);\n const suppressedScheduledRef = useRef(0);\n const outcomeSettledRef = useRef(false);\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!externalWidget) {\n return undefined;\n }\n\n const provider = getExternalWidgetProvider(externalWidget.scriptSrc);\n\n // Config may be refreshed (e.g. by a merged FORM_SUBMIT response) on a later\n // render of the same mounted step -- keep the global current either way.\n const globalConfig: Record<string, unknown> = { ...externalWidget.config };\n if (externalWidget.successCallbackKey) {\n const successCallbackKey = externalWidget.successCallbackKey;\n globalConfig[successCallbackKey] = (payload?: unknown) => {\n if (scheduledFiredRef.current) {\n suppressedScheduledRef.current += 1;\n // err, NOT log: `log` is gated on window.xaLogLevel === \"debug\", which no\n // visitor's browser sets, so a repeat in the wild would be invisible -- the\n // opposite of the point. A partner firing its success hook twice for one\n // booking is an anomaly worth a console error, the same treatment this hook\n // already gives a rejected script origin and a failed script load.\n err(\n `[ExternalWidget] Suppressed repeat ${successCallbackKey} fire ` +\n `#${suppressedScheduledRef.current} from ${provider}`,\n payload\n );\n setSuppressedScheduledCount(suppressedScheduledRef.current);\n return;\n }\n scheduledFiredRef.current = true;\n optionsRef.current.onScheduled?.(provider, payload);\n };\n }\n (window as unknown as Record<string, unknown>)[externalWidget.configGlobal] = globalConfig;\n\n if (hasMountedRef.current) {\n return undefined;\n }\n hasMountedRef.current = true;\n\n const settle = (nextOutcome: ExternalWidgetOutcome, notify: (() => void) | undefined) => {\n if (outcomeSettledRef.current) {\n return;\n }\n outcomeSettledRef.current = true;\n setOutcome(nextOutcome);\n notify?.();\n if (nextOutcome !== \"rendered\" && externalWidget.fallbackStep) {\n onFallback?.(externalWidget.fallbackStep);\n }\n };\n\n if (!isValidScriptSrc(externalWidget.scriptSrc)) {\n err(\n `[ExternalWidget] Rejected script URL from unexpected origin: ${externalWidget.scriptSrc}`\n );\n settle(\"error\", () => onError?.(provider));\n return undefined;\n }\n\n const anchor = document.getElementById(externalWidget.anchorId);\n const timeoutMs = externalWidget.renderTimeoutMs ?? DEFAULT_RENDER_TIMEOUT_MS;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let observer: MutationObserver | undefined;\n let extensions = 0;\n\n const handleRendered = () => settle(\"rendered\", () => onRendered?.(provider));\n const handleNoRender = () => settle(\"no_render\", () => onNoRender?.(provider));\n\n // Settle on a decisive step id. Returns true once the outcome is settled.\n const evaluate = (el: HTMLElement | null): boolean => {\n if (!el) {\n return false;\n }\n const state = classifyAnchor(el);\n if (state === \"rendered\") {\n handleRendered();\n return true;\n }\n if (state === \"no_coverage\") {\n handleNoRender();\n return true;\n }\n return false; // \"loading\" | \"empty\" -> keep waiting\n };\n\n const onTimeout = () => {\n if (outcomeSettledRef.current) {\n return;\n }\n const currentAnchor = document.getElementById(externalWidget.anchorId);\n if (evaluate(currentAnchor)) {\n return;\n }\n // Still loading? Extend rather than declare a false no-render.\n if (\n currentAnchor &&\n classifyAnchor(currentAnchor) === \"loading\" &&\n extensions < MAX_RENDER_TIMEOUT_EXTENSIONS\n ) {\n extensions += 1;\n timeoutId = setTimeout(onTimeout, timeoutMs);\n return;\n }\n // Empty past the backstop (or stuck loading) -> hard failure.\n handleNoRender();\n };\n\n const settledOnMount = evaluate(anchor);\n if (!settledOnMount) {\n if (anchor) {\n observer = new MutationObserver(() => {\n evaluate(document.getElementById(externalWidget.anchorId));\n });\n observer.observe(anchor, { childList: true, subtree: true });\n }\n timeoutId = setTimeout(onTimeout, timeoutMs);\n }\n\n let origin: string;\n try {\n origin = new URL(externalWidget.scriptSrc).origin;\n } catch {\n origin = externalWidget.scriptSrc;\n }\n\n const existingScript = document.querySelector(\n `script[${SCRIPT_ORIGIN_ATTRIBUTE}=\"${origin}\"]`\n );\n\n if (!existingScript) {\n const script = document.createElement(\"script\");\n script.src = externalWidget.cacheBust\n ? `${externalWidget.scriptSrc}${\n externalWidget.scriptSrc.includes(\"?\") ? \"&\" : \"?\"\n }v=${Date.now()}`\n : externalWidget.scriptSrc;\n script.setAttribute(SCRIPT_ORIGIN_ATTRIBUTE, origin);\n script.onerror = () => {\n err(`[ExternalWidget] Failed to load script: ${externalWidget.scriptSrc}`);\n settle(\"error\", () => onError?.(provider));\n };\n // Intentionally no cleanup on unmount -- mirrors useTrustedForm.\n document.body.appendChild(script);\n }\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n observer?.disconnect();\n };\n // Only the identity of externalWidget should re-trigger the mount sequence;\n // the notify callbacks are read from optionsRef to avoid re-running on every\n // parent re-render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [externalWidget]);\n\n return { outcome, suppressedScheduledCount };\n}\n","import React, { FC, useEffect, useId, useState } from \"react\";\nimport { FormSelectInput } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\nimport { CheckBoxIcon, CheckBoxOutlineIcon, RadioCheckedIcon, RadioUncheckedIcon } from \"../icons\";\n\nimport styles from \"./FormFieldSelect.module.scss\";\n\nexport interface FormSelectProps extends FormFieldProps {\n readonly field: Styleable<FormSelectInput>;\n}\n\nexport const FormFieldSelect: FC<FormSelectProps> = (props) => {\n const { field, onFieldChange, errorMessage } = props;\n\n const [selectValue, setSelectValue] = useState<string[]>([]); // array for checkboxes\n const [radioValue, setRadioValue] = useState<string>(\"\"); // single value for radio\n\n const onCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const { name, checked } = e.target;\n setSelectValue((prevOptions) => {\n if (checked) {\n return [...prevOptions, name];\n } else {\n return prevOptions.filter((option) => option !== name);\n }\n });\n };\n\n const onRadioChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n setRadioValue(e.target.value);\n };\n\n const id = `xapp-select-${useId()}`;\n const titleId = `${id}-title`;\n const helperId = `${id}-helper-text`;\n const invalid = !!errorMessage;\n\n useEffect(() => {\n if (field.radio) {\n onFieldChange(field.name, radioValue ? [radioValue] : []);\n } else {\n onFieldChange(field.name, selectValue);\n }\n }, [selectValue, radioValue, field.name, field.radio, onFieldChange]);\n\n return (\n <div style={{ ...field.style }}>\n <div\n className={`${styles.xapp_select_title_container}${!field.title ? \"__empty\" : \"\"}`}>\n <p id={titleId}>{field.title}</p>\n </div>\n\n {/* Native radios sharing one name get arrow-key movement and single selection from\n the browser; the group names them by the step's question. */}\n <div\n className={styles.xapp_select_container}\n role={field.radio ? \"radiogroup\" : \"group\"}\n // A radio cannot carry aria-invalid; its group can. Checkboxes carry their own.\n aria-invalid={(field.radio && invalid) || undefined}\n aria-labelledby={field.title ? titleId : undefined}\n aria-describedby={invalid ? helperId : undefined}>\n {field.items.map((item) => {\n const checked = field.radio ? radioValue === item.id : selectValue.includes(item.id);\n const Icon = field.radio\n ? checked\n ? RadioCheckedIcon\n : RadioUncheckedIcon\n : checked\n ? CheckBoxIcon\n : CheckBoxOutlineIcon;\n\n return (\n <label key={item.id} className={styles.xapp_select_option}>\n <span\n className={`${styles.xapp_checkbox_select} ${\n checked ? styles.xapp_checkbox_select_checked : \"\"\n }`}>\n {field.radio ? (\n <input\n type=\"radio\"\n className={styles.xapp_select_input}\n name={field.name}\n value={item.id}\n checked={checked}\n onChange={onRadioChange}\n />\n ) : (\n <input\n type=\"checkbox\"\n className={styles.xapp_select_input}\n name={item.id}\n checked={checked}\n onChange={onCheckboxChange}\n aria-invalid={invalid || undefined}\n />\n )}\n <Icon className={styles.xapp_select_icon} />\n </span>\n <span className={styles.xapp_select_label}>{item.label}</span>\n </label>\n );\n })}\n </div>\n\n {errorMessage && (\n <p id={helperId} className={styles.xapp_select_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n );\n};\n\nexport default FormFieldSelect;\n","import React, { FC } from \"react\";\n\nimport { FormCardInput } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport styles from \"./FormFieldCard.module.scss\";\n\nexport interface FormCardProps extends FormFieldProps {\n readonly field: Styleable<FormCardInput>;\n}\n\n/**\n * The element each text variant renders as -- MUI Typography's default variant mapping, which\n * this card used until #1741. The variant's look comes from FormFieldCard.module.scss.\n */\nconst VARIANT_ELEMENTS: Record<string, \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\" | \"p\" | \"span\"> = {\n h1: \"h1\",\n h2: \"h2\",\n h3: \"h3\",\n h4: \"h4\",\n h5: \"h5\",\n h6: \"h6\",\n subtitle1: \"h6\",\n subtitle2: \"h6\",\n body1: \"p\",\n body2: \"p\",\n inherit: \"p\",\n button: \"span\",\n caption: \"span\",\n overline: \"span\",\n};\n\nconst DEFAULT_VARIANT = \"body2\";\n\n/**\n * Typography's palette shorthands, at the default MUI theme's values. Anything else is taken\n * to be a CSS colour and passed straight through, as Typography did.\n */\nconst PALETTE_COLORS: Record<string, string> = {\n primary: \"#1976d2\",\n secondary: \"#9c27b0\",\n error: \"#d32f2f\",\n warning: \"#ed6c02\",\n info: \"#0288d1\",\n success: \"#2e7d32\",\n textPrimary: \"rgba(0, 0, 0, 0.87)\",\n textSecondary: \"rgba(0, 0, 0, 0.6)\",\n textDisabled: \"rgba(0, 0, 0, 0.38)\",\n \"text.primary\": \"rgba(0, 0, 0, 0.87)\",\n \"text.secondary\": \"rgba(0, 0, 0, 0.6)\",\n \"text.disabled\": \"rgba(0, 0, 0, 0.38)\",\n};\n\nconst DEFAULT_COLOR = \"textSecondary\";\n\nfunction resolveColor(color: string): string {\n return PALETTE_COLORS[color] || color;\n}\n\nexport const FormFieldCard: FC<FormCardProps> = (props) => {\n const { field } = props;\n\n const variant = field.variant && VARIANT_ELEMENTS[field.variant] ? field.variant : DEFAULT_VARIANT;\n const Text = VARIANT_ELEMENTS[variant];\n\n return (\n <div className={styles.xapp_form_card}>\n <div className={styles.xapp_form_card_body}>\n {field.header && (\n <div className={styles.xapp_form_card_header}>\n <span className={styles.xapp_form_card_header_title}>{field.header.title}</span>\n {field.header.subheader && (\n <span className={styles.xapp_form_card_header_subheader}>{field.header.subheader}</span>\n )}\n </div>\n )}\n\n {field.media && (\n <img\n className={styles.xapp_form_card_media}\n src={field.media.imageUrl}\n alt={field.media.alt}\n height={field.media.height}\n width={field.media.width}\n />\n )}\n\n {field.text && (\n <div className={styles.xapp_form_card_content}>\n <Text\n className={`${styles.xapp_form_card_text} ${styles[`xapp_form_card_text_${variant}`] || \"\"}`}\n data-variant={variant}\n style={{\n whiteSpace: \"pre-line\",\n textAlign: (field.align || \"center\") as React.CSSProperties[\"textAlign\"],\n color: resolveColor(field.color || DEFAULT_COLOR),\n ...field.style,\n }}>\n {field.text}\n </Text>\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default FormFieldCard;\n","import React, { FC, useEffect, useId, useState } from \"react\";\n\nimport { FormChipsInput, ActionableItem, SelectableItem } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\nimport { CheckIcon } from \"../icons\";\n\nimport styles from \"./FormFieldChips.module.scss\";\n\nexport function isSelectableItem(item: ActionableItem | SelectableItem): item is SelectableItem {\n return !!item && !(item as ActionableItem).url;\n}\n\nexport function isActionableItem(item: ActionableItem | SelectableItem): item is ActionableItem {\n return !!(item as ActionableItem).url;\n}\n\nexport interface FormFieldChipsProps extends FormFieldProps {\n readonly field: Styleable<FormChipsInput>;\n /** Optional prefilled value that takes precedence over items' selected state.\n * Only used for initial mount; late-arriving updates (after mount) are not supported. */\n readonly value?: string[];\n}\n\nexport const FormFieldChips: FC<FormFieldChipsProps> = (props) => {\n const { field, onFieldChange, errorMessage, value } = props;\n\n /**\n * Selected chips\n */\n // Use prefilled value if provided, otherwise look for pre-selected items\n const selectedFromProps = value || props.field.items\n .filter(isSelectableItem) // filter out actionable items\n .filter((item) => item.selected)\n .map((item) => item.id);\n const [selectedChips, setSelectedChips] = useState<string[]>(selectedFromProps); // array!\n\n const handleChipClick = (id: string) => {\n const checked = selectedChips.includes(id);\n\n if (field.radio) {\n setSelectedChips((_prevOptions) => {\n if (!checked) {\n return [id]; // add\n } else {\n return []; // delete\n }\n });\n } else {\n setSelectedChips((prevOptions) => {\n if (!checked) {\n return [...prevOptions, id]; // add\n } else {\n return prevOptions.filter((option) => option !== id); // delete\n }\n });\n }\n };\n\n const id = `xapp-chips-${useId()}`;\n const titleId = `${id}-title`;\n const helperId = `${id}-helper-text`;\n\n useEffect(() => {\n if (typeof onFieldChange === \"function\") {\n onFieldChange(field.name, selectedChips);\n }\n }, [selectedChips, field.name, onFieldChange]);\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignContent: \"center\",\n alignItems: \"center\",\n }}>\n <div\n className={`${styles.xapp_chips_title_container}${!field.title ? \"__empty\" : \"\"}`}\n style={{ ...field.style }}>\n <p id={titleId}>{field.title}</p>\n </div>\n\n <div\n className={styles.xapp_chips_container}\n role=\"group\"\n aria-labelledby={field.title ? titleId : undefined}\n aria-describedby={errorMessage ? helperId : undefined}>\n {field.items.map((item, index) => {\n const selected = selectedChips.includes(item.id);\n const className = `${styles.xapp_checkbox_chip} ${selected ? styles.xapp_chip_clicked : \"\"}`;\n const content = (\n <>\n {selected && <CheckIcon className={styles.xapp_chip_icon} />}\n <span className={styles.xapp_chip_label}>{item.label}</span>\n </>\n );\n\n if (isSelectableItem(item)) {\n return (\n <div key={index} className={styles.xapp_chip_wrapper}>\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => handleChipClick(item.id)}\n className={className}>\n {content}\n </button>\n </div>\n );\n } else if (isActionableItem(item)) {\n return (\n <div key={index} className={styles.xapp_chip_wrapper}>\n <a href={item.url} className={`${className} ${styles.xapp_chip_link}`}>\n {content}\n </a>\n </div>\n );\n } else {\n return <></>;\n }\n })}\n </div>\n\n {errorMessage && (\n <p id={helperId} className={styles.xapp_chips_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n );\n};\n\nexport default FormFieldChips;\n","import { FormTextInput } from \"stentor-models\";\n\n/**\n * The HTML input helper attributes we derive for a form field.\n *\n * These are what give mobile users the right keyboard and let iOS/Android\n * AutoFill offer the right saved value - neither happens without explicit tokens.\n */\nexport interface InputHelperProps {\n /**\n * The real HTML input type. Note this is NOT FormInput.type, which is the\n * widget discriminator (\"TEXT\" | \"DROPDOWN\" | ...) and is not a valid input type.\n */\n readonly type: \"text\" | \"tel\" | \"email\";\n readonly inputMode: \"text\" | \"tel\" | \"email\" | \"numeric\";\n /**\n * Left off entirely when we cannot confidently pick a token - a wrong\n * autocomplete is worse than none.\n */\n readonly autoComplete?: string;\n readonly enterKeyHint: \"next\" | \"done\";\n}\n\nexport interface FormatToInputPropsRequest {\n readonly format?: FormTextInput[\"format\"];\n readonly name?: string;\n /**\n * When true the keyboard shows \"done\" rather than \"next\".\n */\n readonly isLastField?: boolean;\n}\n\ntype FormatMapping = Omit<InputHelperProps, \"enterKeyHint\">;\n\nconst FORMAT_PROPS: Record<NonNullable<FormTextInput[\"format\"]>, FormatMapping> = {\n PHONE: { type: \"tel\", inputMode: \"tel\", autoComplete: \"tel\" },\n EMAIL: { type: \"email\", inputMode: \"email\", autoComplete: \"email\" },\n // Deliberately not type=\"number\" - that adds spinners and strips the leading\n // zero from real US postal codes such as 02134.\n ZIP_CODE: { type: \"text\", inputMode: \"numeric\", autoComplete: \"postal-code\" },\n ADDRESS: { type: \"text\", inputMode: \"text\", autoComplete: \"street-address\" },\n};\n\nconst DEFAULT_PROPS: FormatMapping = { type: \"text\", inputMode: \"text\" };\n\n/**\n * Field names we can map to an autocomplete token without guessing. Keys are\n * normalized - lowercased with everything but letters and digits removed - so\n * \"FULL_NAME\", \"fullName\" and \"full name\" all land on the same entry.\n *\n * Keep this conservative. Anything ambiguous belongs on field.format instead.\n */\nconst NAME_AUTOCOMPLETE: Record<string, string> = {\n name: \"name\",\n fullname: \"name\",\n yourname: \"name\",\n customername: \"name\",\n contactname: \"name\",\n firstname: \"given-name\",\n fname: \"given-name\",\n givenname: \"given-name\",\n lastname: \"family-name\",\n lname: \"family-name\",\n surname: \"family-name\",\n familyname: \"family-name\",\n email: \"email\",\n emailaddress: \"email\",\n phone: \"tel\",\n phonenumber: \"tel\",\n telephone: \"tel\",\n tel: \"tel\",\n mobile: \"tel\",\n mobilephone: \"tel\",\n cellphone: \"tel\",\n zip: \"postal-code\",\n zipcode: \"postal-code\",\n postalcode: \"postal-code\",\n postcode: \"postal-code\",\n address: \"street-address\",\n streetaddress: \"street-address\",\n street: \"street-address\",\n city: \"address-level2\",\n town: \"address-level2\",\n state: \"address-level1\",\n province: \"address-level1\",\n company: \"organization\",\n companyname: \"organization\",\n organization: \"organization\",\n business: \"organization\",\n businessname: \"organization\",\n};\n\nfunction autoCompleteFromName(name?: string): string | undefined {\n if (!name) {\n return undefined;\n }\n\n return NAME_AUTOCOMPLETE[name.toLowerCase().replace(/[^a-z0-9]/g, \"\")];\n}\n\n/**\n * Derive the mobile input helper attributes for a text field.\n *\n * `field.format` carries the real semantics (\"PHONE\", \"ZIP_CODE\", ...); when it\n * is unset we fall back to plain text and only infer autoComplete from the field\n * name where that is unambiguous.\n */\nexport function formatToInputProps(request: FormatToInputPropsRequest): InputHelperProps {\n const { format, name, isLastField } = request;\n\n const mapped = format ? FORMAT_PROPS[format] : undefined;\n const enterKeyHint = isLastField ? \"done\" : \"next\";\n\n if (mapped) {\n return { ...mapped, enterKeyHint };\n }\n\n const autoComplete = autoCompleteFromName(name);\n\n return autoComplete\n ? { ...DEFAULT_PROPS, autoComplete, enterKeyHint }\n : { ...DEFAULT_PROPS, enterKeyHint };\n}\n\nexport default formatToInputProps;\n","import React, { FC, useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\n\nimport { FormTextInput } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\nimport { formatToInputProps } from \"../../utils/formatToInputProps\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport styles from \"./FormFieldTextInput.module.scss\";\n\nexport interface FormTextInputProps extends FormFieldProps {\n readonly field: Styleable<FormTextInput>;\n readonly value?: string | undefined;\n /**\n * When this is the last field of the step the keyboard shows \"done\" rather than \"next\".\n */\n readonly isLastField?: boolean;\n}\n\n// Show counter when within this percentage of the limit\nconst COUNTER_THRESHOLD_PERCENT = 0.8;\n\nexport const FormFieldTextInput: FC<FormTextInputProps> = (props) => {\n const { field, onFieldChange, value, errorMessage, required, isLastField } = props;\n\n const [text, setText] = useState(value || \"\");\n const [focused, setFocused] = useState(false);\n\n const id = `xapp-text-${useId()}`;\n const helperId = `${id}-helper-text`;\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const { value } = e.target;\n setText(value);\n };\n\n useEffect(() => {\n onFieldChange(field.name, text);\n }, [field.name, onFieldChange, text]);\n\n useEffect(() => {\n setText(value || \"\");\n }, [value]);\n\n // A multiline field with no fixed `rows` grows with its content up to `rowsMax`, the way the\n // MUI textarea it replaces did. Fixed `rows` is left to the browser.\n const autosize = !!field.multiline && !field.rows;\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!autosize || !textarea) {\n return;\n }\n textarea.style.height = \"auto\";\n const lineHeight = parseFloat(getComputedStyle(textarea).lineHeight) || 0;\n const maxHeight = field.rowsMax && lineHeight ? lineHeight * field.rowsMax : Infinity;\n const next = Math.min(textarea.scrollHeight, maxHeight);\n if (next > 0) {\n textarea.style.height = `${next}px`;\n }\n }, [autosize, field.rowsMax, text]);\n\n const maxLength = field.maxLength;\n const currentLength = text.length;\n const isAtLimit = maxLength !== undefined && currentLength >= maxLength;\n const showCounter = maxLength !== undefined && currentLength >= maxLength * COUNTER_THRESHOLD_PERCENT;\n\n // field.type is the widget discriminator (\"TEXT\" | \"DROPDOWN\" | ...), not an HTML\n // input type - the real semantics live on field.format.\n const { type, ...inputHelpers } = formatToInputProps({\n format: field.format,\n name: field.name,\n isLastField,\n });\n\n // MUI's floating label: resting inside the field until it is focused or has a value. With no\n // label to collide with, the placeholder is always shown.\n const shrink = focused || text.length > 0 || !field.label;\n\n const controlProps = {\n ...inputHelpers,\n id,\n name: field.name,\n className: styles.xapp_text_input_control,\n placeholder: field.placeholder,\n value: text,\n onChange,\n onFocus: () => setFocused(true),\n onBlur: () => setFocused(false),\n required,\n maxLength: field.maxLength || undefined,\n \"aria-invalid\": !!errorMessage,\n \"aria-describedby\": errorMessage ? helperId : undefined,\n // Read by the stylesheet, which hides the placeholder behind a resting label.\n \"data-shrink\": shrink ? \"true\" : \"false\",\n };\n\n return (\n <div className={styles.xapp_text_input_container}>\n {field.title && (\n <div className={styles[\"xapp_text_input_container__title\"]}>\n <p>{field.title}</p>\n </div>\n )}\n\n <div className={styles[\"xapp_text_input_container__field\"]}>\n <div\n className={`${styles.xapp_text_input_text} ${errorMessage ? styles.xapp_text_input_error : \"\"}`}\n style={field.style}>\n <div\n className={`${styles.xapp_text_input_root} ${focused ? styles.xapp_text_input_focused : \"\"} ${\n field.multiline ? styles.xapp_text_input_multiline : \"\"\n }`}>\n {field.label && (\n <label\n htmlFor={id}\n className={styles.xapp_text_input_label}\n data-shrink={shrink ? \"true\" : \"false\"}>\n {field.label}\n {required && (\n <span className={styles.xapp_text_input_asterisk} aria-hidden=\"true\">\n {\" *\"}\n </span>\n )}\n </label>\n )}\n {field.multiline ? (\n <textarea {...controlProps} ref={textareaRef} rows={field.rows || 1} />\n ) : (\n <input {...controlProps} type={type} />\n )}\n </div>\n {errorMessage && (\n <p id={helperId} className={styles.xapp_text_input_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n {showCounter && (\n <div className={`${styles.xapp_text_input_counter} ${isAtLimit ? styles[\"xapp_text_input_counter--limit\"] : \"\"}`}>\n {currentLength}/{maxLength}\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default FormFieldTextInput;\n","import React, { FC, useEffect, useRef, useState } from \"react\";\n\nimport { FormDropdownInput } from \"stentor-models\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\nimport { ArrowDropDownIcon } from \"../icons\";\n\nimport styles from \"./FormFieldDropdown.module.scss\";\n\nconst PLACEHOLDER_LABEL = \"Select an option\";\n\n/**\n * Extended SelectableItem interface to support free-form text input for dropdown items.\n * This allows dropdown options to trigger an additional text input field when selected.\n *\n * Note: This extends the stentor-models SelectableItem type with additional properties.\n * Consider adding these properties to stentor-models SelectableItem in a future release\n * if this pattern becomes widely used across the platform.\n */\nexport interface SelectableItemWithFreeForm {\n label: string;\n id: string;\n selected?: boolean;\n /**\n * If true, shows a free-form text input field when this item is selected.\n * Useful for \"Other\" options that require additional user input.\n */\n freeFormInput?: boolean;\n /**\n * Custom field name for the free-form input value.\n * Defaults to \"message\" if not specified.\n * This allows multiple dropdowns to have different free-form field names.\n */\n freeFormFieldName?: string;\n}\n\nexport interface FormDropdownProps extends FormFieldProps {\n readonly field: FormDropdownInput;\n}\n\nexport const FormFieldDropdown: FC<FormDropdownProps> = (props) => {\n const { field, onFieldChange, errorMessage, required, freeFormErrorMessage } = props;\n\n const helperId = `${field.name}-helper-text`;\n const freeFormId = `${field.name}-free-form`;\n const freeFormHelperId = `${freeFormId}-helper-text`;\n\n const [dropValue, setDropValue] = useState(() => {\n const selectedItem = field.items.find(item => item.selected);\n return selectedItem?.id || \"none\";\n });\n const [freeFormValue, setFreeFormValue] = useState(\"\");\n const [showFreeForm, setShowFreeForm] = useState(() => {\n const selectedItem = field.items.find(item => item.selected) as SelectableItemWithFreeForm;\n return selectedItem?.freeFormInput || false;\n });\n\n const onChange = (e: React.ChangeEvent<HTMLSelectElement>) => {\n const { value } = e.target;\n\n // Get the previous selected item to clear its free-form value if needed\n const prevSelectedItem = field.items.find(\n (item) => item.id === dropValue\n ) as SelectableItemWithFreeForm;\n\n setDropValue(value);\n\n // Check if the selected item has freeFormInput enabled\n const selectedItem = field.items.find(\n (item) => item.id === value\n ) as SelectableItemWithFreeForm;\n if (selectedItem && selectedItem.freeFormInput) {\n setShowFreeForm(true);\n } else {\n setShowFreeForm(false);\n\n // Only clear if switching away from a free-form item AND there was actually a value\n if (prevSelectedItem?.freeFormInput && freeFormValue) {\n const messageFieldName = prevSelectedItem?.freeFormFieldName || \"message\";\n setFreeFormValue(\"\"); // Clear local state\n onFieldChange(messageFieldName, \"\"); // Clear parent state\n }\n }\n };\n\n const onFreeFormChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n setFreeFormValue(e.target.value);\n };\n\n // Track onFieldChange reference to detect if it's not memoized in development\n const onFieldChangeRef = useRef(onFieldChange);\n useEffect(() => {\n if (process.env.NODE_ENV === \"development\" && onFieldChangeRef.current !== onFieldChange) {\n console.warn(\n \"FormFieldDropdown: onFieldChange prop is not memoized. \" +\n \"This may cause performance issues. Please wrap it in useCallback in the parent component.\"\n );\n }\n onFieldChangeRef.current = onFieldChange;\n }, [onFieldChange]);\n\n // Get the current free-form field name if applicable\n const currentFreeFormFieldName = React.useMemo(() => {\n if (showFreeForm) {\n const selectedItem = field.items.find(\n (item) => item.id === dropValue\n ) as SelectableItemWithFreeForm;\n return selectedItem?.freeFormFieldName || \"message\";\n }\n return null;\n }, [showFreeForm, dropValue, field.items]);\n\n // IMPORTANT: Parent components MUST use useCallback for onFieldChange\n // to prevent infinite re-renders. See FormStepDisplay.tsx:352-373 for correct usage.\n useEffect(() => {\n // Send the raw dropdown ID value (formatting happens during text interpolation)\n if (dropValue !== \"none\") {\n onFieldChange(field.name, dropValue);\n }\n\n // If freeform is active and has a value, also send it to the configured field name\n if (showFreeForm && freeFormValue && currentFreeFormFieldName) {\n onFieldChange(currentFreeFormFieldName, freeFormValue);\n }\n }, [dropValue, freeFormValue, showFreeForm, field.name, currentFreeFormFieldName, onFieldChange]);\n\n // A native <select> at every width. Mobile already had it -- the OS wheel/sheet picker,\n // momentum scrolling, no focus trap inside the fixed modal -- and desktop now gets the same\n // control in place of MUI's listbox (#1741). The outline and floating label are drawn to\n // match the outlined MUI field it replaces.\n return (\n <div className={styles.xapp_dropdown_container}>\n <div className={`${styles.xapp_dropdown_control} ${errorMessage ? styles.xapp_dropdown_error : \"\"}`}>\n <label htmlFor={field.name} className={styles.xapp_dropdown_label}>\n {field.title}\n {required && <span aria-hidden=\"true\">{\" *\"}</span>}\n </label>\n <select\n className={styles.xapp_dropdown_select}\n name={field.name}\n id={field.name}\n value={dropValue}\n onChange={onChange}\n required={required}\n aria-invalid={!!errorMessage}\n aria-describedby={errorMessage ? helperId : undefined}>\n <option value=\"none\">{PLACEHOLDER_LABEL}</option>\n {field.items.map((item) => (\n <option key={item.id} value={item.id}>\n {item.label}\n </option>\n ))}\n </select>\n <ArrowDropDownIcon className={styles.xapp_dropdown_arrow} />\n <fieldset aria-hidden=\"true\" className={styles.xapp_dropdown_outline}>\n <legend>\n <span>\n {field.title}\n {required && \" *\"}\n </span>\n </legend>\n </fieldset>\n </div>\n {errorMessage && (\n <p id={helperId} className={styles.xapp_dropdown_helper}>\n {errorMessage}\n </p>\n )}\n\n {showFreeForm && (\n <div className={styles.xapp_dropdown_free_form}>\n <input\n type=\"text\"\n id={freeFormId}\n className={`${styles.xapp_dropdown_free_form_input} ${\n freeFormErrorMessage ? styles.xapp_dropdown_error : \"\"\n }`}\n required\n placeholder=\"Please specify\"\n aria-label=\"Please specify\"\n value={freeFormValue}\n onChange={onFreeFormChange}\n maxLength={field.maxLength || undefined}\n aria-invalid={!!freeFormErrorMessage}\n aria-describedby={freeFormErrorMessage ? freeFormHelperId : undefined}\n />\n {freeFormErrorMessage && (\n <p id={freeFormHelperId} className={styles.xapp_dropdown_helper}>\n {freeFormErrorMessage}\n </p>\n )}\n </div>\n )}\n </div>\n );\n};\n\nexport default FormFieldDropdown;\n","import React, {\n FC,\n KeyboardEvent,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport dayjs, { Dayjs } from \"dayjs\";\n\nimport { ChevronLeftIcon, ChevronRightIcon } from \"../icons/FieldIcons\";\n\nimport styles from \"./Calendar.module.scss\";\n\n/**\n * Extra classes for the calendar's parts, so a field can restyle them from its own stylesheet.\n */\nexport interface CalendarClasses {\n readonly header?: string;\n readonly weekday?: string;\n readonly weeks?: string;\n readonly day?: string;\n readonly daySelected?: string;\n readonly dayToday?: string;\n}\n\nexport interface CalendarProps {\n /**\n * The selected day, if any.\n */\n readonly value?: Dayjs | null;\n /**\n * Called with the picked day, at the start of that day in local time.\n */\n readonly onChange: (day: Dayjs) => void;\n /**\n * Whether a day can not be picked. Days before `minDate` and after `maxDate` are\n * already excluded and never reach this.\n */\n readonly shouldDisableDate?: (day: Dayjs) => boolean;\n /**\n * The first day that can be picked. The previous-month arrow stops at its month.\n */\n readonly minDate?: Dayjs;\n /**\n * The last day that can be picked. The next-month arrow stops at its month.\n */\n readonly maxDate?: Dayjs;\n /**\n * The day marked as today. Injectable so a caller that is handed its own \"now\" marks\n * the same day it judges availability against. Defaults to the real clock.\n */\n readonly today?: Dayjs;\n /**\n * The month to open on when there is no value. Defaults to today's.\n */\n readonly referenceDate?: Dayjs;\n /**\n * Availability is still being fetched: the days are replaced by a skeleton.\n */\n readonly loading?: boolean;\n /**\n * Draw the neighbouring months' days in the leading and trailing weeks instead of\n * leaving those cells blank.\n */\n readonly showDaysOutsideCurrentMonth?: boolean;\n /**\n * Always draw this many weeks, padding with the following month's, so the calendar\n * does not change height between months.\n */\n readonly fixedWeekNumber?: number;\n /**\n * An extra class for a day, on top of the calendar's own.\n */\n readonly getDayClassName?: (day: Dayjs, disabled: boolean) => string | undefined;\n readonly classes?: CalendarClasses;\n readonly className?: string;\n}\n\n/**\n * The longest a keyboard search walks looking for a day that can be picked, so a calendar\n * with nothing available can never loop.\n */\nconst SEARCH_LIMIT_DAYS = 366;\n\nconst FULL_DATE_FORMAT = \"dddd, MMMM D, YYYY\";\n\nfunction classNames(...names: (string | false | undefined)[]): string {\n return names.filter((name) => !!name).join(\" \");\n}\n\n/**\n * The weeks drawn for a month, Sunday first, padded with the following month's weeks up\n * to `fixedWeekNumber`.\n */\nfunction weeksOf(month: Dayjs, fixedWeekNumber?: number): Dayjs[][] {\n const first = month.startOf(\"month\");\n const weeksInMonth = Math.ceil((first.day() + first.daysInMonth()) / 7);\n const count = Math.max(weeksInMonth, fixedWeekNumber || 0);\n const start = first.startOf(\"week\");\n\n return Array.from({ length: count }, (_, week) =>\n Array.from({ length: 7 }, (__, day) => start.add(week * 7 + day, \"day\"))\n );\n}\n\n/**\n * A month grid of days in the ARIA grid pattern, replacing @mui/x-date-pickers' DateCalendar\n * (#1745).\n *\n * One day is in the tab order at a time; the arrow keys move between days, skipping any that\n * can not be picked, Page Up and Page Down move a month, and Home and End go to the start and\n * end of the week. Each day is named by its full date, so a screen reader announces \"Monday,\n * August 24, 2026\" rather than \"24\".\n */\nexport const Calendar: FC<CalendarProps> = (props) => {\n const {\n value,\n onChange,\n shouldDisableDate,\n minDate,\n maxDate,\n referenceDate,\n loading,\n showDaysOutsideCurrentMonth,\n fixedWeekNumber,\n getDayClassName,\n classes = {},\n className,\n } = props;\n\n const today = useMemo(\n () => (props.today || dayjs()).startOf(\"day\"),\n // Keyed on the day, so a caller handing down a fresh object each render is not a change.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [props.today ? props.today.format(\"YYYY-MM-DD\") : undefined]\n );\n\n const labelId = useId();\n const gridRef = useRef<HTMLDivElement>(null);\n // Set when the keyboard moves the focused day, so the effect below moves real focus to it.\n const focusOnRender = useRef(false);\n\n const [month, setMonth] = useState<Dayjs>(() =>\n (value || referenceDate || today).startOf(\"month\")\n );\n const [focusedDay, setFocusedDay] = useState<Dayjs>(() => (value || today).startOf(\"day\"));\n\n // A value set from outside -- a resumed selection, a preselected date -- brings its month\n // into view, as MUI's calendar did.\n const valueKey = value ? value.format(\"YYYY-MM-DD\") : undefined;\n useEffect(() => {\n if (!value) {\n return;\n }\n\n setFocusedDay(value.startOf(\"day\"));\n setMonth((current) => (value.isSame(current, \"month\") ? current : value.startOf(\"month\")));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [valueKey]);\n\n const isOutOfRange = useCallback(\n (day: Dayjs): boolean =>\n (!!minDate && day.isBefore(minDate, \"day\")) ||\n (!!maxDate && day.isAfter(maxDate, \"day\")),\n [minDate, maxDate]\n );\n\n const isDisabled = useCallback(\n (day: Dayjs): boolean =>\n isOutOfRange(day) || (!!shouldDisableDate && shouldDisableDate(day)),\n [isOutOfRange, shouldDisableDate]\n );\n\n /**\n * The nearest day to `target` between `from` and `to` inclusive that can be picked.\n */\n const closestEnabled = useCallback(\n (target: Dayjs, from: Dayjs, to: Dayjs): Dayjs | undefined => {\n const clamped = target.isBefore(from, \"day\")\n ? from\n : target.isAfter(to, \"day\")\n ? to\n : target;\n const span = to.diff(from, \"day\");\n\n for (let offset = 0; offset <= span; offset++) {\n for (const candidate of [clamped.add(-offset, \"day\"), clamped.add(offset, \"day\")]) {\n if (\n !candidate.isBefore(from, \"day\") &&\n !candidate.isAfter(to, \"day\") &&\n !isDisabled(candidate)\n ) {\n return candidate;\n }\n }\n }\n\n return undefined;\n },\n [isDisabled]\n );\n\n // The one day in the tab order: the focused day when it is in view and can be picked,\n // otherwise the nearest one in this month that can.\n const tabbableDay = useMemo(() => {\n if (focusedDay.isSame(month, \"month\") && !isDisabled(focusedDay)) {\n return focusedDay;\n }\n\n return closestEnabled(\n focusedDay,\n month.startOf(\"month\"),\n month.endOf(\"month\").startOf(\"day\")\n );\n }, [focusedDay, month, isDisabled, closestEnabled]);\n\n useEffect(() => {\n if (!focusOnRender.current) {\n return;\n }\n focusOnRender.current = false;\n\n const timestamp = String(focusedDay.valueOf());\n const target = gridRef.current?.querySelector<HTMLElement>(\n `[data-timestamp=\"${timestamp}\"]`\n );\n target?.focus();\n }, [focusedDay, month]);\n\n const moveFocus = (day: Dayjs) => {\n focusOnRender.current = true;\n setFocusedDay(day);\n if (!day.isSame(month, \"month\")) {\n setMonth(day.startOf(\"month\"));\n }\n };\n\n /** Walk from `day` in steps of `delta` days to the first one that can be picked. */\n const step = (day: Dayjs, delta: number): Dayjs | undefined => {\n let candidate = day;\n\n for (let walked = 0; walked < SEARCH_LIMIT_DAYS; walked += Math.abs(delta)) {\n candidate = candidate.add(delta, \"day\");\n if (isOutOfRange(candidate)) {\n return undefined;\n }\n if (!isDisabled(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n };\n\n /** The first day that can be picked walking from `from` towards `to`, inclusive. */\n const scan = (from: Dayjs, to: Dayjs): Dayjs | undefined => {\n const direction = to.isBefore(from, \"day\") ? -1 : 1;\n const span = Math.abs(to.diff(from, \"day\"));\n\n for (let offset = 0; offset <= span; offset++) {\n const candidate = from.add(offset * direction, \"day\");\n if (!isDisabled(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n };\n\n /** The same day of the month `delta` months away, or the nearest day there that can be picked. */\n const monthJump = (day: Dayjs, delta: number): Dayjs | undefined => {\n const target = day.add(delta, \"month\");\n return closestEnabled(\n target,\n target.startOf(\"month\"),\n target.endOf(\"month\").startOf(\"day\")\n );\n };\n\n const onDayKeyDown = (event: KeyboardEvent<HTMLButtonElement>, day: Dayjs) => {\n let next: Dayjs | undefined;\n\n switch (event.key) {\n case \"ArrowLeft\":\n next = step(day, -1);\n break;\n case \"ArrowRight\":\n next = step(day, 1);\n break;\n case \"ArrowUp\":\n next = step(day, -7);\n break;\n case \"ArrowDown\":\n next = step(day, 7);\n break;\n case \"Home\":\n case \"End\": {\n let edge =\n event.key === \"Home\" ? day.startOf(\"week\") : day.endOf(\"week\").startOf(\"day\");\n // With the neighbouring months' days left blank, the week ends at the month's edge.\n if (!showDaysOutsideCurrentMonth && !edge.isSame(day, \"month\")) {\n edge =\n event.key === \"Home\"\n ? day.startOf(\"month\")\n : day.endOf(\"month\").startOf(\"day\");\n }\n next = scan(edge, day);\n break;\n }\n case \"PageUp\":\n next = monthJump(day, -1);\n break;\n case \"PageDown\":\n next = monthJump(day, 1);\n break;\n default:\n return;\n }\n\n event.preventDefault();\n\n if (next && !next.isSame(day, \"day\")) {\n moveFocus(next);\n }\n };\n\n const onDayClick = (day: Dayjs) => {\n setFocusedDay(day);\n if (!day.isSame(month, \"month\")) {\n setMonth(day.startOf(\"month\"));\n }\n onChange(day);\n };\n\n const previousDisabled = !!minDate && !month.isAfter(minDate, \"month\");\n const nextDisabled = !!maxDate && !month.isBefore(maxDate, \"month\");\n\n const weeks = useMemo(() => weeksOf(month, fixedWeekNumber), [month, fixedWeekNumber]);\n const weekdays = weeks[0];\n\n return (\n <div className={classNames(styles.xapp_calendar, className)} data-xapp-calendar=\"\">\n <div className={classNames(styles.xapp_calendar_header, classes.header)}>\n <span aria-live=\"polite\" className={styles.xapp_calendar_label} id={labelId}>\n {month.format(\"MMMM YYYY\")}\n </span>\n <div className={styles.xapp_calendar_nav}>\n <button\n aria-label=\"Previous month\"\n className={styles.xapp_calendar_nav_button}\n disabled={previousDisabled}\n onClick={() => setMonth(month.add(-1, \"month\"))}\n type=\"button\"\n >\n <ChevronLeftIcon />\n </button>\n <button\n aria-label=\"Next month\"\n className={styles.xapp_calendar_nav_button}\n disabled={nextDisabled}\n onClick={() => setMonth(month.add(1, \"month\"))}\n type=\"button\"\n >\n <ChevronRightIcon />\n </button>\n </div>\n </div>\n\n <div\n aria-busy={loading ? true : undefined}\n aria-labelledby={labelId}\n ref={gridRef}\n role=\"grid\"\n >\n <div className={styles.xapp_calendar_week} role=\"row\">\n {weekdays.map((day) => (\n <span\n aria-label={day.format(\"dddd\")}\n className={classNames(styles.xapp_calendar_weekday, classes.weekday)}\n key={day.day()}\n role=\"columnheader\"\n >\n {day.format(\"dd\").charAt(0)}\n </span>\n ))}\n </div>\n\n {loading ? (\n <div aria-hidden=\"true\" className={styles.xapp_calendar_skeleton}>\n {weeks.map((week, row) => (\n <div className={styles.xapp_calendar_week} key={row}>\n {week.map((day) => (\n <span\n className={styles.xapp_calendar_skeleton_day}\n key={day.valueOf()}\n />\n ))}\n </div>\n ))}\n </div>\n ) : (\n <div\n className={classNames(styles.xapp_calendar_weeks, classes.weeks)}\n role=\"rowgroup\"\n >\n {weeks.map((week, row) => (\n <div className={styles.xapp_calendar_week} key={row} role=\"row\">\n {week.map((day) => {\n const outside = !day.isSame(month, \"month\");\n\n if (outside && !showDaysOutsideCurrentMonth) {\n return (\n <span\n className={styles.xapp_calendar_filler}\n key={day.valueOf()}\n role=\"gridcell\"\n />\n );\n }\n\n const disabled = isDisabled(day);\n const selected = !!value && day.isSame(value, \"day\");\n const isToday = day.isSame(today, \"day\");\n\n return (\n <button\n aria-current={isToday ? \"date\" : undefined}\n aria-label={day.format(FULL_DATE_FORMAT)}\n aria-selected={selected}\n className={classNames(\n styles.xapp_calendar_day,\n classes.day,\n selected && styles.xapp_calendar_day_selected,\n selected && classes.daySelected,\n isToday && styles.xapp_calendar_day_today,\n isToday && classes.dayToday,\n outside && styles.xapp_calendar_day_outside,\n getDayClassName && getDayClassName(day, disabled)\n )}\n data-timestamp={day.valueOf()}\n disabled={disabled}\n key={day.valueOf()}\n onClick={() => onDayClick(day)}\n onKeyDown={(event) => onDayKeyDown(event, day)}\n role=\"gridcell\"\n tabIndex={\n !!tabbableDay && day.isSame(tabbableDay, \"day\")\n ? 0\n : -1\n }\n type=\"button\"\n >\n {day.date()}\n </button>\n );\n })}\n </div>\n ))}\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default Calendar;\n","import { Dayjs } from \"dayjs\";\n\n/**\n * The days an FSM/CRM has declared full.\n *\n * They reach the widget as one comma delimited string on a channel action response -\n * never on the initial render - and each entry is either a \"YYYY-MM-DD\" date, a weekday\n * name as `dddd` formats it (\"Saturday\"), or either of those with `*` standing in for any\n * run of characters (\"2026-08-*\").\n */\n\n/**\n * Split what the channel sent into the entries to match against.\n *\n * Reports `undefined` rather than an empty array when nothing has arrived, so a caller\n * can tell \"no availability information yet\" from \"nothing is busy\".\n *\n * @param busyDays The comma delimited list, as the channel sends it.\n */\nexport function parseBusyDays(busyDays?: string): string[] | undefined {\n if (!busyDays) {\n return undefined;\n }\n\n const entries = busyDays\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => !!entry);\n\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * Whether the CRM has declared the given day full.\n *\n * An absent or empty list means nothing is busy, so a picker shows its own availability\n * rather than greying everything or nothing out while the response is still in flight.\n *\n * @param day The day being drawn.\n * @param busyDays The entries from {@link parseBusyDays}.\n */\nexport function isBusyDay(day: Dayjs, busyDays?: readonly string[]): boolean {\n if (!busyDays || busyDays.length === 0) {\n return false;\n }\n\n const dateString = day.format(\"YYYY-MM-DD\");\n const dayString = day.format(\"dddd\");\n\n return busyDays.some((busyDay) => isMatch(dateString, busyDay) || isMatch(dayString, busyDay));\n}\n\n// Replace * with a regex that matches any number of characters\nfunction isMatch(str: string, pattern: string): boolean {\n const regexPattern = pattern.split(\"*\").map(escapeRegExp).join(\".*\");\n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(str);\n}\n\nfunction escapeRegExp(str: string): string {\n return str.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n}\n","import { Dayjs } from \"dayjs\";\n\nimport { BusyDayDescription } from \"stentor-models\";\n\n/**\n * Determines whether a calendar day counts as a bookable \"business day\" for the business.\n *\n * When `availableDays` is provided, those are the business's operating days — a business open\n * 7 days a week includes weekends. Only when `availableDays` is absent do we fall back to the\n * legacy Monday–Friday definition of a business day.\n */\nexport function isBusinessDay(day: Dayjs, busyDays: BusyDayDescription): boolean {\n if (Array.isArray(busyDays.availableDays) && busyDays.availableDays.length > 0) {\n const availableDays = busyDays.availableDays.map((d) => d.toLowerCase());\n return availableDays.includes(day.format(\"dddd\").toLowerCase());\n }\n\n // No explicit availableDays — business days are Monday to Friday.\n return day.day() !== 0 && day.day() !== 6;\n}\n\n/**\n * Pure implementation of the default busy-day rules for the date picker.\n *\n * Returns true when the given date should be disabled (not selectable).\n *\n * @param d The date being evaluated.\n * @param busyDays The busy-day configuration.\n * @param now The current moment, used for \"current day\" and time-of-day checks.\n */\nexport function isDisabledByBusyDays(d: Dayjs, busyDays: BusyDayDescription, now: Dayjs): boolean {\n if (busyDays.blockWeekends && (d.day() === 0 || d.day() === 6)) {\n return true;\n }\n\n if (busyDays.blockCurrentDay && d.isSame(now, \"day\")) {\n return true;\n }\n\n if (busyDays.blockNextBusinessDays) {\n let nextBusinessDay = now;\n let count = 0;\n // Bound the search so a misconfigured availableDays can never loop forever.\n let guard = 0;\n while (count < busyDays.blockNextBusinessDays && guard < 366) {\n nextBusinessDay = nextBusinessDay.add(1, \"day\");\n guard++;\n // Only count days the business is actually open, so a 7-day-a-week business\n // doesn't skip weekends (the cause of Friday showing Monday instead of Saturday).\n if (isBusinessDay(nextBusinessDay, busyDays)) {\n count++;\n }\n }\n\n if (d.isBefore(nextBusinessDay, \"day\")) {\n return true;\n }\n }\n\n if (busyDays.currentDayAvailableUntil && d.isSame(now, \"day\")) {\n // currentDayAvailableUntil is 24 hour format (HH:mm), in the client's local time.\n const time = now.format(\"HH:mm\");\n // if we are after the time, we should disable the current day\n if (time > busyDays.currentDayAvailableUntil) {\n return true;\n }\n }\n\n if (Array.isArray(busyDays.availableDays) && busyDays.availableDays.length > 0) {\n // availableDays are days of the week the business is open\n const availableDays = busyDays.availableDays.map((day) => day.toLowerCase());\n\n if (!availableDays.includes(d.format(\"dddd\").toLowerCase())) {\n return true;\n }\n }\n\n return false;\n}\n","import React, { FC, useCallback, useEffect } from \"react\";\n\nimport { FormDateInput, BusyDayDescription } from \"stentor-models\";\n\nimport dayjs, { Dayjs } from \"dayjs\";\n\nimport { Calendar } from \"../Calendar\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport { isBusyDay, parseBusyDays } from \"../../utils/busyDays\";\n\nimport { isDisabledByBusyDays } from \"./dateAvailability\";\n\nimport styles from \"./FormFieldDate.module.scss\";\n\nexport const DEFAULT_BUSY_DAYS: BusyDayDescription = {\n blockWeekends: true,\n blockCurrentDay: true,\n blockNextBusinessDays: 2,\n};\n\nexport interface FormDateProps extends FormFieldProps {\n /**\n * The date field\n */\n readonly field: FormDateInput;\n /**\n * Busy days as dates comma delimited, for example \"YYYY-MM-DD,YYYY-MM-DD\"\n */\n readonly busyDays?: string;\n /**\n * Are we loading availability information\n */\n readonly loading: boolean;\n}\n\nconst loadingMessage = \"Getting latest availability...\";\n\nexport const FormFieldDate: FC<FormDateProps> = (props) => {\n // Only go up to 2 months in the future\n const MAX_DATE = dayjs().add(2, \"month\");\n const TODAY = dayjs();\n\n const { field, onFieldChange, errorMessage, busyDays, loading } = props;\n\n /**\n * Tints a day by whether it can be booked: grey for the past and beyond the two month\n * horizon, green for a day that is open. A day blocked by the busy-day rules keeps no tint.\n */\n const getDayClassName = (day: Dayjs, disabled: boolean): string | undefined => {\n const isPast = day.isBefore(TODAY, \"day\");\n\n const isBeyondMaxDate = day.isAfter(MAX_DATE, \"day\");\n\n if (isPast || isBeyondMaxDate) {\n return styles.xapp_date_picker_past;\n } else if (disabled) {\n return undefined;\n }\n\n // available\n return styles.xapp_date_picker_available;\n };\n\n const [dateTimeValue, setDateTimeValue] = React.useState<Dayjs>();\n\n const onChange = (newValue: Dayjs) => {\n setDateTimeValue(newValue);\n };\n\n useEffect(() => {\n onFieldChange(field.name, dateTimeValue);\n }, [dateTimeValue, field.name, onFieldChange]);\n\n const disabledDays = parseBusyDays(busyDays);\n\n /**\n * Callback to determine if a date should be disabled used by the calendar\n */\n const shouldDisableDate = useCallback(\n (d: Dayjs): boolean => {\n if (!disabledDays) {\n // See if field has any defaultBusyDays by checking keys\n const hasDefaultBusyDays = Object.keys(field?.defaultBusyDays || {}).length > 0;\n\n // look for defaultBusyDays on the form or use the DEFAULT_BUSY_DAYS\n const busyDays = hasDefaultBusyDays\n ? // the extra '|| {}' is to make the subsequent types happy\n field.defaultBusyDays || {}\n : DEFAULT_BUSY_DAYS;\n\n return isDisabledByBusyDays(d, busyDays, TODAY);\n }\n\n try {\n return isBusyDay(d, disabledDays);\n } catch (err) {\n console.error(`shouldDisableDate: ${err}`);\n }\n\n return false;\n },\n [TODAY, disabledDays, field.defaultBusyDays]\n );\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignContent: \"center\",\n alignItems: \"center\",\n }}\n >\n <div className={styles.xapp_date_picker_container}>\n <Calendar\n className={styles.xapp_date_picker}\n classes={{\n header: styles.xapp_date_picker_header,\n weekday: styles.xapp_date_picker_weekday,\n weeks: styles.xapp_date_picker_weeks,\n day: styles.xapp_date_picker_day,\n daySelected: styles.xapp_date_picker_day_selected,\n dayToday: styles.xapp_date_picker_day_today,\n }}\n fixedWeekNumber={6}\n getDayClassName={getDayClassName}\n loading={loading}\n maxDate={MAX_DATE}\n minDate={TODAY}\n onChange={onChange}\n shouldDisableDate={shouldDisableDate}\n showDaysOutsideCurrentMonth={true}\n today={TODAY}\n value={dateTimeValue}\n />\n </div>\n\n {loading && <p className={styles.xapp_date_picker_loading}>{loadingMessage}</p>}\n\n {!loading && errorMessage && (\n <p className={styles.xapp_date_picker_error}>{errorMessage}</p>\n )}\n </div>\n );\n};\n\nexport default FormFieldDate;\n","import React, { FC, useEffect, useState } from \"react\";\n\nimport { FormDateRangeInput } from \"stentor-models\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\n\n/**\n * The value this field reports through onFieldChange, and the shape it accepts\n * back as its initial value. Both halves are \"YYYY-MM-DD\" - what an\n * <input type=\"date\"> reads and writes.\n */\nexport interface FormDateRangeValue {\n from: string;\n to: string;\n}\n\nexport interface FormDateRangeProps extends FormFieldProps {\n readonly field: FormDateRangeInput;\n /**\n * Initial value, so the field can be pre-populated or resumed. Dates may\n * arrive as strings (stored form config is JSON) or as real Date objects.\n */\n readonly value?: { from?: string | Date; to?: string | Date };\n /**\n * When this is the last field of the step the keyboard shows \"done\" rather than \"next\".\n */\n readonly isLastField?: boolean;\n}\n\nexport const FROM_LABEL = \"From\";\nexport const TO_LABEL = \"To\";\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}/;\n\n/**\n * Coerce whatever the config or the model hands us into the \"YYYY-MM-DD\" an\n * <input type=\"date\"> accepts. Anything we cannot parse becomes an empty field\n * rather than a date we invented.\n */\nfunction toInputDate(value?: string | Date): string {\n if (!value) {\n return \"\";\n }\n\n if (typeof value === \"string\" && ISO_DATE.test(value)) {\n // Already in the right form - including the leading date of a full ISO timestamp.\n return value.slice(0, 10);\n }\n\n const date = value instanceof Date ? value : new Date(value);\n\n // A date-only string parses as UTC midnight, so read the UTC parts back out.\n // Going through the local parts would shift the day east of Greenwich.\n return isNaN(date.getTime()) ? \"\" : date.toISOString().slice(0, 10);\n}\n\nexport const FormFieldDateRange: FC<FormDateRangeProps> = (props) => {\n const { field, onFieldChange, value, errorMessage, required, isLastField } = props;\n\n // preselecteDates is the model's spelling - it is the field's own default,\n // used only when the step has no value for us already.\n const initialFrom = toInputDate(value?.from || field.preselecteDates?.from);\n const initialTo = toInputDate(value?.to || field.preselecteDates?.to);\n\n const [range, setRange] = useState<FormDateRangeValue>({ from: initialFrom, to: initialTo });\n\n useEffect(() => {\n setRange({ from: initialFrom, to: initialTo });\n }, [initialFrom, initialTo]);\n\n const change = (next: FormDateRangeValue) => {\n setRange(next);\n // An untouched range reports as undefined rather than a pair of empty\n // strings: an object with keys reads as \"filled\" to the mandatory checks.\n onFieldChange(field.name, next.from || next.to ? next : undefined);\n };\n\n const onFromChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n change({ ...range, from: e.target.value });\n };\n\n const onToChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n change({ ...range, to: e.target.value });\n };\n\n const fromId = `${field.name}-from`;\n const toId = `${field.name}-to`;\n\n // No autoComplete on either input: there is no standard token for an arbitrary\n // from/to pair, and a wrong autocomplete is worse than none - the same rule\n // formatToInputProps follows. type=\"date\" is what keeps mobile off the text\n // keyboard, so there is no iOS auto-zoom to guard against either.\n return (\n <div style={field.style}>\n {field.title && <h2>{field.title}</h2>}\n <label htmlFor={fromId}>{FROM_LABEL}</label>\n <input\n id={fromId}\n name={fromId}\n type=\"date\"\n value={range.from}\n onChange={onFromChange}\n max={range.to || undefined}\n required={required}\n enterKeyHint=\"next\"\n />\n <label htmlFor={toId}>{TO_LABEL}</label>\n <input\n id={toId}\n name={toId}\n type=\"date\"\n value={range.to}\n onChange={onToChange}\n min={range.from || undefined}\n required={required}\n enterKeyHint={isLastField ? \"done\" : \"next\"}\n />\n {errorMessage && <p>{errorMessage}</p>}\n </div>\n );\n};\n\nexport default FormFieldDateRange;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from \"react\";\n\nimport dayjs, { Dayjs } from \"dayjs\";\n\nimport { ClockTime, FormDateTimeInput, TimeOffering } from \"stentor-models\";\n\nimport { isBusyDay, parseBusyDays } from \"../../utils/busyDays\";\nimport {\n firstSelectableDate,\n formatOfferingLabel,\n formatTimezoneLabel,\n generateOfferings,\n horizonDaysOf,\n hostTimezone,\n isDateSelectable,\n isUsableTimezone,\n OfferingsByDate,\n toCalendarDate,\n toOffsetIso,\n} from \"../../utils/timeSlots\";\n\nimport { Calendar } from \"../Calendar\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport styles from \"./FormFieldDateTime.module.scss\";\n\n/**\n * What the field reports through `onFieldChange`, and what it accepts back to resume.\n *\n * Everything a lead consumer needs is resolved here rather than at submit time, because\n * this is where the schedule - and so the timezone the times are expressed in - is known.\n */\nexport interface FormDateTimeValue {\n /**\n * The chosen day as the business sees it, \"YYYY-MM-DD\". Never shifted into UTC.\n */\n date: string;\n /**\n * What the chosen time reads as, and what is submitted for the field itself.\n */\n label: string;\n /**\n * When the appointment starts, \"HH:MM\".\n */\n start: ClockTime;\n /**\n * When it ends, \"HH:MM\". Absent for a discrete start time.\n */\n end?: ClockTime;\n /**\n * Date and time together as ISO 8601 carrying the schedule's offset on that date,\n * e.g. \"2026-08-24T09:30:00-04:00\", so the value survives a DST transition.\n */\n datetime: string;\n}\n\nexport const NO_DATE_MESSAGE = \"Select a date to see the available times.\";\nexport const NO_TIMES_MESSAGE = \"No times are available on this date.\";\nexport const TIMES_LABEL = \"Appointment times\";\nexport const TIMEZONE_NOTICE_PREFIX = \"Times shown in\";\n\nexport interface FormDateTimeProps extends FormFieldProps {\n readonly field: FormDateTimeInput;\n /**\n * A previously chosen date and time, so stepping back into the form resumes it.\n */\n readonly value?: FormDateTimeValue;\n /**\n * The current moment. Injectable so tests and Storybook get a fixed calendar rather\n * than whatever day they happen to run on.\n */\n readonly now?: Date;\n /**\n * The days the tenant's CRM has declared full, comma delimited - \"YYYY-MM-DD,YYYY-MM-DD\".\n *\n * Arrives on a channel action response and so is absent on the first render; until it\n * turns up the calendar shows the schedule's own availability. Busy days narrow that\n * availability, they never widen it.\n */\n readonly busyDays?: string;\n /**\n * The CRM's own open windows per date, \"YYYY-MM-DD\" to offerings, for a CRM that\n * books live slots.\n *\n * When present it replaces what `field.schedule` would generate: a mapped date offers\n * exactly its entries, and a date absent from the map - or mapped to nothing - cannot\n * be picked. `busyDays` and the schedule's horizon and timezone still apply.\n */\n readonly offeringsByDate?: OfferingsByDate;\n /**\n * Open on the soonest date that actually has times, instead of on the prompt.\n *\n * For a preview that lands straight on this step: a calendar with an empty\n * column beside it reads as a form with nothing to offer, when the schedule\n * is in fact full of slots one click away.\n *\n * Off by default, and deliberately not derived from `demoMode`. On a real\n * booking page a preselected date is a date the customer never chose, and\n * nothing stops them carrying it through to submit -- an appointment request\n * for a day picked by the software. Only the date is chosen; the time is\n * still theirs.\n */\n readonly preselectFirstAvailable?: boolean;\n}\n\n/**\n * Identifies an offering within a day's column. Start and end together, rather than the\n * index, so a selection survives a re-render that regenerates the array.\n */\nfunction offeringKey(offering: TimeOffering): string {\n return `${offering.start}|${offering.end || \"\"}`;\n}\n\n/**\n * Whether two selections name the same appointment.\n *\n * Compared field by field rather than by reference, so a value rebuilt from the same date\n * and offering counts as unchanged.\n */\nfunction sameSelection(a: FormDateTimeValue, b: FormDateTimeValue): boolean {\n return (\n a.date === b.date &&\n a.start === b.start &&\n a.end === b.end &&\n a.label === b.label &&\n a.datetime === b.datetime\n );\n}\n\n/**\n * What the column says the times are expressed in.\n *\n * A visitor two zones away reads \"9:30 AM\" as their own 9:30 unless something says\n * otherwise, so the zone is named outright - and named again as theirs when the two\n * differ, which is the only case where the distinction costs them an appointment. Zones\n * that merely have different identifiers but read the same, \"America/Detroit\" against\n * \"America/New_York\", are not a difference worth raising.\n *\n * @param timezone The zone the times are actually in.\n * @param visitorTimezone The zone the visitor's browser reports, if any.\n */\nfunction timezoneNotice(timezone: string, visitorTimezone: string): string {\n const name = formatTimezoneLabel(timezone);\n\n if (!name) {\n return \"\";\n }\n\n const visitorName =\n visitorTimezone && visitorTimezone !== timezone\n ? formatTimezoneLabel(visitorTimezone)\n : \"\";\n\n if (visitorName && visitorName !== name) {\n return `${TIMEZONE_NOTICE_PREFIX} ${name}, not your time zone (${visitorName}).`;\n }\n\n return `${TIMEZONE_NOTICE_PREFIX} ${name}.`;\n}\n\n/**\n * Calendar beside a scrollable column of appointment times, in the manner of Calendly.\n *\n * The column is generated from `field.schedule` on the client, so picking a date repaints\n * it immediately - there is no availability lookup and no round trip to wait on. Changing\n * the date clears the chosen time, because a time that exists on one day frequently does\n * not exist on the next.\n */\nexport const FormFieldDateTime: FC<FormDateTimeProps> = (props) => {\n const {\n field,\n onFieldChange,\n errorMessage,\n value,\n required,\n busyDays,\n offeringsByDate,\n preselectFirstAvailable,\n } = props;\n\n const schedule = field.schedule;\n\n // A fresh `new Date()` on every render would churn every memo below it.\n const now = useMemo(() => props.now || new Date(), [props.now]);\n\n const [selectedDate, setSelectedDate] = useState<Dayjs | undefined>(() =>\n value?.date ? dayjs(`${value.date}T00:00:00`) : undefined\n );\n const [selectedKey, setSelectedKey] = useState<string | undefined>(() =>\n value ? offeringKey(value) : undefined\n );\n\n const offerings = useMemo(\n () =>\n selectedDate\n ? generateOfferings(schedule, selectedDate.toDate(), now, offeringsByDate)\n : [],\n [schedule, selectedDate, now, offeringsByDate]\n );\n\n const selected = useMemo(\n () => offerings.find((offering) => offeringKey(offering) === selectedKey),\n [offerings, selectedKey]\n );\n\n const fieldValue = useMemo<FormDateTimeValue | undefined>(() => {\n if (!selectedDate || !selected) {\n return undefined;\n }\n\n const date = toCalendarDate(selectedDate.toDate());\n\n const next: FormDateTimeValue = {\n date,\n label: formatOfferingLabel(selected),\n start: selected.start,\n datetime: toOffsetIso(date, selected.start, schedule?.timezone),\n };\n\n if (selected.end) {\n next.end = selected.end;\n }\n\n // Hand back the very object the step passed down when the selection has not\n // actually moved off it. The step's prefill guard only releases on reference\n // equality, so reporting a freshly built twin reads as a stale update: the guard\n // stays closed and every later edit is silently discarded, leaving the submitted\n // value frozen at the prefill while the UI shows the new choice.\n if (value && sameSelection(value, next)) {\n return value;\n }\n\n return next;\n }, [selectedDate, selected, schedule, value]);\n\n // fieldValue is memoised, so this only reaches the step when the selection really\n // changed - not every time the parent hands down a new onFieldChange.\n useEffect(() => {\n onFieldChange(field.name, fieldValue);\n }, [fieldValue, field.name, onFieldChange]);\n\n // Memoised on the string itself so a busyDays that arrives later - or changes -\n // gives shouldDisableDate a new identity and the calendar repaints.\n const disabledDays = useMemo(() => parseBusyDays(busyDays), [busyDays]);\n\n // A date chosen before the CRM answered can turn out to be full. The selection is\n // dropped entirely rather than kept and greyed: the lead is asked again instead of\n // submitting against a day with no capacity, and the field reports undefined so a\n // mandatory step will not advance on it.\n useEffect(() => {\n if (selectedDate && isBusyDay(selectedDate, disabledDays)) {\n setSelectedDate(undefined);\n setSelectedKey(undefined);\n }\n }, [selectedDate, disabledDays]);\n\n // The soonest day with times, for a caller that asked to open on one.\n //\n // Recomputed against `disabledDays`, so this also answers the case the effect\n // above creates: busy days arrive after the first render, and a preselected\n // day that turns out to be full is cleared there and re-picked here as the\n // next day that is not. The search excludes busy days, so the day it lands on\n // cannot be cleared again and the two effects settle rather than trade.\n const preselected = useMemo(\n () =>\n preselectFirstAvailable\n ? firstSelectableDate(\n schedule,\n now,\n (date) => isBusyDay(dayjs(date), disabledDays),\n offeringsByDate\n )\n : undefined,\n [preselectFirstAvailable, schedule, now, disabledDays, offeringsByDate]\n );\n\n // Only ever fills an empty selection: a resumed value, or a day they picked\n // themselves, is theirs. And only the date -- the time is the answer, and\n // answering for someone is how a preview stops being a preview of their form.\n useEffect(() => {\n if (!preselected || selectedDate) {\n return;\n }\n\n setSelectedDate(dayjs(preselected));\n }, [preselected, selectedDate]);\n\n const onDateChange = (next: Dayjs) => {\n setSelectedDate(next);\n // A 9:30 slot valid on Tuesday may not exist on Saturday, so the time goes.\n setSelectedKey(undefined);\n };\n\n const shouldDisableDate = useCallback(\n (day: Dayjs): boolean =>\n !isDateSelectable(schedule, day.toDate(), now, offeringsByDate) ||\n isBusyDay(day, disabledDays),\n [schedule, now, disabledDays, offeringsByDate]\n );\n\n const horizon = horizonDaysOf(schedule);\n\n // What the times are *actually* in. An unusable zone is substituted for the host's\n // deep inside timeSlots rather than thrown, so the notice has to follow that\n // substitution or it would name a zone the column is not using.\n const hasSchedule = !!schedule;\n const scheduleTimezone = schedule?.timezone;\n const timezoneUsable = isUsableTimezone(scheduleTimezone);\n const notice = useMemo(() => {\n if (!hasSchedule) {\n return \"\";\n }\n\n const visitorTimezone = hostTimezone();\n\n return timezoneNotice(\n timezoneUsable ? scheduleTimezone : visitorTimezone,\n visitorTimezone\n );\n }, [hasSchedule, scheduleTimezone, timezoneUsable]);\n\n // The substitution is otherwise silent, and a typo'd zone renders times that are\n // wrong for everybody. Once per schedule, not once per render: a warning that\n // repeats on every click is one a developer learns to scroll past.\n // Keyed on the values rather than on the schedule object, so a parent that rebuilds\n // its field on every render does not turn this into a warning per keystroke.\n useEffect(() => {\n if (hasSchedule && !timezoneUsable) {\n console.warn(\n `FormFieldDateTime: \"${scheduleTimezone}\" is not a usable timezone, so ` +\n `times are shown in the visitor's zone instead. Set the schedule's ` +\n `timezone to an IANA identifier such as \"America/New_York\".`\n );\n }\n }, [hasSchedule, scheduleTimezone, timezoneUsable]);\n\n // Rendered as one flat list rather than nested lists: a group is a heading in the\n // middle of the column, so a schedule that names only some of its offerings still\n // reads as a single scrollable run.\n let previousGroup: string | undefined;\n\n return (\n <div className={styles.xapp_datetime} style={field.style}>\n {!!field.title && <h2 className={styles.xapp_datetime_title}>{field.title}</h2>}\n\n <div className={styles.xapp_datetime_body}>\n <div className={styles.xapp_datetime_calendar}>\n <Calendar\n // No minDate: past dates are already unselectable through\n // shouldDisableDate, which measures them against the now this\n // component was handed rather than the real clock.\n maxDate={dayjs(now).add(horizon, \"day\")}\n onChange={onDateChange}\n referenceDate={dayjs(now)}\n shouldDisableDate={shouldDisableDate}\n today={dayjs(now)}\n value={selectedDate || null}\n />\n </div>\n\n <div className={styles.xapp_datetime_times_column}>\n {!!notice && (\n // Deliberately a sibling of the group rather than a child: the\n // group's accessible name already carries the requirement, and a\n // screen reader reads this on its way past either way.\n <p className={styles.xapp_datetime_timezone}>{notice}</p>\n )}\n\n <div\n // `aria-required` is not valid on role=\"group\", and the offerings\n // are buttons rather than form controls, so the requirement rides\n // in the accessible name where a screen reader will actually\n // announce it.\n aria-label={required ? `${TIMES_LABEL} (required)` : TIMES_LABEL}\n className={styles.xapp_datetime_times}\n role=\"group\"\n >\n {!selectedDate && (\n <p className={styles.xapp_datetime_message}>{NO_DATE_MESSAGE}</p>\n )}\n\n {!!selectedDate && offerings.length === 0 && (\n <p className={styles.xapp_datetime_message}>{NO_TIMES_MESSAGE}</p>\n )}\n\n {offerings.map((offering, index) => {\n const key = offeringKey(offering);\n const header =\n offering.group !== previousGroup ? offering.group : undefined;\n previousGroup = offering.group;\n\n return (\n <React.Fragment key={`${key}-${index}`}>\n {!!header && (\n <h3 className={styles.xapp_datetime_group}>{header}</h3>\n )}\n <button\n aria-pressed={key === selectedKey}\n className={`${styles.xapp_datetime_time} ${\n key === selectedKey\n ? styles.xapp_datetime_time_selected\n : \"\"\n }`}\n onClick={() => setSelectedKey(key)}\n type=\"button\"\n >\n {formatOfferingLabel(offering)}\n </button>\n </React.Fragment>\n );\n })}\n </div>\n </div>\n </div>\n\n {!!errorMessage && (\n <p className={styles.xapp_datetime_error}>{errorMessage}</p>\n )}\n </div>\n );\n};\n\nexport default FormFieldDateTime;\n","!function(t,e){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define([],e):\"object\"==typeof exports?exports.AutosuggestHighlightParse=e():t.AutosuggestHighlightParse=e()}(this,(()=>{return t={705:t=>{t.exports=function(t,e){const h=[];return 0===e.length?h.push({text:t,highlight:!1}):e[0][0]>0&&h.push({text:t.slice(0,e[0][0]),highlight:!1}),e.forEach(((i,o)=>{const s=i[0],r=i[1];h.push({text:t.slice(s,r),highlight:!0}),o===e.length-1?r<t.length&&h.push({text:t.slice(r,t.length),highlight:!1}):r<e[o+1][0]&&h.push({text:t.slice(r,e[o+1][0]),highlight:!1})})),h}}},e={},function h(i){var o=e[i];if(void 0!==o)return o.exports;var s=e[i]={exports:{}};return t[i](s,s.exports,h),s.exports}(705);var t,e}));","import { AddressAutocompleteParameters } from \"stentor-models\";\n\nimport { err } from \".\";\n\nexport interface AddressAutocompleteConfig {\n apiKey?: string;\n baseUrl?: string;\n}\n\nexport interface AddressAutocompleteQuery {\n input: string;\n componentRestrictions?: {\n country: \"US\";\n };\n params?: AddressAutocompleteParameters;\n}\n\nexport interface MainTextMatchedSubstrings {\n offset: number;\n length: number;\n}\n\nexport interface StructuredFormatting {\n main_text: string;\n secondary_text: string;\n main_text_matched_substrings?: readonly MainTextMatchedSubstrings[];\n}\n\nexport interface PlaceType {\n description: string;\n structured_formatting: StructuredFormatting;\n /**\n * Google Place ID for the prediction, used to resolve full place details\n * (the prediction description never includes the postal code).\n */\n placeId?: string;\n}\n\n/**\n * Place details from the New Places API (v1). Only the fields the widget uses.\n */\nexport interface PlaceDetails {\n id?: string;\n formattedAddress?: string;\n}\n\n// New Places API (v1) response types\ninterface NewApiMatch {\n startOffset?: number;\n endOffset: number;\n}\n\ninterface NewApiFormattedText {\n text: string;\n matches?: NewApiMatch[];\n}\n\ninterface NewApiPlacePrediction {\n placeId: string;\n text: NewApiFormattedText;\n structuredFormat: {\n mainText: NewApiFormattedText;\n secondaryText?: { text: string };\n };\n}\n\n// The New Places API can return placePrediction or queryPrediction items\ninterface NewApiSuggestion {\n placePrediction?: NewApiPlacePrediction;\n}\n\ninterface PlaceSuggestion {\n placePrediction: NewApiPlacePrediction;\n}\n\ninterface NewApiResponse {\n suggestions?: NewApiSuggestion[];\n}\n\nfunction isPlaceSuggestion(s: NewApiSuggestion): s is PlaceSuggestion {\n return s.placePrediction != null;\n}\n\nfunction mapSuggestion(suggestion: PlaceSuggestion): PlaceType {\n const { placePrediction } = suggestion;\n return {\n placeId: placePrediction.placeId,\n description: placePrediction.text.text,\n structured_formatting: {\n main_text: placePrediction.structuredFormat.mainText.text,\n secondary_text: placePrediction.structuredFormat.secondaryText?.text || \"\",\n main_text_matched_substrings: (\n placePrediction.structuredFormat.mainText.matches || []\n ).map((m) => ({\n offset: m.startOffset ?? 0,\n length: (m.endOffset ?? 0) - (m.startOffset ?? 0),\n })),\n },\n };\n}\n\n/**\n * A service that interacts with a Google Places Autocomplete compatible API (New Places API v1).\n */\nexport class AddressAutocompleteService {\n private readonly baseUrl: string;\n private readonly key?: string;\n\n constructor(config: AddressAutocompleteConfig) {\n this.baseUrl = config.baseUrl || \"https://api.xapp.ai\";\n this.key = config.apiKey;\n }\n\n public getPlacePredictions(\n query: AddressAutocompleteQuery,\n callback: (results?: readonly PlaceType[]) => void\n ) {\n const requestBody: Record<string, unknown> = {};\n\n // Translate legacy params to New Places API v1 fields\n if (query.params) {\n // Convert legacy \"components\" (e.g. \"country:us\" or \"country:us|country:ca\")\n // to New API \"includedRegionCodes\" (e.g. [\"us\", \"ca\"])\n if (query.params.components) {\n const regionCodes = query.params.components\n .split(\"|\")\n .filter((c) => c.startsWith(\"country:\"))\n .map((c) => c.replace(\"country:\", \"\").toLowerCase());\n if (regionCodes.length > 0) {\n requestBody.includedRegionCodes = regionCodes;\n }\n }\n // Convert legacy \"language\" to New API \"languageCode\"\n if (query.params.language) {\n requestBody.languageCode = query.params.language;\n }\n // Convert legacy \"location\" (lat,lng string) + \"radius\" to New API \"locationBias\"\n if (query.params.location) {\n const [lat, lng] = query.params.location.split(\",\").map(Number);\n if (!isNaN(lat) && !isNaN(lng)) {\n requestBody.locationBias = {\n circle: {\n center: { latitude: lat, longitude: lng },\n radius: Number(query.params.radius) || 50000,\n },\n };\n }\n }\n }\n\n requestBody.input = query.input;\n\n // componentRestrictions overrides params; default to US unless already set\n if (query.componentRestrictions?.country) {\n requestBody.includedRegionCodes = [query.componentRestrictions.country.toLowerCase()];\n } else if (!requestBody.includedRegionCodes) {\n requestBody.includedRegionCodes = [\"us\"];\n }\n\n let url = `${this.baseUrl}/places/autocomplete`;\n if (this.key) {\n url += `?key=${encodeURIComponent(this.key)}`;\n }\n\n fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(requestBody),\n })\n .then((response) => {\n if (!response.ok) {\n throw new Error(`getPlacePredictions: HTTP error! Status: ${response.status}`);\n }\n return response.json();\n })\n .then((data: NewApiResponse) => {\n callback((data.suggestions || []).filter(isPlaceSuggestion).map(mapSuggestion));\n })\n .catch((error) => {\n err(\"getPlacePredictions: Fetch error:\", error);\n callback([]);\n });\n }\n\n /**\n * Resolves a place id from a prediction to full place details, which include\n * the formatted address with postal code. Calls back with undefined on failure.\n */\n public getPlaceDetails(placeId: string, callback: (details?: PlaceDetails) => void) {\n let url = `${this.baseUrl}/places/details/${encodeURIComponent(placeId)}`;\n if (this.key) {\n url += `?key=${encodeURIComponent(this.key)}`;\n }\n\n fetch(url)\n .then((response) => {\n if (!response.ok) {\n throw new Error(`getPlaceDetails: HTTP error! Status: ${response.status}`);\n }\n return response.json();\n })\n .then((data: PlaceDetails) => {\n callback(data);\n })\n .catch((error) => {\n err(\"getPlaceDetails: Fetch error:\", error);\n callback(undefined);\n });\n }\n}\n","import React, { FC, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\nimport parse from \"autosuggest-highlight/parse\";\n\nimport { AddressAutocompleteParameters, FormFieldTextAddressInput } from \"stentor-models\";\n\nimport { FormTextInputProps } from \"../FormFieldTextInput/FormFieldTextInput\";\nimport { AddressAutocompleteService, PlaceType } from \"../../utils/AddressAutocompleteService\";\n\nimport styles from \"./FormFieldTextInputAddress.module.scss\";\n\nconst POWERED_BY_GOOGLE_URL =\n \"https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white3.png\";\n\n// How long typing has to pause before we ask for predictions, as MUI's Google Maps demo did.\nconst DEBOUNCE_MS = 400;\n\ntype PredictionRequest = { input: string; params?: AddressAutocompleteParameters };\ntype PredictionCallback = (results?: readonly PlaceType[]) => void;\n\n/**\n * Trailing-edge debounce with a `clear`, the part of `@mui/material/utils`'s debounce we used.\n */\nfunction debounce<A extends unknown[]>(fn: (...args: A) => void, wait: number) {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const debounced = (...args: A) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => fn(...args), wait);\n };\n debounced.clear = () => clearTimeout(timeout);\n return debounced;\n}\n\n// MUI's LocationOn icon\nconst LocationOnIcon: FC = () => (\n <svg\n className={styles.xapp_address_option_icon}\n viewBox=\"0 0 24 24\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <path d=\"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7m0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5\" />\n </svg>\n);\n\nexport interface FormFieldTextInputAddressProps\n extends FormTextInputProps,\n Pick<FormFieldTextAddressInput, \"googleMapsApiKey\" | \"mapsBaseUrl\"> {\n readonly field: FormFieldTextAddressInput;\n /**\n * When true, the user must select an address from the autocomplete suggestions.\n * Free-text entry is not allowed.\n *\n * Can also be set via `field.requireSelection` (field-level takes precedence).\n * @see https://github.com/stentorium/stentor/issues/3040\n */\n readonly requireSelection?: boolean;\n}\n\n/**\n * An address field with Places suggestions: a WAI-ARIA combobox (an input plus a listbox), native\n * since XappMedia/chat-widget#1744. It behaves as the MUI Autocomplete it replaced did.\n */\nexport const FormFieldTextInputAddress: FC<FormFieldTextInputAddressProps> = (props) => {\n const {\n field,\n onFieldChange,\n errorMessage,\n required,\n googleMapsApiKey,\n mapsBaseUrl,\n requireSelection,\n } = props;\n\n // Field-level takes precedence, then component prop, default false\n const isFreeSolo = !(field.requireSelection ?? requireSelection);\n\n const [address, setAddress] = useState<PlaceType | null>(null);\n const [text, setText] = useState(\"\");\n const [options, setOptions] = useState<readonly PlaceType[]>([]);\n const [open, setOpen] = useState(false);\n const [focused, setFocused] = useState(false);\n // -1 is the text itself: nothing in the list is active\n const [activeIndex, setActiveIndex] = useState(-1);\n\n const id = `xapp-address-${useId()}`;\n const listboxId = `${id}-listbox`;\n const helperId = `${id}-helper-text`;\n const optionId = (index: number) => `${id}-option-${index}`;\n\n const listboxRef = useRef<HTMLUListElement>(null);\n\n // Mirrors the current input text so async place details callbacks can tell\n // whether the customer has typed or reselected since the request was made.\n const textRef = useRef(\"\");\n\n const onTextChange = (t: string) => {\n textRef.current = t;\n setText(t);\n };\n\n useEffect(() => {\n onFieldChange(field.name, text);\n }, [field.name, onFieldChange, text]);\n\n const apiKey = field.googleMapsApiKey || googleMapsApiKey;\n const baseUrl = field.mapsBaseUrl || mapsBaseUrl;\n\n const autocompleteService = useMemo(\n () => new AddressAutocompleteService({ apiKey, baseUrl }),\n [apiKey, baseUrl]\n );\n\n // Show Google attribution when using the xapp.ai proxy (which forwards to Google Places API).\n // Custom non-xapp.ai base URLs are assumed to be non-Google backends that handle their own attribution.\n const showGoogleAttribution = (() => {\n if (!baseUrl) return true;\n try {\n const hostname = new URL(baseUrl).hostname;\n return hostname === \"xapp.ai\" || hostname.endsWith(\".xapp.ai\");\n } catch {\n return false;\n }\n })();\n\n const fetch = useMemo(\n () =>\n debounce((request: PredictionRequest, callback: PredictionCallback) => {\n autocompleteService.getPlacePredictions(request, callback);\n }, DEBOUNCE_MS),\n [autocompleteService]\n );\n\n // A request still waiting out the debounce must not fire after the field is gone\n useEffect(() => () => fetch.clear(), [fetch]);\n\n useEffect(() => {\n let active = true;\n\n if (text === \"\") {\n setOptions([]);\n return undefined;\n }\n\n const queryParams = field.mapsUrlQueryParams || undefined;\n\n fetch({ input: text, params: queryParams }, (results?: readonly PlaceType[]) => {\n // A response for text the customer has since changed is dropped\n if (active) {\n setOptions(results || []);\n }\n });\n\n return () => {\n active = false;\n };\n }, [text, fetch, field.mapsUrlQueryParams]);\n\n // The option already chosen is not offered again (MUI's filterSelectedOptions)\n const visibleOptions = useMemo(\n () => (address ? options.filter((o) => o.description !== address.description) : options),\n [options, address]\n );\n\n // A free-text field has nothing to say when there are no suggestions; one that requires a\n // selection says so.\n const popupOpen = open && (visibleOptions.length > 0 || (!isFreeSolo && text !== \"\"));\n\n // New suggestions reset the active option, and it can never point past the list\n useEffect(() => {\n setActiveIndex(-1);\n }, [visibleOptions]);\n\n // Keep the active option in view inside the list without scrolling the page around it\n useLayoutEffect(() => {\n const listbox = listboxRef.current;\n const option = activeIndex >= 0 ? listbox?.children[activeIndex] : undefined;\n if (!listbox || !(option instanceof HTMLElement)) {\n return;\n }\n if (option.offsetTop < listbox.scrollTop) {\n listbox.scrollTop = option.offsetTop;\n } else if (\n option.offsetTop + option.offsetHeight >\n listbox.scrollTop + listbox.clientHeight\n ) {\n listbox.scrollTop = option.offsetTop + option.offsetHeight - listbox.clientHeight;\n }\n }, [activeIndex, popupOpen]);\n\n const close = () => {\n setOpen(false);\n setActiveIndex(-1);\n };\n\n const select = (option: PlaceType) => {\n close();\n setAddress(option);\n onTextChange(option.description);\n // Resolve the selected prediction to full place details so the displayed\n // and stored address includes the postal code (predictions never carry one).\n if (option.placeId) {\n const { placeId, description } = option;\n autocompleteService.getPlaceDetails(placeId, (details) => {\n // Skip stale results: only apply if the field still shows this prediction\n if (details?.formattedAddress && textRef.current === description) {\n setAddress({ ...option, description: details.formattedAddress });\n onTextChange(details.formattedAddress);\n }\n });\n }\n };\n\n const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const { value } = e.target;\n onTextChange(value);\n if (value === \"\") {\n // Clearing the text clears the selection too, as MUI did\n setAddress(null);\n } else {\n setOpen(true);\n }\n };\n\n // Up/Down cycle through the options and back to the text itself (MUI's includeInputInList)\n const move = (step: 1 | -1) => {\n const count = visibleOptions.length;\n if (count === 0) {\n return;\n }\n setActiveIndex((current) => {\n const next = current + step;\n if (next >= count) return -1;\n if (next < -1) return count - 1;\n return next;\n });\n };\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n switch (e.key) {\n case \"ArrowDown\":\n case \"ArrowUp\":\n e.preventDefault();\n setOpen(true);\n move(e.key === \"ArrowDown\" ? 1 : -1);\n break;\n case \"Enter\":\n if (popupOpen && activeIndex >= 0 && visibleOptions[activeIndex]) {\n // Choosing a suggestion must not also submit the form\n e.preventDefault();\n select(visibleOptions[activeIndex]);\n } else {\n close();\n }\n break;\n case \"Escape\":\n if (popupOpen) {\n // Closes the list, not the dialog the form sits in\n e.preventDefault();\n e.stopPropagation();\n close();\n }\n break;\n default:\n break;\n }\n };\n\n const onBlur = () => {\n setFocused(false);\n close();\n // A field that requires a selection drops text that isn't one (MUI's clearOnBlur)\n if (!isFreeSolo) {\n const chosen = address?.description || \"\";\n if (text !== chosen) {\n onTextChange(chosen);\n }\n }\n };\n\n // MUI's floating label: resting inside the field until it is focused or has a value. With no\n // label to collide with, the placeholder is always shown.\n const shrink = focused || text.length > 0 || !field.label;\n const activeOption = popupOpen && activeIndex >= 0 ? optionId(activeIndex) : undefined;\n\n return (\n <div\n className={`${styles.xapp_text_input_address} ${\n errorMessage ? styles.xapp_address_error : \"\"\n }`}\n style={field.style}\n >\n <div className={styles.xapp_address_anchor}>\n <div\n className={`${styles.xapp_address_root} ${\n focused ? styles.xapp_address_focused : \"\"\n }`}\n >\n {field.label && (\n <label\n htmlFor={id}\n className={styles.xapp_address_label}\n data-shrink={shrink ? \"true\" : \"false\"}\n >\n {field.label}\n {required && (\n <span className={styles.xapp_address_asterisk} aria-hidden=\"true\">\n {\" *\"}\n </span>\n )}\n </label>\n )}\n <input\n id={id}\n name={field.name}\n type=\"text\"\n className={styles.xapp_address_control}\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-expanded={popupOpen}\n aria-controls={listboxId}\n aria-activedescendant={activeOption}\n aria-invalid={!!errorMessage}\n aria-describedby={errorMessage ? helperId : undefined}\n // The browser's own autofill list would cover the suggestions\n autoComplete=\"off\"\n autoCapitalize=\"none\"\n spellCheck={false}\n placeholder={field.placeholder}\n required={required}\n maxLength={field.maxLength || undefined}\n value={text}\n onChange={onChange}\n onKeyDown={onKeyDown}\n onFocus={() => setFocused(true)}\n onBlur={onBlur}\n onMouseDown={() => {\n // A click opens the list, as MUI's did; it never toggles it shut\n if (!popupOpen && text !== \"\") {\n setOpen(true);\n }\n }}\n // Read by the stylesheet, which hides the placeholder behind a resting label.\n data-shrink={shrink ? \"true\" : \"false\"}\n />\n </div>\n <div\n className={styles.xapp_address_popup}\n hidden={!popupOpen}\n // Keeps the input focused while an option is clicked\n onMouseDown={(e) => e.preventDefault()}\n >\n <ul\n ref={listboxRef}\n id={listboxId}\n role=\"listbox\"\n aria-label={`${field.label || \"Address\"} suggestions`}\n className={styles.xapp_address_listbox}\n >\n {visibleOptions.map((option, index) => {\n const matches =\n option.structured_formatting.main_text_matched_substrings || [];\n const parts = parse(\n option.structured_formatting.main_text,\n matches.map((match) => [match.offset, match.offset + match.length])\n );\n return (\n <li\n key={option.placeId || option.description}\n id={optionId(index)}\n role=\"option\"\n aria-selected={index === activeIndex}\n className={`${styles.xapp_address_option} ${\n index === activeIndex\n ? styles.xapp_address_option_active\n : \"\"\n }`}\n onMouseMove={() => setActiveIndex(index)}\n onClick={() => select(option)}\n >\n <LocationOnIcon />\n <span className={styles.xapp_address_option_text}>\n {parts.map((part, i) => (\n <span\n key={i}\n style={{\n fontWeight: part.highlight ? \"bold\" : \"normal\",\n }}\n >\n {part.text}\n </span>\n ))}\n <span className={styles.xapp_address_secondary}>\n {option.structured_formatting.secondary_text}\n </span>\n </span>\n </li>\n );\n })}\n </ul>\n {popupOpen && visibleOptions.length === 0 && (\n <div className={styles.xapp_address_no_options}>No locations</div>\n )}\n {showGoogleAttribution && (\n <div className={styles.xapp_address_attribution}>\n <img src={POWERED_BY_GOOGLE_URL} alt=\"powered by Google\" />\n </div>\n )}\n </div>\n </div>\n {errorMessage && (\n <p id={helperId} className={styles.xapp_address_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n );\n};\n","export interface FieldValidatorResult {\n valid: boolean;\n message?: string;\n}\n\nexport const validateEmail = (s: string): FieldValidatorResult => {\n const re = /^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;\n\n const valid = re.test(String(s).toLowerCase());\n const message = !valid ? \"Invalid email address\" : undefined;\n\n return { valid, message };\n};\n\nexport const validatePhoneNumber = (s: string): FieldValidatorResult => {\n // Nothing is valid\n if (isEmptyString(s)) {\n return { valid: true };\n }\n\n const valid = validateUSPhoneNumber(s);\n const message = !valid ? \"Invalid phone number\" : undefined;\n\n return { valid, message };\n};\n\nexport const validateZipCode = (s: string): FieldValidatorResult => {\n // Nothing is valid\n if (isEmptyString(s)) {\n return { valid: true };\n }\n\n // US 5-digit: 12345\n const usZip5Regex = /^\\d{5}$/;\n // US 9-digit (ZIP+4): 12345-6789\n const usZip9Regex = /^\\d{5}-\\d{4}$/;\n // Canadian postal code: A1A 1A1 or A1A1A1 (letter-digit-letter space digit-letter-digit, space optional)\n const canadianPostalCodeRegex = /^[A-Za-z]\\d[A-Za-z]\\s?\\d[A-Za-z]\\d$/;\n\n const valid =\n usZip5Regex.test(s) ||\n usZip9Regex.test(s) ||\n canadianPostalCodeRegex.test(s);\n\n const message = !valid ? \"Invalid zip code or postal code\" : undefined;\n\n return { valid, message };\n};\n\nexport const isEmptyString = (s: string): boolean => {\n return typeof s !== \"string\" || s.trim().length === 0;\n};\n\nconst validateUSPhoneNumber = (s: string) => {\n const sanitizedNumber = s.replace(/\\D/g, \"\");\n\n if (\n sanitizedNumber.length === 10 ||\n (sanitizedNumber.length === 11 && sanitizedNumber.startsWith(\"1\"))\n ) {\n const validPattern = /^(1)?[-. ]?\\(?(\\d{3})\\)?[-. ]?(\\d{3})[-. ]?(\\d{4})$/;\n return validPattern.test(sanitizedNumber);\n }\n\n return false;\n};\n\nexport const formatUSPhoneNumber = (s: string) => {\n if (isEmptyString(s) || !validateUSPhoneNumber(s)) {\n return s;\n }\n\n let sanitizedNumber = s.replace(/\\D/g, \"\");\n\n if (sanitizedNumber.length === 11 && sanitizedNumber.startsWith(\"1\")) {\n sanitizedNumber = sanitizedNumber.slice(1);\n }\n\n const formattedNumber = sanitizedNumber.replace(/(\\d{3})(\\d{3})(\\d{4})/, \"($1) $2-$3\");\n\n return formattedNumber;\n};\n\nexport const formatZipCode = (s: string): string => {\n if (isEmptyString(s)) {\n return s;\n }\n\n const trimmed = s.trim();\n\n // Check if it looks like a Canadian postal code without space\n const canadianNoSpace = /^([A-Za-z]\\d[A-Za-z])(\\d[A-Za-z]\\d)$/;\n const match = trimmed.match(canadianNoSpace);\n if (match) {\n return `${match[1].toUpperCase()} ${match[2].toUpperCase()}`;\n }\n\n // Uppercase Canadian postal codes with space\n const canadianWithSpace = /^[A-Za-z]\\d[A-Za-z]\\s\\d[A-Za-z]\\d$/;\n if (canadianWithSpace.test(trimmed)) {\n return trimmed.toUpperCase();\n }\n\n // Return as-is for US zip codes or invalid input\n return s;\n};\n\nexport const fieldErrorsEqual = (\n obj1: { [key: string]: FieldValidatorResult },\n obj2: { [key: string]: FieldValidatorResult }\n): boolean => {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n\n if (keys1.length !== keys2.length) {\n return false;\n }\n\n for (const key of keys1) {\n if (!obj2.hasOwnProperty(key)) {\n return false;\n }\n\n const attr1 = obj1[key];\n const attr2 = obj2[key];\n\n if (attr1.valid !== attr2.valid) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isEmpty = (obj: unknown) => {\n // Check if the value is null or undefined\n if (obj == null) {\n return true;\n }\n // Check if the value is an empty or whitespace-only string\n if (typeof obj === \"string\") {\n return obj.trim().length === 0;\n }\n // Check if the value is an array\n if (Array.isArray(obj)) {\n return obj.length === 0;\n }\n // Check if the value is a plain object\n if (typeof obj === \"object\" && obj.constructor === Object) {\n return Object.keys(obj).length === 0;\n }\n // For other types (e.g., Map, Set), check if they are empty\n if (typeof obj === \"object\") {\n return Object.keys(obj as object).length === 0;\n }\n // If none of the above conditions are met, return false\n return false;\n};\n","import React, {\n FC,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport {\n FormCardInput,\n FormChipsInput,\n FormDateInput,\n FormDateRangeInput,\n FormDateTimeInput,\n FormDropdownInput,\n FormField,\n FormFieldTextAddressInput,\n FormStep,\n FormStepIFrame,\n FormSteps,\n FormTextInput,\n SelectableItem,\n} from \"stentor-models\";\n\nimport { addContextPrefix, shallowEqualBooleanMap } from \"../../utils/comparator\";\nimport {\n isFormCheckInput,\n isFormChipsInput,\n isFormDateInput,\n isFormDateRangeInput,\n isFormDateTimeInput,\n isFormTextInput,\n isFormDropdownInput,\n} from \"../../utils/guards\";\nimport { joinWithAnd, reformatDate, replaceValues } from \"../../utils/templating\";\nimport {\n DEFAULT_DATE_FIELD_NAME,\n DEFAULT_DATE_TIME_FIELD_NAME,\n DEFAULT_TIME_ZONE_FIELD_NAME,\n FormDateTimeInputWithTimeZone,\n parseOfferingsByDate,\n timeZoneOf,\n} from \"../../utils/timeSlots\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\nimport { useSearchState } from \"../../store\";\nimport { useExternalWidget, ExternalWidgetConfig } from \"../../utils/useExternalWidget\";\n\nimport FormFieldSelect from \"../FormFieldChips/FormFieldSelect\";\nimport { FormFieldCard } from \"../FormFieldCard\";\nimport { FormFieldChips } from \"../FormFieldChips\";\nimport { FormFieldTextInput } from \"../FormFieldTextInput\";\nimport { FormFieldDropdown } from \"../FormFieldDropdown\";\nimport { FormFieldDate } from \"../FormFieldDate\";\nimport { FormDateRangeValue, FormFieldDateRange } from \"../FormFieldDateRange\";\nimport { FormDateTimeValue, FormFieldDateTime } from \"../FormFieldDateTime\";\nimport { FormFieldTextInputAddress } from \"../FormFieldTextInputAddress\";\nimport { SpinnerIcon } from \"../icons\";\n\nimport {\n FieldValidatorResult,\n fieldErrorsEqual,\n formatUSPhoneNumber,\n formatZipCode,\n isEmpty,\n isEmptyString,\n validateEmail,\n validatePhoneNumber,\n validateZipCode,\n} from \"./validators\";\n\nimport styles from \"./FormStepDisplay.module.scss\";\n// Global (non-module) overrides that restyle the CostGuide partner embed rendered under\n// #airo-anchor. Kept separate from the CSS-module styles above because it targets the\n// partner's own light-DOM class names, which must not be scoped. See costguide-overrides.scss.\nimport \"./costguide-overrides.scss\";\nimport { isSelectableItem } from \"../FormFieldChips/FormFieldChips\";\n\n/**\n * Extended FormStep interface for per-step properties not yet in stentor-models.\n * Until they land upstream (targeting stentor-models@1.75.0), we use this type\n * extension to maintain type safety.\n */\ninterface FormStepWithUnloadWarning extends FormStep {\n warnBeforeUnload?: boolean;\n warnBeforeUnloadMessage?: string;\n /**\n * Suppresses the horizontal gutters (ModalDialog + step padding) for this\n * step only, so a full-width embed (e.g. an external booking widget) can\n * render edge-to-edge. From stentor-models@1.75.0's FormStep.fullBleed.\n */\n fullBleed?: boolean;\n}\n\n/**\n * Local extension of FormStep for the external booking-widget handoff step,\n * mirroring stentor-models@1.75.0's FormStepExternalWidget. See the note on\n * FormStepWithUnloadWarning above for why this is redeclared locally.\n */\nexport interface FormStepExternalWidget extends FormStep {\n externalWidget: ExternalWidgetConfig;\n}\n\nexport function isFormStepIframe(step: FormSteps): step is FormStepIFrame {\n return !!step && (step as FormStepIFrame).iframe !== undefined;\n}\n\nexport function isFormStepExternalWidget(step: FormSteps): step is FormStepExternalWidget {\n return !!step && (step as FormStepExternalWidget).externalWidget !== undefined;\n}\n\ntype FormFieldWithValue = FormField & { value: unknown };\nfunction hasFieldValue(f: FormField): f is FormFieldWithValue {\n return \"value\" in f && (f as FormFieldWithValue).value !== undefined;\n}\n\nexport interface StepData {\n current?: { [key: string]: unknown };\n}\n\n/**\n * What the step shows in place of its date and time fields when the CRM will not take a\n * scheduled booking.\n */\nexport const SCHEDULING_DISABLED_MESSAGE = \"We'll contact you to schedule a time.\";\n\n/**\n * The CHIPS fields that pick a date or time rather than answer some other question. Matched by\n * name because that is the only thing that tells a \"Morning / Afternoon\" chip apart from any\n * other: it is the name every lead consumer already reads.\n */\nconst SCHEDULING_CHIPS_NAMES = [\"preferred_time\", \"preferred_date\"];\n\n/**\n * Whether a field asks when the appointment should be, and so goes when scheduling is off.\n */\nfunction isSchedulingField(field: FormField): boolean {\n if (field.type === \"DATE\" || field.type === \"DATETIME\") {\n return true;\n }\n\n return field.type === \"CHIPS\" && SCHEDULING_CHIPS_NAMES.indexOf(field.name) >= 0;\n}\n\n/**\n * Every lead field a scheduling field writes when it is pushed - see `pushData` - so a value\n * pushed before scheduling went off can be cleared from all of them.\n */\nfunction leadFieldNamesOf(field: FormField): string[] {\n const names = [field.name, `${field.name}_start`, `${field.name}_end`];\n\n if (field.type === \"DATETIME\") {\n const dateTimeField = field as FormDateTimeInputWithTimeZone;\n names.push(\n dateTimeField.dateFieldName || DEFAULT_DATE_FIELD_NAME,\n dateTimeField.dateTimeFieldName || DEFAULT_DATE_TIME_FIELD_NAME,\n dateTimeField.timeZoneFieldName || DEFAULT_TIME_ZONE_FIELD_NAME\n );\n }\n\n return names;\n}\n\n/**\n * `schedulingDisabled` off the BusyDays context. Context parameters are typed as strings but\n * carry whatever the handler set, so the boolean and its string form both count.\n */\nfunction isSchedulingDisabled(context?: { [key: string]: unknown }): boolean {\n const flag = context?.schedulingDisabled;\n\n return flag === true || flag === \"true\";\n}\n\ntype Groupable<T extends FormField> = T & { mandatoryGroup?: string };\n\ninterface GroupableFieldStep extends FormStep {\n fields: Groupable<FormField>[];\n}\n\nfunction isGroupableFieldField(step: FormField): step is Groupable<FormField> {\n return !!step && (step as Groupable<FormField>).mandatoryGroup !== undefined;\n}\n\nexport interface FormStepDisplayProps {\n /**\n * Step data\n */\n readonly formStep: FormSteps | GroupableFieldStep;\n /**\n * Open a DATETIME field on the soonest day that has times, rather than on\n * \"Select a date to see the available times.\" For a preview that lands\n * straight on that step; off by default.\n */\n readonly preselectFirstAvailableDate?: boolean;\n /**\n * When the user hits the next button.\n *\n * If submit is true, then the form should be submitted.\n * May return a Promise when a FORM_NEXT server callback is in flight.\n */\n onNextStep: ((submit?: boolean) => Promise<void> | void) | undefined;\n /**\n * When the user hits the previous button\n */\n onPrevStep: (() => void) | undefined;\n /**\n * Data from the step\n */\n onData: (data: StepData) => void;\n /**\n * Data from the step but split up into key, value pairs.\n *\n * For example, {\"name\": \"John Smith\"}\n */\n onDataWithLabels: (data: object) => void;\n\n getData: () => object;\n /**\n * Returns the data needed for the form\n *\n * @returns\n */\n getDataWithLabels: () => object;\n /**\n * Is the form loading\n */\n loading: boolean;\n /**\n * Current step index (0-indexed)\n */\n currentStepIndex?: number;\n /**\n * Total number of steps in the form\n */\n totalSteps?: number;\n /**\n * Callback to track next_step event\n */\n onTrackNextStep?: (\n stepName: string,\n stepIndex: number,\n stepData: Record<string, unknown>,\n isLastStep: boolean\n ) => void;\n /**\n * Optional ref to sync current step data for tracking purposes.\n * This allows parent components to access live form data before step completion.\n */\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /**\n * Whether this step is the one currently visible. Every step's FormStepDisplay\n * is mounted at once (FormDisplay toggles visibility via CSS), so this is what\n * gates the external-widget mount sequence to only run once the step actually\n * becomes active, rather than for every handoff step on the form's first render.\n */\n isActive?: boolean;\n /**\n * True while this step's partner-widget config is still missing the values that only the\n * FORM_SUBMIT response carries. Injecting before they land hands the partner a config with no\n * zipCode, name or trade, and one that reads its global at load never sees the real one.\n */\n externalWidgetConfigPending?: boolean;\n /**\n * Fired when a booking-widget handoff step's anchor gains content within\n * its render timeout.\n */\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n /**\n * Fired when a booking-widget handoff step's render timeout elapses with\n * an empty anchor.\n */\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n /**\n * Fired when the partner script invokes the configured success callback.\n */\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n /**\n * Fired when a booking-widget handoff step's script fails to load or is rejected.\n */\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n /**\n * Fired when a booking-widget handoff step fails to render (timeout or script\n * error) and `externalWidget.fallbackStep` is set, so the parent can navigate\n * there. Not fired when fallbackStep is unset -- an inline fallback message is\n * rendered in place instead.\n */\n onExternalWidgetFallback?: (fallbackStep: string) => void;\n /**\n * Message shown when this step's FORM_SUBMIT dispatch failed, so the user knows\n * their submission did not land and can retry rather than assuming it worked\n * (issue #1373). Undefined when the step has no failed submit.\n */\n submitError?: string;\n /**\n * Suppresses this step's own title/subtitle block. Set when a partner frame is\n * around the step, since the frame's intro block renders them instead -- and\n * placement is the frame's decision (it can sit outside the frame entirely).\n */\n hideIntro?: boolean;\n}\n\n/**\n * Both halves present. `FormFieldDateRange` reports `undefined` when both are empty and a\n * partial object when only one is filled, so this distinguishes \"untouched\" from \"half done\"\n * without either being treated as a usable range.\n */\n/**\n * A datetime field holds two values and is only satisfied by both. `start` rather than\n * the label, because an offering without a label still formats one for display.\n */\nfunction isCompleteDateTime(value: unknown): boolean {\n const selection = value as FormDateTimeValue | undefined;\n\n return !!selection?.date && !!selection?.start;\n}\n\nfunction isCompleteRange(value: unknown): boolean {\n const range = value as { from?: string; to?: string } | undefined;\n return !!range?.from && !!range?.to;\n}\n\nexport const FormStepDisplay: FC<FormStepDisplayProps> = (props) => {\n const stepData = useRef<StepData>({});\n // Track which fields were prefilled from server values (not user input)\n const prefilledFields = useRef<Set<string>>(new Set());\n const hasNotifiedPrefill = useRef(false);\n const prevFieldsRef = useRef(props.formStep.fields);\n\n const fieldTests = useRef({});\n\n const [mandatoryGroups, setMandatoryGroups] = useState<{ [name: string]: string[] }>({});\n const [fieldConditions, setFieldConditions] = useState<{ [name: string]: boolean }>({});\n const [fieldErrors, setFieldErrors] = useState<{ [name: string]: FieldValidatorResult }>({});\n const [isSubmitting, setIsSubmitting] = useState(false);\n\n const { context } = useSearchState();\n\n // Both arrive on the BusyDays context alongside busyDays, from a CRM that either books\n // live slots or will not take a scheduled booking at all right now.\n const schedulingDisabled = isSchedulingDisabled(context);\n const rawOfferingsByDate: unknown = context?.offeringsByDate;\n const offeringsByDate = useMemo(\n () => parseOfferingsByDate(rawOfferingsByDate),\n [rawOfferingsByDate]\n );\n\n // A field that is not shown cannot be asked for, and its value - a preselected chip, a\n // date picked before the flag arrived - is not an answer the lead gave.\n const isHiddenSchedulingField = useCallback(\n (field?: FormField) => schedulingDisabled && !!field && isSchedulingField(field),\n [schedulingDisabled]\n );\n\n const {\n formStep,\n onNextStep: nextStep,\n onPrevStep: prevStep,\n onData: handleData,\n onDataWithLabels: handleDataWithLabels,\n getData,\n getDataWithLabels,\n loading,\n currentStepIndex,\n totalSteps,\n onTrackNextStep,\n currentStepDataRef,\n isActive,\n externalWidgetConfigPending,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n onExternalWidgetFallback,\n submitError,\n hideIntro,\n } = props;\n\n // Gated on isActive: every step's FormStepDisplay is mounted at once, so\n // without this the mount sequence would fire for a handoff step as soon as\n // the form first renders, rather than when the step actually becomes active.\n //\n // Also gated on the submit's config having arrived. Becoming active is not enough: the step is\n // reached by a fire-and-forget FORM_SUBMIT, so it renders before the response carrying zipCode,\n // name and trade. Our own placeholder shows in the meantime, which is the same thing the\n // visitor sees while the partner's script boots.\n const externalWidgetConfig =\n isActive && !externalWidgetConfigPending && isFormStepExternalWidget(formStep)\n ? formStep.externalWidget\n : undefined;\n\n const { outcome: externalWidgetOutcome } = useExternalWidget(externalWidgetConfig, {\n onRendered: (provider) => onTrackHandoffRendered?.(formStep.name, provider),\n onNoRender: (provider) => onTrackHandoffNoRender?.(formStep.name, provider),\n onScheduled: (provider, payload) =>\n onTrackHandoffScheduled?.(formStep.name, provider, payload),\n onError: (provider) => onTrackHandoffError?.(formStep.name, provider),\n onFallback: (fallbackStep) => onExternalWidgetFallback?.(fallbackStep),\n });\n\n // The partner embed shows its OWN loading UI (e.g. CostGuide's #step-loading) while it works,\n // which the hook still reports as \"pending\". Watch the anchor locally so our placeholder steps\n // aside the moment their content appears -- otherwise two spinners show at once.\n //\n // Deliberately local state rather than something exposed from useExternalWidget: returning\n // anchor state from the hook re-runs its mount effect on a fresh config object, which\n // early-exits via hasMountedRef *after* cleanup has torn down the render-timeout timer, so\n // no_render never fires. The hook's own tests catch that. externalWidgetConfig is a stable\n // reference here, so watching it from this component is safe.\n //\n // ASSUMPTION for the next partner integration: \"any child element\" is treated as \"the partner\n // is showing something\". That holds for CostGuide, whose first write is its own visible\n // #step-loading spinner. A partner whose first write is an empty wrapper it populates a moment\n // later would retire our placeholder early and leave a blank gap until their content paints.\n // If that shows up, tighten the predicate here (e.g. require text content or a known step id)\n // rather than removing the check -- without it CostGuide stacks two spinners.\n //\n // useLayoutEffect, NOT useEffect: steps are never unmounted, only shown and hidden via a CSS\n // class (FormDisplay), so re-entering a handoff step whose embed already rendered goes through\n // a real render with the flag freshly reset to false. A passive effect runs after paint, which\n // would flash the placeholder over an embed that is already there for one frame -- the exact\n // jarring pop-in this component exists to remove. Correcting before paint closes that window.\n // jsdom never paints, so no test can catch a regression here; see WidgetStylesheet for the\n // same reasoning.\n const [externalWidgetContentShown, setExternalWidgetContentShown] = useState(false);\n useLayoutEffect(() => {\n if (!externalWidgetConfig) {\n setExternalWidgetContentShown(false);\n return undefined;\n }\n const anchorId = externalWidgetConfig.anchorId;\n const anchor = document.getElementById(anchorId);\n if (!anchor) {\n return undefined;\n }\n if (anchor.childElementCount > 0) {\n setExternalWidgetContentShown(true);\n return undefined;\n }\n const observer = new MutationObserver(() => {\n const el = document.getElementById(anchorId);\n if (el && el.childElementCount > 0) {\n setExternalWidgetContentShown(true);\n // Nothing left to watch, and a booking widget mutates its subtree constantly\n // once it is live -- keeping this attached would invoke the callback for the\n // rest of the step's lifetime for no benefit.\n observer.disconnect();\n }\n });\n observer.observe(anchor, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, [externalWidgetConfig]);\n\n const checkConditions = useCallback(() => {\n const newConditions = {};\n\n Object.entries(fieldTests.current).forEach(([name, f]) => {\n try {\n // Create context with null-safe helper functions\n const context = {\n ...getData(),\n ...stepData.current,\n // Helper for safe array/string checking\n safeIncludes: (value: any, searchElement: any): boolean => {\n if (Array.isArray(value)) return value.includes(searchElement);\n if (typeof value === \"string\") return value === searchElement;\n return false;\n },\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n newConditions[name] = (f as Function).call(context);\n } catch (error) {\n // Log error in development mode for debugging\n if (process.env.NODE_ENV === \"development\") {\n console.error(`Condition evaluation failed for field \"${name}\":`, error);\n }\n // Default to false if condition fails - field will be hidden\n newConditions[name] = false;\n }\n });\n\n if (!shallowEqualBooleanMap(newConditions, fieldConditions)) {\n setFieldConditions(newConditions);\n }\n }, [fieldConditions, getData]);\n\n useEffect(() => {\n const groups: { [key: string]: string[] } = {};\n\n for (const field of formStep.fields) {\n if (isGroupableFieldField(field) && !isHiddenSchedulingField(field)) {\n const groupName = field.mandatoryGroup;\n if (groupName) {\n if (!groups[groupName]) {\n groups[groupName] = [];\n }\n groups[groupName].push(field.name);\n }\n }\n }\n\n setMandatoryGroups(groups);\n }, [formStep.fields, isHiddenSchedulingField]);\n\n // Reset prefill tracking when formStep.fields is replaced by a new array reference\n // (e.g. via FORM_STEP_UPDATE). This must happen in the render phase — not useEffect —\n // for the same reason as the seeding loop below (see lines 247–252).\n const resetPrefillTracking = () => {\n prefilledFields.current.clear();\n hasNotifiedPrefill.current = false;\n stepData.current = {};\n };\n\n if (prevFieldsRef.current !== formStep.fields) {\n prevFieldsRef.current = formStep.fields;\n resetPrefillTracking();\n }\n\n // Seed prefilled values synchronously during render so they're available\n // as value props when children mount. This must happen in the render phase\n // (not useEffect/useLayoutEffect) because both fire children-first, and child\n // components (e.g. FormFieldTextInput) call onFieldChange on mount with their\n // default value, which would overwrite the prefill. The guards make this idempotent\n // and safe under Strict Mode double-renders.\n for (const field of formStep.fields) {\n if (\n hasFieldValue(field) &&\n !prefilledFields.current.has(field.name) &&\n !Object.prototype.hasOwnProperty.call(stepData.current, field.name)\n ) {\n stepData.current[field.name] = field.value;\n prefilledFields.current.add(field.name);\n }\n }\n\n // The step's values without those of hidden scheduling fields, for everything that leaves\n // the step: the prefill notify, the push and the next-step tracking.\n const visibleStepValues = (stepValues: object): { [key: string]: unknown } => {\n const visibleValues: { [key: string]: unknown } = { ...stepValues };\n\n for (const field of formStep.fields) {\n if (isHiddenSchedulingField(field)) {\n delete visibleValues[field.name];\n }\n }\n\n return visibleValues;\n };\n\n useEffect(() => {\n // check for initial data and look for conditions\n for (const field of formStep.fields) {\n if (field.type === \"CHIPS\") {\n // look for preselected chips\n const chipsSelectedFromProps = (field as FormChipsInput).items\n .filter((item) => isSelectableItem(item))\n .filter((item) => item.selected)\n .map((item) => item.id);\n\n // if we have length, set it (guard prevents overwriting prefilled or user-entered data)\n if (\n chipsSelectedFromProps.length > 0 &&\n !Object.prototype.hasOwnProperty.call(stepData.current, field.name)\n ) {\n stepData.current[field.name] = chipsSelectedFromProps;\n }\n }\n\n if (field.condition) {\n const conditionWithThis = addContextPrefix(field.condition);\n\n // eslint-disable-next-line no-new-func\n fieldTests.current[field.name] = new Function(`return (${conditionWithThis});`);\n }\n }\n\n // Notify parent of prefilled data once (not on every formStep.fields change)\n if (prefilledFields.current.size > 0 && !hasNotifiedPrefill.current) {\n hasNotifiedPrefill.current = true;\n handleData(visibleStepValues(stepData.current));\n }\n\n checkConditions();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [checkConditions, formStep.fields]); // once\n\n const validate: () => boolean = useCallback(() => {\n const errors: { [name: string]: FieldValidatorResult } = {};\n let isValid = true;\n const corrections: { [name: string]: string } = {};\n\n // Validate individual fields first\n formStep.fields.forEach((field) => {\n let result: FieldValidatorResult = { valid: true };\n\n const value = stepData.current[field.name];\n\n // Skip validation for hidden fields\n if (fieldConditions[field.name] === false || isHiddenSchedulingField(field)) {\n errors[field.name] = result;\n return;\n }\n\n // For dropdowns, always validate if mandatory (even if not touched)\n if (isFormDropdownInput(field)) {\n // Check if mandatory field has a value selected\n if (\n field.mandatory &&\n (value === undefined || value === null || value === \"none\")\n ) {\n result = {\n valid: false,\n message: field.mandatoryError || \"Please select an option\",\n };\n } else if (value !== undefined && value !== null && value !== \"none\") {\n // Check if the selected dropdown item requires free-form input\n const selectedItem = field.items.find((item) => item.id === value);\n\n if (selectedItem && (selectedItem as any).freeFormInput) {\n // Get the free-form field name (default to \"message\")\n const freeFormFieldName =\n (selectedItem as any).freeFormFieldName || \"message\";\n const freeFormValue = stepData.current[freeFormFieldName];\n\n // Validate that free-form field has a value\n // If validation fails, set error on the free-form field, not the dropdown\n if (\n !freeFormValue ||\n (typeof freeFormValue === \"string\" && freeFormValue.trim() === \"\")\n ) {\n // Set error on the free-form field specifically\n errors[freeFormFieldName] = {\n valid: false,\n message: \"Please specify additional details\",\n };\n // Mark the form as invalid\n result = {\n valid: false,\n message: \"\", // No error on dropdown itself\n };\n }\n }\n }\n }\n // Like dropdowns, a mandatory range is validated whether or not it was touched.\n // FormFieldDateRange only reports through onFieldChange once the user edits it,\n // so an untouched field never lands in stepData and the touched-only branch below\n // would skip it entirely - which is exactly how a mandatory range submitted empty.\n //\n // The inputs' own required/min/max cannot cover this: the step has no <form> and\n // Next is not type=\"submit\", so the browser never runs constraint validation.\n //\n // A half-filled range fails too. An open-ended window is not a date range, and\n // delivering one as a lead is worse than asking the user to finish.\n else if (isFormDateRangeInput(field)) {\n if (field.mandatory && !isCompleteRange(value)) {\n result = {\n valid: false,\n message: field.mandatoryError || \"Please select a date range\",\n };\n }\n }\n // Same reasoning as the range above, and the same failure to avoid: a\n // mandatory datetime needs BOTH halves, and a field the user never touched\n // has to fail rather than fall through the touched-only branch below.\n else if (isFormDateTimeInput(field)) {\n if (field.mandatory && !isCompleteDateTime(value)) {\n result = {\n valid: false,\n message: field.mandatoryError || \"Please select a date and a time\",\n };\n }\n }\n // Only validate other fields if they've been touched\n else if (Object.prototype.hasOwnProperty.call(stepData.current, field.name)) {\n if (isFormTextInput(field)) {\n if (field.mandatory === true && isEmptyString(value)) {\n result = {\n valid: false,\n message: field.mandatoryError || \"This field is mandatory\",\n };\n } else if (field.format === \"EMAIL\" && !isEmptyString(value)) {\n result = validateEmail(value);\n } else if (field.format === \"PHONE\" && !isEmptyString(value)) {\n result = validatePhoneNumber(value);\n if (result.valid) {\n const formattedNumber = formatUSPhoneNumber(value);\n if (formattedNumber !== value)\n corrections[field.name] = formattedNumber;\n }\n } else if (field.format === \"ZIP_CODE\" && !isEmptyString(value)) {\n result = validateZipCode(value);\n if (result.valid) {\n const formattedZip = formatZipCode(value);\n if (formattedZip !== value) corrections[field.name] = formattedZip;\n }\n }\n } else if (isFormChipsInput(field)) {\n if (field.minRequired && value.length < field.minRequired) {\n result = {\n valid: false,\n message: `Please select at least ${field.minRequired} option(s)`,\n };\n } else if (field.maxAllowed && value.length > field.maxAllowed) {\n result = {\n valid: false,\n message: `Please select no more than ${field.maxAllowed} option(s)`,\n };\n } else if (field.mandatory && value?.length !== 1) {\n result = { valid: false, message: \"Please select one option\" };\n }\n } else if (isFormDateInput(field) && field.mandatory && value == null) {\n result = { valid: false, message: \"Please select a day\" };\n } else if (isFormCheckInput(field) && field.mandatory && !value?.length) {\n // CHECK is a multi-select unless radio, so any selection satisfies mandatory\n result = {\n valid: false,\n message: field.mandatoryError || \"This field is mandatory\",\n };\n }\n }\n\n isValid = isValid && result.valid;\n errors[field.name] = result;\n });\n\n // Validate mandatoryGroups: only ONE field in the group is needed\n for (const [, fieldNames] of Object.entries(mandatoryGroups)) {\n const hasValue = fieldNames.some((name) => !isEmpty(stepData.current[name]));\n\n if (!hasValue) {\n // get the mandatoryError off the field\n const field = formStep.fields.find((f) => f.name === fieldNames[0]);\n const fieldError = fieldErrors[fieldNames[0]];\n const errorMessage =\n fieldError?.message ||\n field?.mandatoryError ||\n \"At least one of these fields is required\";\n\n // Mark each field in the group as invalid\n fieldNames.forEach((name) => {\n errors[name] = {\n valid: false,\n message: errorMessage,\n };\n });\n\n isValid = false;\n }\n }\n\n // Apply corrections if needed\n if (!isEmpty(corrections)) {\n stepData.current = { ...stepData.current, ...corrections };\n }\n\n // Only update state if different\n if (!fieldErrorsEqual(fieldErrors, errors)) {\n setFieldErrors(errors);\n }\n\n return isValid;\n }, [fieldConditions, fieldErrors, formStep.fields, mandatoryGroups, isHiddenSchedulingField]);\n\n const continueToNext = async () => {\n if (!validate() || isSubmitting) {\n return;\n }\n\n setIsSubmitting(true);\n try {\n pushData(stepData.current);\n\n // Track next_step event if tracking callback is provided\n if (onTrackNextStep && currentStepIndex !== undefined && totalSteps !== undefined) {\n const isLastStep = currentStepIndex === totalSteps - 1;\n onTrackNextStep(\n formStep.name,\n currentStepIndex,\n visibleStepValues(stepData.current),\n isLastStep\n );\n }\n\n if (nextStep) {\n await nextStep(formStep.nextAction === \"submit\");\n }\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const pushData = (stepValues: object) => {\n const data: object = visibleStepValues(stepValues);\n\n // The form merges what each push sends, so a hidden field's value pushed before\n // scheduling went off - stepping back pushes too - would outlive the field unless it\n // is cleared. Only keys the form already holds, so nothing new appears in the lead.\n const pushedData: object = getData();\n const pushedLabels: object = getDataWithLabels();\n const clearedData: { [key: string]: undefined } = {};\n const clearedLabels: { [key: string]: undefined } = {};\n\n for (const field of formStep.fields) {\n if (isHiddenSchedulingField(field)) {\n for (const name of leadFieldNamesOf(field)) {\n if (Object.prototype.hasOwnProperty.call(pushedData, name)) {\n clearedData[name] = undefined;\n }\n if (Object.prototype.hasOwnProperty.call(pushedLabels, name)) {\n clearedLabels[name] = undefined;\n }\n }\n }\n }\n\n // Cleared first, so a visible field writing the same key still wins.\n const augmentedData: { [key: string]: unknown } = { ...clearedData, ...data };\n\n // Now create the equivalent with string representation for templating\n const dataWithLabels: { [name: string]: string } = {};\n\n // One place that turns collected times into the `<field>_start` / `<field>_end`\n // lead fields, so the chips field and the datetime field cannot drift apart on\n // the shape a CRM receives.\n const applyTimes = (fieldName: string, startTimes: string[], endTimes: string[]) => {\n if (startTimes.length > 0) {\n const joinedStart = startTimes.join(\", \");\n augmentedData[`${fieldName}_start`] = joinedStart;\n dataWithLabels[`${fieldName}_start`] = joinedStart;\n }\n if (endTimes.length > 0) {\n const joinedEnd = endTimes.join(\", \");\n augmentedData[`${fieldName}_end`] = joinedEnd;\n dataWithLabels[`${fieldName}_end`] = joinedEnd;\n }\n };\n\n for (const fieldName of Object.keys(data)) {\n const value = data[fieldName];\n\n const formField = formStep.fields.find((field) => field.name === fieldName);\n\n if (formField?.type === \"CHIPS\" && value !== undefined) {\n const valueLabels: string[] = [];\n const startTimes: string[] = [];\n const endTimes: string[] = [];\n\n (value as string[]).forEach((s) => {\n const item = (formField as FormChipsInput).items.find((chip) => chip.id === s);\n if (item) {\n valueLabels.push(item.label);\n const timedItem = item as SelectableItem;\n if (timedItem.startTime) {\n startTimes.push(timedItem.startTime);\n }\n if (timedItem.endTime) {\n endTimes.push(timedItem.endTime);\n }\n }\n });\n\n dataWithLabels[fieldName] = joinWithAnd(valueLabels);\n applyTimes(fieldName, startTimes, endTimes);\n } else if (formField?.type === \"DATETIME\" && value !== undefined) {\n // One field, up to six lead fields: the label under the field's own name -\n // the same key and shape the chips field it replaces emits today - plus\n // the start, the optional end, the date, the combined timestamp and the\n // zone that timestamp's wall clock belongs to.\n const dateTimeField = formField as FormDateTimeInputWithTimeZone;\n const selection = value as FormDateTimeValue;\n\n augmentedData[fieldName] = selection.label;\n dataWithLabels[fieldName] = selection.label;\n\n applyTimes(\n fieldName,\n selection.start ? [selection.start] : [],\n selection.end ? [selection.end] : []\n );\n\n // Never hardcoded: a tenant may submit the pair under its own names.\n const dateFieldName = dateTimeField.dateFieldName || DEFAULT_DATE_FIELD_NAME;\n augmentedData[dateFieldName] = selection.date;\n dataWithLabels[dateFieldName] = selection.date;\n\n const dateTimeFieldName =\n dateTimeField.dateTimeFieldName || DEFAULT_DATE_TIME_FIELD_NAME;\n augmentedData[dateTimeFieldName] = selection.datetime;\n dataWithLabels[dateTimeFieldName] = selection.datetime;\n\n // What makes the timestamp above readable as a business wall clock rather\n // than whatever a browser happened to submit under a field called `date`.\n // Absent when the schedule's zone was unusable and the picker fell back to\n // the host's, because then it would be a lie.\n const timeZone = timeZoneOf(dateTimeField.schedule);\n\n if (timeZone) {\n const timeZoneFieldName =\n dateTimeField.timeZoneFieldName || DEFAULT_TIME_ZONE_FIELD_NAME;\n augmentedData[timeZoneFieldName] = timeZone;\n dataWithLabels[timeZoneFieldName] = timeZone;\n }\n } else if (formField?.type === \"DROPDOWN\" && value !== undefined) {\n // Find the selected item by ID\n const item = (formField as FormDropdownInput).items.find(\n (item) => item.id === value\n );\n if (item) {\n // Use label if available, otherwise format the ID (remove _ and capitalize)\n if (item.label && item.label.trim().length > 0) {\n dataWithLabels[fieldName] = item.label;\n } else {\n // Format ID: \"contact_us\" -> \"Contact Us\"\n dataWithLabels[fieldName] = value\n .replace(/_/g, \" \")\n .split(\" \")\n .map(\n (word: string) =>\n word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()\n )\n .join(\" \");\n }\n } else {\n dataWithLabels[fieldName] = value;\n }\n } else if (formField?.type === \"DATE\" && value !== undefined) {\n dataWithLabels[fieldName] = reformatDate(value);\n } else {\n dataWithLabels[fieldName] = value;\n }\n }\n\n handleData(augmentedData);\n handleDataWithLabels({ ...clearedLabels, ...dataWithLabels });\n };\n\n const goBackToPrevious = () => {\n pushData(stepData.current);\n\n if (prevStep) {\n prevStep();\n }\n };\n\n const isNextDisabled = () => {\n // for each of the fields, check...\n // 1. for the required ones, do we have entries and are they are valid\n // 2. for the optional ones, if they have any content, make sure they are value\n\n for (const key in fieldErrors) {\n // make sure we are only looking at required fields\n if (fieldConditions[key] === false) {\n continue;\n }\n if (!fieldErrors[key].valid) {\n return true;\n }\n }\n return false;\n };\n\n const onFieldChange = useCallback(\n (name: string, value: string | string[] | object | undefined) => {\n const isFirst = !Object.prototype.hasOwnProperty.call(stepData.current, name);\n\n // When a field was just prefilled (e.g. after FORM_STEP_UPDATE reset), the child\n // component's stale useEffect may fire onFieldChange with its old value before it\n // syncs to the new value prop. Block stale updates; clear the guard once the child\n // reports the matching prefilled value (or any subsequent call after sync).\n if (prefilledFields.current.has(name)) {\n if (!isFirst && stepData.current[name] === value) {\n // Child synced to the prefilled value — clear guard, no-op (value unchanged)\n prefilledFields.current.delete(name);\n return;\n }\n if (!isFirst && stepData.current[name] !== value) {\n // Stale update from child's old state — skip to preserve prefill\n return;\n }\n }\n\n if (!isFirst && stepData.current[name] === value) {\n return;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n value = undefined; // treat empty arrays as undefined\n }\n\n stepData.current = { ...stepData.current, [name]: value };\n\n // Sync to parent ref for tracking purposes\n if (currentStepDataRef) {\n currentStepDataRef.current = stepData.current as Record<string, unknown>;\n }\n\n checkConditions();\n\n if (!isEmpty(fieldErrors)) {\n validate();\n }\n },\n [checkConditions, fieldErrors, validate, currentStepDataRef]\n );\n\n const config = useContext(SearchWidgetConfigContext);\n\n checkConditions();\n\n const getFields = (): JSX.Element[] => {\n if (!formStep) {\n return [];\n }\n\n const stepFields = formStep.fields || [];\n\n // The card goes where the first of the hidden fields would have been, so it reads in\n // the place the visitor would otherwise have been asked.\n const firstHiddenIndex = stepFields.findIndex((field) => isHiddenSchedulingField(field));\n\n const fields = stepFields.map((field, index) => {\n let fieldComponent: JSX.Element | null;\n // The last field of the step gets \"done\" rather than \"next\" on the mobile keyboard\n const isLastField = index === stepFields.length - 1;\n\n if (isHiddenSchedulingField(field)) {\n return index === firstHiddenIndex ? (\n <div key={index} className={`${styles.xapp_formfield} ${styles.active}`}>\n <FormFieldCard\n field={{\n name: \"scheduling_disabled\",\n type: \"CARD\",\n text: SCHEDULING_DISABLED_MESSAGE,\n }}\n onFieldChange={onFieldChange}\n />\n </div>\n ) : null;\n }\n\n switch (field.type) {\n case \"TEXT\":\n if ((field as FormFieldTextAddressInput).format === \"ADDRESS\") {\n fieldComponent = (\n <FormFieldTextInputAddress\n key={field.name}\n field={field as FormFieldTextAddressInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name]}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n googleMapsApiKey={config.googleMapsApiKey}\n mapsBaseUrl={config.mapsBaseUrl}\n />\n );\n } else {\n fieldComponent = (\n <FormFieldTextInput\n key={field.name}\n field={field as FormTextInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name]}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n isLastField={isLastField}\n />\n );\n }\n break;\n case \"DROPDOWN\": {\n // Compute free-form error message if applicable\n const dropdownField = field as FormDropdownInput;\n const currentValue = stepData.current[dropdownField.name];\n let freeFormError: string | undefined;\n\n if (currentValue && currentValue !== \"none\") {\n const selectedItem = dropdownField.items.find(\n (item) => item.id === currentValue\n );\n if (selectedItem && (selectedItem as any).freeFormInput) {\n const freeFormFieldName =\n (selectedItem as any).freeFormFieldName || \"message\";\n freeFormError = fieldErrors[freeFormFieldName]?.message;\n }\n }\n\n fieldComponent = (\n <FormFieldDropdown\n key={field.name}\n field={dropdownField}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n freeFormErrorMessage={freeFormError}\n />\n );\n break;\n }\n case \"CHECK\":\n fieldComponent = (\n <FormFieldSelect\n key={field.name}\n field={field as FormChipsInput}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n />\n );\n break;\n case \"CHIPS\":\n fieldComponent = (\n <FormFieldChips\n key={field.name}\n field={field as FormChipsInput}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n value={stepData.current[field.name] as string[] | undefined}\n />\n );\n break;\n case \"DATE\":\n const busyDays = context?.busyDays;\n\n fieldComponent = (\n <FormFieldDate\n key={field.name}\n field={field as FormDateInput}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n busyDays={busyDays}\n loading={loading}\n />\n );\n break;\n case \"DATETIME\":\n fieldComponent = (\n <FormFieldDateTime\n key={field.name}\n field={field as FormDateTimeInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name] as FormDateTimeValue | undefined}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n busyDays={context?.busyDays}\n offeringsByDate={offeringsByDate}\n preselectFirstAvailable={props.preselectFirstAvailableDate}\n />\n );\n break;\n case \"DATERANGE\":\n fieldComponent = (\n <FormFieldDateRange\n key={field.name}\n field={field as FormDateRangeInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name] as FormDateRangeValue | undefined}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n isLastField={isLastField}\n />\n );\n break;\n\n case \"CARD\":\n fieldComponent = (\n <FormFieldCard\n key={field.name}\n field={replaceValues(field, getDataWithLabels()) as FormCardInput}\n onFieldChange={onFieldChange}\n />\n );\n break;\n\n default:\n fieldComponent = null;\n }\n\n return (\n <div\n key={index}\n className={`${styles.xapp_formfield} ${\n fieldConditions[field.name] !== false ? styles.active : \"\"\n }`}\n >\n {fieldComponent}\n </div>\n );\n });\n\n return fields.filter((field): field is JSX.Element => field !== null);\n };\n\n const fullBleed = !!formStep && (formStep as FormStepWithUnloadWarning).fullBleed;\n\n return (\n <div className={fullBleed ? styles.xapp_step_full_bleed : undefined}>\n {!hideIntro && !!formStep && (formStep.title || formStep.subtitle) && (\n <div className={styles.xapp_formfield_title}>\n {!!formStep.title && <p>{formStep.title}</p>}\n {!!formStep.subtitle && (\n <p className={styles.xapp_formfield_subtitle}>{formStep.subtitle}</p>\n )}\n </div>\n )}\n\n {!!formStep && (formStep as FormStepWithUnloadWarning).warnBeforeUnloadMessage && (\n <div\n style={{\n backgroundColor: \"#fff3cd\",\n color: \"#856404\",\n padding: \"12px 16px\",\n marginBottom: \"16px\",\n borderRadius: \"4px\",\n border: \"1px solid #ffeaa7\",\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n }}\n >\n <span style={{ fontSize: \"20px\" }}>⚠️</span>\n <span>{(formStep as FormStepWithUnloadWarning).warnBeforeUnloadMessage}</span>\n </div>\n )}\n\n {isFormStepIframe(formStep) && (\n <div className={styles.xapp_step_iframe_wrapper}>\n <iframe\n src={formStep.iframe.src}\n title={formStep.title}\n width={formStep.iframe.width || \"100%\"}\n height={formStep.iframe.height || \"100%\"}\n frameBorder=\"0\"\n allowFullScreen\n />\n </div>\n )}\n {isFormStepExternalWidget(formStep) && (\n <div className={styles.xapp_external_widget_container}>\n <div\n id={formStep.externalWidget.anchorId}\n className={styles.xapp_external_widget_anchor}\n />\n {isActive &&\n externalWidgetOutcome === \"pending\" &&\n !externalWidgetContentShown && (\n <div\n className={styles.xapp_external_widget_loading}\n role=\"status\"\n aria-live=\"polite\"\n >\n <span className={styles.xapp_external_widget_spinner}>\n <SpinnerIcon />\n </span>\n <p>Finding available appointments&hellip;</p>\n </div>\n )}\n {(externalWidgetOutcome === \"no_render\" || externalWidgetOutcome === \"error\") &&\n !formStep.externalWidget.fallbackStep && (\n <div className={styles.xapp_external_widget_fallback}>\n <p>\n {\n \"We're sorry, we couldn't load the booking form. Please try again later.\"\n }\n </p>\n </div>\n )}\n </div>\n )}\n <div>{getFields()}</div>\n\n {!!submitError && (\n <div className={styles.xapp_submit_error} role=\"alert\">\n <p>{submitError}</p>\n </div>\n )}\n\n <div\n className={`${styles.xapp_form_actions} ${\n (formStep as any).final ? styles.xapp_form_actions_final : \"\"\n }`}\n // A marker as well as the class: the class is what the css reads, the marker is\n // what a test can see (this module's classes do not resolve under jest).\n {...((formStep as any).final ? { \"data-xapp-final-actions\": \"\" } : {})}\n >\n {/* For final steps, show the next button centered above the previous button --\n or beside it, when the theme asks for `finalButtonPlacement: \"inline\"`. */}\n {!!nextStep && formStep.nextAction !== \"omit\" && (formStep as any).final && (\n <div className={styles.xapp_final_button_container}>\n <button\n type=\"button\"\n className={`${styles.xapp_step_button} ${\n isNextDisabled() || isSubmitting\n ? styles.xapp_disabled_button\n : formStep.nextLabel\n ? styles.xapp_secondary_button\n : styles.xapp_primary_button\n }`}\n disabled={isSubmitting}\n onClick={continueToNext}\n >\n {isSubmitting ? \"Loading...\" : formStep.nextLabel || \"Next\"}\n </button>\n </div>\n )}\n\n <div className={styles.xapp_form_nav_buttons}>\n {prevStep === undefined && <div className={styles.xapp_dummy_button}></div>}\n\n {!!prevStep && formStep.previousAction !== \"omit\" && (\n <button\n type=\"button\"\n className={`${styles.xapp_step_button} ${styles.xapp_primary_button} ${styles.xapp_back_button}`}\n onClick={goBackToPrevious}\n aria-label={formStep.previousLabel || \"Previous\"}\n >\n {/* Both shapes are rendered and the theme displays exactly one -- see\n getBackButtonStyle. The arrow is decorative; the accessible name is\n on the button itself, so the icon variant is not a nameless control. */}\n <span className={styles.xapp_back_button_label}>\n {formStep.previousLabel || \"Previous\"}\n </span>\n <span className={styles.xapp_back_button_icon} aria-hidden=\"true\">\n &#8592;\n </span>\n </button>\n )}\n\n {/* For non-final steps, show the next button in the normal position */}\n {!!nextStep && formStep.nextAction !== \"omit\" && !(formStep as any).final && (\n <button\n type=\"button\"\n className={`${styles.xapp_step_button} ${\n isNextDisabled() || isSubmitting\n ? styles.xapp_disabled_button\n : formStep.nextLabel\n ? styles.xapp_secondary_button\n : styles.xapp_primary_button\n }`}\n disabled={isSubmitting}\n onClick={continueToNext}\n >\n {isSubmitting ? \"Loading...\" : formStep.nextLabel || \"Next\"}\n </button>\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default FormStepDisplay;\n","\nimport {\n FormInput,\n FormTextInput,\n FormChipsInput,\n FormDateRangeInput,\n FormDateTimeInput,\n FormDropdownInput,\n} from \"stentor-models\";\n\nexport function isFormTextInput(field: FormInput): field is FormTextInput {\n return !!field && field.type === \"TEXT\";\n}\n\nexport function isFormChipsInput(field: FormInput): field is FormChipsInput {\n return !!field && field.type === \"CHIPS\";\n}\n\nexport function isFormDateInput(field: FormInput): field is FormChipsInput {\n return !!field && field.type === \"DATE\";\n}\n\nexport function isFormCheckInput(field: FormInput): field is FormChipsInput {\n return !!field && field.type === \"CHECK\";\n}\n\nexport function isFormDateRangeInput(field: FormInput): field is FormDateRangeInput {\n return !!field && field.type === \"DATERANGE\";\n}\n\nexport function isFormDateTimeInput(field: FormInput): field is FormDateTimeInput {\n return !!field && field.type === \"DATETIME\";\n}\n\nexport function isFormDropdownInput(field: FormInput): field is FormDropdownInput {\n return !!field && field.type === \"DROPDOWN\";\n}","import React, { FC } from \"react\";\n\nimport { PartnerFormFraming } from \"@xapp/stentor-form-widget-channel\";\n\nimport styles from \"./FormFrame.module.scss\";\n\nexport interface FormFrameProps {\n /**\n * The partner chrome to draw. Without it nothing here renders anything but\n * the children.\n */\n readonly framing?: PartnerFormFraming;\n /**\n * Draw the frame and the tab.\n *\n * Off for a booking handoff step -- the partner's embed brings its own frame,\n * and a second one around it reads as a mistake.\n */\n readonly framed?: boolean;\n readonly children?: React.ReactNode;\n}\n\n/**\n * The partner framing around one form step: the tab off the top of the card, an\n * optional intro block carrying the PRESET's own copy, and the framed card itself.\n *\n * The intro deliberately does not fall back to the step's title. Step titles are\n * progress labels sized for a stepper -- \"Request\", \"Contact Information\" -- and\n * rendering one here turned it into a page-sized banner over the tab that nobody\n * authored. A preset that wants a headline says so with `framing.introTitle`.\n *\n * Only ever rendered when a partner style preset resolved, which only happens on\n * the stand-alone page -- see resolveFormStyle.\n */\nexport const FormFrame: FC<FormFrameProps> = (props) => {\n const { framing, framed, children } = props;\n\n const tabLabel = framing?.tabLabel;\n const title = framing?.introTitle;\n const subtitle = framing?.introSubtitle;\n const introPlacement = framing?.introPlacement || \"above-tab\";\n\n const intro =\n title || subtitle ? (\n <div className={styles.xapp_form_frame_intro} data-xapp-form-frame-intro=\"\">\n {!!title && (\n <h2 className={styles.xapp_form_frame_title} data-xapp-form-frame-title=\"\">\n {title}\n </h2>\n )}\n {!!subtitle && (\n <p className={styles.xapp_form_frame_subtitle} data-xapp-form-frame-subtitle=\"\">\n {subtitle}\n </p>\n )}\n </div>\n ) : null;\n\n return (\n <div className={styles.xapp_form_frame_root}>\n {introPlacement === \"above-tab\" && intro}\n {/* The tab is a sibling ABOVE the card, not absolutely positioned inside it: in the\n approved design it is a tab sitting on the card's top edge (rounded top corners\n only, square bottom), and the card is pulled up to tuck under it. Centring a fully\n rounded pill over the border reads as a badge instead. The row keeps the intro's\n white background running behind the tab so the two read as one white block. */}\n {framed && !!tabLabel && (\n <div className={styles.xapp_form_frame_tab_row}>\n <span className={styles.xapp_form_frame_tab} data-xapp-form-frame-tab=\"\">\n {tabLabel}\n </span>\n </div>\n )}\n <div\n className={framed ? styles.xapp_form_frame_framed : styles.xapp_form_frame_plain}\n data-xapp-form-frame={framed ? \"framed\" : \"plain\"}\n >\n {introPlacement === \"inline\" && intro}\n {children}\n </div>\n </div>\n );\n};\n\nexport default FormFrame;\n","import React from \"react\";\n\nimport { FormHeaderItem } from \"stentor-models\";\n\nimport styles from './SimpleNavigationHeader.module.scss';\n\ninterface SimpleNavigationHeaderProps {\n items: FormHeaderItem[];\n onHeaderClick(step: string): void;\n labelHeader?: boolean;\n stepName: string;\n isShowCase?: boolean;\n}\n\nexport const SimpleNavigationHeader: React.FC<SimpleNavigationHeaderProps> = (\n props: SimpleNavigationHeaderProps\n) => {\n const { items, onHeaderClick, labelHeader, stepName, isShowCase } = props;\n\n if (!!labelHeader) {\n const header = items.find((item) => item.step === stepName);\n const headerText = header?.label;\n\n // Nothing to say, so nothing is drawn. This used to render the same coloured Box with an\n // empty div inside, which on a step the header has no label for -- the CostGuide booking\n // handoff is not in the header array -- painted a bare teal band above the partner's own\n // form. The band was never authored; it is the header showing up with no content.\n if (headerText === undefined) {\n return null;\n }\n\n return (\n <div\n className={`${styles.xapp_navigation_header_row} ${\n !!isShowCase ? styles.xapp_navigation_header_showcase : styles.xapp_navigation_header_container\n }`}>\n <h4 className={styles.xapp_navigation_header_title}>{headerText}</h4>\n </div>\n );\n } else {\n return (\n <div className={`${styles.xapp_navigation_header_row} ${styles.xapp_navigation_header}`}>\n <div className={styles.xapp_navigation_header_track}>\n {items.map((item, index) => (\n <div key={index} className={styles.xapp_navigation_header_step}>\n <button\n type=\"button\"\n aria-label={item.label}\n className={`${styles.xapp_navigation_header} ${styles.xapp_navigation_header_dot}`}\n onClick={() => {\n onHeaderClick(`${item.step}`);\n }}\n />\n <p className={styles.xapp_navigation_header_label}>{item.label}</p>\n </div>\n ))}\n </div>\n </div>\n );\n }\n};\n","/*! Copyright (c) 2025, XAPP AI */\n\n/**\n * From a given zip code, determine if it is in the service area defined by the provided zip codes.\n *\n * @param zip Zip code as a string\n * @param zipCodes Array of zip codes that define the service area, masking is supported, such as \"12345\", \"1234*\", \"123*5\", \"12*45\".\n */\nexport function isInServiceArea(zip: string, zipCodes: string[]): boolean {\n // Normalize input ZIP: keep only 5 digits\n const baseZip = zip.slice(0, 5);\n\n const foundSupportedZip = zipCodes.find((supportedZip) => {\n // If the supported zip code is an exact match, return true\n if (supportedZip === baseZip) {\n return true;\n }\n\n // If the supported zip code contains asterisks, we need to check for a match\n if (supportedZip.includes(\"*\")) {\n // Replace asterisks with regex wildcard and create a regex pattern\n const regexPattern = supportedZip.replace(/\\*/g, \"\\\\d\") + \"$\";\n const regex = new RegExp(`^${regexPattern}`);\n return regex.test(baseZip);\n }\n\n // If no match found, return false\n return false;\n });\n\n // If we found a supported zip code, return true, otherwise false\n return !!foundSupportedZip;\n}\n","/**\n * Extracts the ZIP code from a given address string.\n *\n * @param address The address string to extract the ZIP code from.\n * @returns The extracted ZIP code, or undefined if no valid ZIP code is found.\n */\nexport function extractZipFromAddress(address?: string): string | undefined {\n if (!address) return undefined;\n\n const matches = address.match(/\\b\\d{5}(?:-\\d{4})?\\b/g);\n if (!matches) return undefined;\n\n for (let i = matches.length - 1; i >= 0; i--) {\n const zip = matches[i];\n const index = address.indexOf(zip);\n const before = address.slice(0, index);\n\n // Heuristic 1: ZIP appears after a comma or 2-letter state code\n if (/(,|\\b[A-Z]{2})\\s*$/.test(before.trim())) {\n return zip;\n }\n\n // Heuristic 2: ZIP appears far enough into the string (e.g. not a house number)\n if (index > 15) {\n return zip;\n }\n }\n\n return undefined;\n}\n","import React, { FC, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { FormStep, MultistepForm } from \"stentor-models\";\n\nimport { FormActionResponseData, FormNextData, FormStepUpdateDisplay } from \".\";\nimport { FormStepDisplay, isFormStepExternalWidget } from \"../FormStepDisplay\";\nimport { FormFrame } from \"../FormFrame\";\nimport { ExternalWidgetConfig } from \"../../utils/useExternalWidget\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\n\nimport { SimpleNavigationHeader } from \"../SimpleNavigationHeader\";\nimport { err } from \"../../utils\";\nimport { addContextPrefix } from \"../../utils/comparator\";\nimport { isInServiceArea } from \"../../utils/isInServiceArea\";\nimport { extractZipFromAddress } from \"../../utils/extractZipFromAddress\";\n\nimport styles from \"./FormDisplay.module.scss\";\n\ninterface FormNextResponse {\n displays?: FormStepUpdateDisplay[];\n}\n\n/**\n * Shown on the step whose FORM_SUBMIT dispatch failed. That dispatch is the request\n * that creates the lead, so a silent failure loses it -- the user must be told rather\n * than left believing they submitted (issue #1373).\n */\nexport const SUBMIT_ERROR_MESSAGE =\n \"We couldn't submit your information. Please check your connection and try again.\";\n\n/**\n * How long the handoff step waits for the FORM_SUBMIT response before injecting the partner\n * script with only the static config.\n *\n * The handoff is reached by a submit, and FormWidget dispatches FORM_SUBMIT fire-and-forget so the\n * UI is not blocked -- the step goes active before the response lands. The per-submission values\n * (zipCode, name, trade) only exist in that response, and a partner script that reads its config\n * global once at load will never see them if we inject first. CostGuide does exactly that: it read\n * the static config, found no zip, and asked the visitor for one we already had.\n *\n * Waiting is bounded so a failed or slow submit still reaches the partner's form. That is degraded\n * -- no prefill -- rather than broken.\n */\nexport const EXTERNAL_WIDGET_CONFIG_WAIT_MS = 5000;\n\ninterface StepOverride {\n fields?: unknown[];\n externalWidget?: {\n config?: Record<string, string | number | boolean>;\n };\n}\n\n/**\n * Extended FormStep interface to support additional per-step properties not yet in stentor-models.\n */\nexport interface ExtendedFormStep extends FormStep {\n /**\n * If true, shows a browser warning dialog when the user attempts to leave the page.\n * Useful for confirmation steps where the user hasn't submitted yet.\n */\n warnBeforeUnload?: boolean;\n /**\n * Optional message to display in a visual warning banner.\n * The browser's beforeunload dialog will show a generic message (browsers ignore custom messages for security).\n * This message is displayed in a yellow warning banner for better visibility, especially on mobile.\n */\n warnBeforeUnloadMessage?: string;\n /**\n * When true, fires a FORM_NEXT server callback before advancing past this step.\n * The server can return a FORM_STEP_UPDATE display to dynamically replace the next step's fields.\n * If the call fails or exceeds 3 seconds, the widget proceeds with the existing client-side fields.\n */\n serverCallback?: boolean;\n}\n\ninterface StandardFormData {\n address?: string;\n email?: string;\n full_name?: string;\n first_name?: string;\n last_name?: string;\n phone?: string;\n zip?: string;\n zip_code?: string;\n\n [key: string]: string | undefined;\n}\n\nexport interface FormDisplayProps {\n readonly form: MultistepForm;\n readonly loading: boolean;\n /**\n * Zero-based step to open on, instead of the first.\n *\n * For previews that want to show a particular step -- the booking preview on\n * get.xapp.ai opens on the date and time step, because the calendar is the\n * part worth showing. Applied once, when the form first arrives with steps,\n * so navigating away from it sticks. An index the form has no step for is\n * ignored and the form opens where it always would.\n */\n readonly initialStep?: number;\n /**\n * Open the date/time step on the soonest day that has times, rather than on\n * \"Select a date to see the available times.\"\n *\n * For a preview that lands straight on that step: an empty column beside a\n * calendar reads as a form with nothing to offer. Off by default -- on a real\n * booking page a preselected date is one the customer never chose.\n */\n readonly preselectFirstAvailableDate?: boolean;\n /**\n * Fired with the step index when {@link FormDisplayProps.initialStep} is\n * actually applied, and not at all when it is ignored.\n *\n * FormWidget keeps its own `currentStepRef` and only ever writes it from the\n * next/previous tracking callbacks, so a form that jumps straight to a step\n * without saying so leaves that ref on 0 -- and every abandonment path (close,\n * the beforeunload beacon, the tab-hidden timeout) reads it for lastStepIndex\n * and completionPercentage. This keeps the two in step.\n */\n onTrackInitialStep?: (stepIndex: number) => void;\n /**\n * Dispatches the form action. For FORM_SUBMIT this is the request that creates the\n * lead, so the returned promise is awaited and a rejection is surfaced to the user\n * -- see onSubmitForm. Implementations that return void keep the old fire-and-forget\n * behaviour.\n */\n onActionResponse(data: unknown, action: string): void | Promise<unknown>;\n isShowCase?: boolean;\n /**\n * Callback to track next_step event\n */\n onTrackNextStep?: (\n stepName: string,\n stepIndex: number,\n stepData: Record<string, unknown>,\n isLastStep: boolean\n ) => void;\n /**\n * Callback to track previous_step event\n */\n onTrackPreviousStep?: (\n fromStepName: string,\n fromStepIndex: number,\n toStepName: string,\n toStepIndex: number\n ) => void;\n /**\n * Callback to track submit event\n */\n onTrackSubmit?: (\n stepName: string,\n stepIndex: number,\n completedData: Record<string, unknown>,\n totalSteps: number\n ) => void;\n /**\n * Callback to track a FORM_SUBMIT dispatch that failed outright. onTrackSubmit fires\n * on a different endpoint before the dispatch, so without this a lost lead leaves a\n * submit event behind and no counter-signal at all.\n */\n onTrackSubmitFailure?: (\n stepName: string,\n stepIndex: number,\n totalSteps: number,\n reason: string\n ) => void;\n /**\n * Ref to sync current step data for tracking purposes\n */\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /**\n * When provided, fires a FORM_NEXT request before advancing to the next step.\n * The server can return a FORM_STEP_UPDATE display to replace the next step's fields.\n * If the call fails or exceeds 3 seconds, the widget proceeds with the existing fields.\n */\n onFormNext?: (data: FormNextData) => Promise<unknown>;\n /**\n * A FORM_STEP_UPDATE display extracted from the (fire-and-forget) FORM_SUBMIT\n * response, forwarded down from FormWidget. A new object reference triggers\n * applying the update to the named step's overrides -- see the effect below.\n */\n stepUpdate?: FormStepUpdateDisplay;\n /**\n * Callback to track a booking-widget handoff step's anchor gaining content\n * within its render timeout\n */\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n /**\n * Callback to track a booking-widget handoff step's render timeout elapsing\n * with an empty anchor\n */\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n /**\n * Callback to track the partner script invoking the configured success callback\n */\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n /**\n * Callback to track a booking-widget handoff step's script failing to load\n */\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n}\n\nexport const FormDisplay: FC<FormDisplayProps> = (props) => {\n const {\n form,\n onActionResponse,\n isShowCase,\n loading,\n onTrackNextStep,\n onTrackPreviousStep,\n onTrackSubmit,\n onTrackSubmitFailure,\n currentStepDataRef,\n initialStep,\n preselectFirstAvailableDate,\n onTrackInitialStep,\n onFormNext,\n stepUpdate,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n } = props;\n // TODO: const title = form?.title;\n\n // Partner chrome from a resolved style preset. Undefined for an embedded form --\n // presets only ever resolve on the stand-alone page -- so the markup below is\n // byte for byte what it was before presets existed.\n const { framing } = useContext(SearchWidgetConfigContext);\n\n const [currentStep, setCurrentStep] = useState(0);\n /** Whether {@link FormDisplayProps.initialStep} has been honoured yet. */\n const appliedInitialStep = useRef(false);\n const [stepOverrides, setStepOverrides] = useState<Record<string, StepOverride>>({});\n // The index of the step whose submit failed, so the message renders on that step\n // only -- an error shown on some *other* step would be nonsense.\n //\n // In practice this is visible for the final step, which is the one that matters:\n // it never advances, so it is still on screen when its dispatch rejects. A\n // non-final submitting step has already advanced by then and inactive steps are\n // display:none, so its banner stays hidden unless the user navigates back to it.\n // That is deliberate: its submit is not the lead (the final one carries all of\n // formData), and blocking the advance would strand the user short of the step that\n // does create the lead. onTrackSubmitFailure still fires for it either way.\n const [failedSubmitStep, setFailedSubmitStep] = useState<number | undefined>(undefined);\n // const [submitted, setSubmitted] = useState(false);\n\n // Applies a FORM_STEP_UPDATE display (from either a FORM_NEXT or FORM_SUBMIT\n // response) to the named step's overrides. externalWidget.config is\n // shallow-merged over whatever config is already present (the static step\n // definition, or an earlier update), with the new values winning on conflict.\n // A fields-only update behaves exactly as before: it fully replaces the\n // override's fields, leaving any existing externalWidget override untouched.\n const applyFormStepUpdate = (display: FormStepUpdateDisplay) => {\n const stepName = display.step;\n if (!stepName) {\n return;\n }\n setStepOverrides((prev) => {\n const existing = prev[stepName];\n const next: StepOverride = { fields: display.fields || [] };\n if (display.externalWidget?.config) {\n handoffConfigSettledRef.current[stepName] = true;\n next.externalWidget = {\n config: {\n ...existing?.externalWidget?.config,\n ...display.externalWidget.config,\n },\n };\n } else if (existing?.externalWidget) {\n next.externalWidget = existing.externalWidget;\n }\n return { ...prev, [stepName]: next };\n });\n };\n\n // Applies a FORM_STEP_UPDATE surfaced from the fire-and-forget FORM_SUBMIT\n // response. `stepUpdate` is a fresh object reference each time FormWidget\n // detects one, so this only ever runs on a genuine new update.\n useEffect(() => {\n if (stepUpdate) {\n applyFormStepUpdate(stepUpdate);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [stepUpdate]);\n\n // True from the moment a submit starts advancing to a handoff step until that submit settles.\n // See EXTERNAL_WIDGET_CONFIG_WAIT_MS.\n const [awaitingHandoffConfig, setAwaitingHandoffConfig] = useState(false);\n // The wait is a once-per-handoff-step thing, keyed by step name. Once per FORM would be\n // wrong twice over: a visitor who steps back and returns would re-arm the wait and sit in\n // front of a spinner over an embed that already rendered, and a form with a SECOND handoff\n // step would inherit the first's settle, never arm its own wait, and hand that partner the\n // static config on the render it became active.\n const handoffConfigSettledRef = useRef<Record<string, boolean>>({});\n\n // Bounds the wait above. Reset per step so returning to a handoff waits again rather than\n // inheriting a previous step's expiry.\n const [externalWidgetWaitElapsed, setExternalWidgetWaitElapsed] = useState(false);\n useEffect(() => {\n setExternalWidgetWaitElapsed(false);\n const activeStep = form.steps?.[currentStep];\n if (!activeStep || !isFormStepExternalWidget(activeStep)) {\n return undefined;\n }\n const timer = setTimeout(() => {\n setExternalWidgetWaitElapsed(true);\n // Given up on for good, for THIS step, not just for this pass.\n handoffConfigSettledRef.current[activeStep.name] = true;\n setAwaitingHandoffConfig(false);\n }, EXTERNAL_WIDGET_CONFIG_WAIT_MS);\n return () => clearTimeout(timer);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [currentStep]);\n\n const fieldTests = useRef({});\n\n useEffect(() => {\n if (Array.isArray(form.steps) && form.steps.length > 0) {\n for (const step of form.steps) {\n if (step.condition) {\n const conditionWithThis = addContextPrefix(step.condition, \"context\", [\n \"isInServiceArea\",\n ]);\n\n fieldTests.current[step.name] = (context) =>\n // eslint-disable-next-line no-new-func\n new Function(\n \"context\",\n \"isInServiceArea\",\n `return (${conditionWithThis});`\n )(context, isInServiceArea);\n }\n }\n }\n }, [form?.steps]);\n\n useEffect(() => {\n // Check if currentIndex is out of bounds\n if (currentStep < 0 || currentStep >= form?.steps?.length) {\n setCurrentStep(0);\n }\n }, [form?.steps, currentStep]);\n\n useEffect(() => {\n // Deliberately not a useState initialiser. The form arrives\n // asynchronously, so at mount there are no steps yet and the bounds\n // guard above would reset the index to 0 before it ever rendered.\n //\n // The ref makes it fire once. Without it, every re-render carrying the\n // same initialStep would drag the user back to the step they had just\n // navigated away from.\n if (appliedInitialStep.current) return;\n if (typeof initialStep !== \"number\") return;\n\n const steps = form?.steps;\n if (!steps?.length) return;\n\n appliedInitialStep.current = true;\n\n // An index the form has no step for is the caller's mistake. Opening\n // where the form always would beats rendering nothing.\n if (initialStep > 0 && initialStep < steps.length) {\n setCurrentStep(initialStep);\n onTrackInitialStep?.(initialStep);\n }\n }, [form?.steps, initialStep, onTrackInitialStep]);\n\n // Memoize the current step's warnBeforeUnload value to prevent unnecessary effect re-runs\n const shouldWarnBeforeUnload = useMemo(() => {\n const currentFormStep = form.steps?.[currentStep] as ExtendedFormStep | undefined;\n return currentFormStep?.warnBeforeUnload ?? false;\n }, [currentStep, form.steps]);\n\n // Handle beforeunload warning for steps that require it\n useEffect(() => {\n if (shouldWarnBeforeUnload) {\n const handleBeforeUnload = (e: BeforeUnloadEvent) => {\n e.preventDefault();\n // eslint-disable-next-line no-param-reassign\n e.returnValue = \"\"; // Required for Chrome\n return \"\"; // For older browsers\n };\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n\n return () => {\n window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n };\n }\n\n return undefined;\n }, [shouldWarnBeforeUnload]);\n\n const formData = useRef<StandardFormData>({});\n const formDataWithLabels = useRef({});\n const lastStepData = useRef<object>({});\n const formSubmittedRef = useRef(false);\n\n // Re-arm the submit guard whenever the form moves to a different step, so the\n // guard only ever collapses repeat submissions of the *same* step. The final\n // step never advances, so its latch holds and the lead is still submitted once.\n useEffect(() => {\n formSubmittedRef.current = false;\n }, [currentStep]);\n\n const nextStep = async (submit?: boolean) => {\n let nextStepIndex = -1;\n\n for (let i = currentStep + 1; i < form.steps.length; i++) {\n const formStepItem = form.steps[i];\n\n const test = fieldTests.current[formStepItem.name];\n\n const zip =\n formData.current.zip_code ||\n formData.current.zip ||\n extractZipFromAddress(formData.current.address);\n\n // Build the context to pass in\n const context = {\n ...formData.current,\n zip,\n };\n\n if (test) {\n // eslint-disable-next-line @typescript-eslint/ban-types\n if ((test as Function)(context)) {\n nextStepIndex = i;\n break;\n }\n } else {\n nextStepIndex = i;\n break;\n }\n }\n\n // Fire FORM_NEXT before advancing only when the current step has serverCallback: true\n const currentStepDef = form.steps[currentStep] as ExtendedFormStep;\n if (nextStepIndex >= 0 && !submit && onFormNext && currentStepDef?.serverCallback) {\n // Clear any stale override for the upcoming step before the server call,\n // so a timeout/error doesn't leave outdated fields from a previous pass.\n setStepOverrides((prev) => {\n const next = { ...prev };\n delete next[form.steps[nextStepIndex].name];\n return next;\n });\n try {\n const timeout = new Promise<undefined>((resolve) =>\n setTimeout(() => resolve(undefined), 3000)\n );\n const request = onFormNext({\n result: lastStepData.current as Record<string, unknown>,\n form: form.name,\n step: form.steps[currentStep].name,\n nextStep: form.steps[nextStepIndex].name,\n });\n const response = await Promise.race([request, timeout]);\n const r = response as FormNextResponse;\n if (r?.displays) {\n for (const display of r.displays) {\n if (display.type === \"FORM_STEP_UPDATE\") {\n applyFormStepUpdate(display);\n }\n }\n }\n } catch {\n // Graceful degradation: proceed with existing step fields\n }\n }\n\n // The handoff step is reached by a submit, and its per-submission config (zipCode, name,\n // trade) only exists in that response. Flag the wait BEFORE advancing so the step never\n // renders unflagged for a frame and injects the partner script with the static config.\n const advancingToHandoff =\n nextStepIndex >= 0 && !!submit && isFormStepExternalWidget(form.steps[nextStepIndex]);\n if (advancingToHandoff && !handoffConfigSettledRef.current[form.steps[nextStepIndex].name]) {\n setAwaitingHandoffConfig(true);\n }\n\n if (nextStepIndex >= 0) {\n setCurrentStep(nextStepIndex);\n }\n\n if (!!submit) {\n // Awaited so FormStepDisplay's own isSubmitting state stays set for the\n // duration of the dispatch, and so a rejection is handled rather than\n // becoming an unhandled rejection (issue #1373).\n // Pass the current step index since state updates are async\n //\n // The wait is deliberately NOT released here. The dispatch resolving is not the\n // config arriving: FormWidget surfaces the FORM_STEP_UPDATE as state, which reaches\n // this component a render later. Releasing on settle injected the partner script\n // inside that gap with the static config only -- 7-14ms measured against the live\n // page, against CostGuide's own bundle landing ~90ms after, so whether a visitor was\n // prefilled came down to which of the two won. It is released by the override\n // actually being present, and bounded by EXTERNAL_WIDGET_CONFIG_WAIT_MS so a submit\n // that fails or returns nothing still reaches the partner's form without prefill.\n await onSubmitForm(currentStep);\n }\n };\n\n const prevStep = () => {\n const fromStepIndex = currentStep;\n const fromStepName = form.steps?.[fromStepIndex]?.name || \"unknown\";\n\n for (let i = currentStep - 1; i >= 0; i--) {\n const step = form.steps[i];\n const test = fieldTests.current[step.name];\n\n const zip =\n formData.current.zip_code ||\n formData.current.zip ||\n extractZipFromAddress(formData.current.address);\n\n const context = {\n ...formData.current,\n zip,\n };\n\n if (test) {\n // eslint-disable-next-line @typescript-eslint/ban-types\n if ((test as Function)(context)) {\n // Track previous_step event before changing step\n if (onTrackPreviousStep) {\n onTrackPreviousStep(fromStepName, fromStepIndex, step.name, i);\n }\n setCurrentStep(i);\n break;\n }\n } else {\n // Track previous_step event before changing step\n if (onTrackPreviousStep) {\n onTrackPreviousStep(fromStepName, fromStepIndex, step.name, i);\n }\n setCurrentStep(i);\n break;\n }\n }\n };\n\n const handleData = (data: object) => {\n lastStepData.current = data;\n formData.current = { ...formData.current, ...data };\n };\n\n const getData = () => {\n return formData.current;\n };\n\n const handleDataWithLabels = (data: object) => {\n formDataWithLabels.current = { ...formDataWithLabels.current, ...data };\n };\n\n const getDataWithLabels = () => {\n return formDataWithLabels.current;\n };\n\n const onSubmitForm = async (submitStepIndex?: number) => {\n // Guard against double-firing the backend submission for a single step: a\n // double-click before the \"submitting\" UI state flushes, a re-render, or a\n // retry can invoke this more than once for the same submission. The latch is\n // scoped to the current step, re-armed by the effect above -- see there for why.\n if (formSubmittedRef.current) {\n return;\n }\n formSubmittedRef.current = true;\n\n // Use provided step index or fall back to currentStep\n const stepIndex = submitStepIndex ?? currentStep;\n const safeStepIndex = stepIndex >= 0 && stepIndex < form.steps.length ? stepIndex : 0;\n\n // Track submit event if tracking callback is provided\n if (onTrackSubmit) {\n onTrackSubmit(\n form.steps[safeStepIndex].name,\n safeStepIndex,\n formData.current as Record<string, unknown>,\n form.steps.length\n );\n }\n\n const data: FormActionResponseData = {\n result: formData.current,\n form: form.name,\n step: form.steps[safeStepIndex].name,\n final: !!form.steps[safeStepIndex].final,\n };\n if (typeof onActionResponse !== \"function\") {\n return;\n }\n\n // This dispatch is what creates the lead. onTrackSubmit above has already\n // recorded the submit on a *different* endpoint, so if this fails and nobody\n // notices, the analytics say the form was submitted and no lead exists --\n // exactly the loss reported in issue #1373. Await it, and on failure re-arm the\n // guard (otherwise the user's retry click is swallowed), tell the user, and\n // emit the counter-signal.\n setFailedSubmitStep(undefined);\n try {\n await onActionResponse(data, \"FORM_SUBMIT\");\n } catch (error) {\n formSubmittedRef.current = false;\n setFailedSubmitStep(safeStepIndex);\n\n const reason = error instanceof Error ? error.message : String(error);\n err(`FORM_SUBMIT failed on step ${form.steps[safeStepIndex].name}: ${reason}`);\n\n if (onTrackSubmitFailure) {\n onTrackSubmitFailure(\n form.steps[safeStepIndex].name,\n safeStepIndex,\n form.steps.length,\n reason\n );\n }\n }\n };\n\n const onHeaderClick = (step: string) => {\n const condition = (formStep: FormStep) => formStep.name === step;\n const index = form.steps.findIndex(condition);\n\n if (index === -1) {\n err(`Header click: Cannot find step to jump to: ${step}`);\n return;\n }\n\n setCurrentStep(index);\n };\n\n // A booking-widget handoff step is terminal (previousAction/nextAction: \"omit\"),\n // so the only way out of it is a forced jump: the partner script failed to\n // render or errored, and externalWidget.fallbackStep names where to go instead.\n const jumpToExternalWidgetFallback = (fallbackStep: string) => {\n const index = form.steps.findIndex((formStep) => formStep.name === fallbackStep);\n\n if (index === -1) {\n err(`External widget fallback: Cannot find step to jump to: ${fallbackStep}`);\n return;\n }\n\n setCurrentStep(index);\n };\n\n let step = currentStep;\n\n // Safety\n if (currentStep < 0 || currentStep >= form?.steps?.length) {\n step = 0;\n }\n\n // In labelHeader mode SimpleNavigationHeader renders the current step's header label as a\n // full-width h4 banner. When a partner preset draws its own tab that is two headers stacked on\n // one step -- and the banner is the one nobody designed for this layout: the labels come from\n // the handler's stepper (\"Request\", \"Contact Info\"), sized for a progress strip. The tab wins.\n //\n // Only the label variant. The stepper variant is genuine progress UI and stays.\n //\n // And only where a tab is actually drawn. The tab is per-step and only on FRAMED steps -- the\n // handoff step is deliberately unframed, since the partner's embed brings its own chrome -- so\n // suppressing form-wide would leave that step identifying itself with neither banner nor tab.\n const activeStepHandsOff = isFormStepExternalWidget(form.steps[step]);\n const activeStepFramed = !activeStepHandsOff;\n const partnerTabReplacesLabelHeader =\n !!framing?.tabLabel && !!form.labelHeader && activeStepFramed;\n\n // The handoff step wears the partner's chrome and none of ours. `form.header` only names\n // OUR steps, so there is no entry for this one and the label header rendered\n // `.empty_step_header`: a 42px bar in the header colour with nothing written in it, sitting\n // directly above the partner's own card. The tab is already off here (the step is unframed),\n // so suppressing the banner leaves the step with no heading of ours at all, which is the\n // point -- their embed introduces itself.\n // Not gated on `framing`. It was, and then the CostGuide preset dropped its framing, which\n // silently switched this whole behaviour back off -- the empty banner and our border returned\n // to the handoff step with every test still green. A handoff step wears the partner's chrome\n // whether or not a preset is drawing any of ours.\n const bareHandoff = activeStepHandsOff;\n const hideLabelHeader = partnerTabReplacesLabelHeader || bareHandoff;\n\n return (\n // The marker, not a class: .xapp_search_response_part reserves space for the header with\n // a hand-written margin, and that margin cannot see whether the header was rendered.\n // FormDisplay is what decides, so it says so here and the ancestor collapses off it.\n //\n // `data-xapp-bare-handoff` is read the same way, by the widget root, to drop its border,\n // radius and shadow for this step -- our box around their box reads as a mistake.\n <div\n {...(hideLabelHeader ? { \"data-xapp-header-suppressed\": \"\" } : {})}\n {...(bareHandoff ? { \"data-xapp-bare-handoff\": \"\" } : {})}\n >\n {form.header.length > 0 && !hideLabelHeader && (\n <div\n className={\n !!isShowCase\n ? styles.xapp_header_container_showcase\n : styles.xapp_header_container\n }\n >\n <SimpleNavigationHeader\n items={form.header}\n onHeaderClick={onHeaderClick}\n labelHeader={form.labelHeader}\n stepName={form.steps[step].name}\n isShowCase={isShowCase}\n />\n </div>\n )}\n <div>\n {form.steps.map((formStep, index) => {\n const override = stepOverrides[formStep.name];\n let effectiveStep = formStep;\n if (override?.fields) {\n effectiveStep = {\n ...effectiveStep,\n fields: override.fields as typeof formStep.fields,\n };\n }\n if (override?.externalWidget?.config) {\n const staticExternalWidget = (\n formStep as unknown as { externalWidget?: ExternalWidgetConfig }\n ).externalWidget;\n if (staticExternalWidget) {\n effectiveStep = {\n ...effectiveStep,\n externalWidget: {\n ...staticExternalWidget,\n config: {\n ...staticExternalWidget.config,\n ...override.externalWidget.config,\n },\n },\n } as FormStep;\n }\n }\n const isActive = form.steps[step].name === formStep.name;\n // The frame goes around the steps we render ourselves. A booking\n // handoff step is the partner's own embed and brings its own\n // frame, so it renders unframed. That is a property of the step,\n // not a piece of state, so crossing into the handoff turns the\n // frame off without remounting anything.\n const framed = !isFormStepExternalWidget(effectiveStep);\n const stepDisplay = (\n <FormStepDisplay\n formStep={effectiveStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onData={handleData}\n onDataWithLabels={handleDataWithLabels}\n onNextStep={step < form.steps.length ? nextStep : undefined}\n onPrevStep={step > 0 ? prevStep : undefined}\n getData={getData}\n getDataWithLabels={getDataWithLabels}\n loading={loading}\n currentStepIndex={index}\n totalSteps={form.steps.length}\n onTrackNextStep={onTrackNextStep}\n currentStepDataRef={currentStepDataRef}\n isActive={isActive}\n // Hold the partner script until the submit's values are merged in.\n externalWidgetConfigPending={\n awaitingHandoffConfig &&\n isFormStepExternalWidget(formStep) &&\n !override?.externalWidget?.config &&\n !externalWidgetWaitElapsed\n }\n onTrackHandoffRendered={onTrackHandoffRendered}\n onTrackHandoffNoRender={onTrackHandoffNoRender}\n onTrackHandoffScheduled={onTrackHandoffScheduled}\n onTrackHandoffError={onTrackHandoffError}\n onExternalWidgetFallback={jumpToExternalWidgetFallback}\n // Only when the frame is actually drawing an intro of its own.\n // The frame no longer borrows the step's title, so hiding the\n // step's intro unconditionally would drop the heading entirely.\n // Suppressed when the frame draws its own intro, and always on a\n // partner-embed step: the embed opens with its own heading, so ours\n // is a second one for the same thing. #1659 narrowed this from \"any\n // framed form\" and switched the handoff step's title back on.\n hideIntro={\n !!framing?.introTitle ||\n !!framing?.introSubtitle ||\n isFormStepExternalWidget(effectiveStep)\n }\n submitError={\n failedSubmitStep === index ? SUBMIT_ERROR_MESSAGE : undefined\n }\n />\n );\n return (\n <div\n key={index}\n className={`${styles.xapp_formstep} ${isActive ? styles.active : \"\"}`}\n data-xapp-form-step-active={isActive ? \"true\" : \"false\"}\n >\n {framing ? (\n <FormFrame framing={framing} framed={framed}>\n {stepDisplay}\n </FormFrame>\n ) : (\n stepDisplay\n )}\n </div>\n );\n })}\n </div>\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { Display } from \"stentor-models\";\nimport { isCarousel, isForm, isList } from \"../../utils/guards\";\nimport { SearchResponseCarouselDisplay } from \"../SearchResponseCarouselDisplay\";\nimport { SearchResponseListDisplay } from \"../SearchResponseListDisplay\";\nimport { FormDisplay } from \"../FormDisplay\";\nimport { FormNextData, FormStepUpdateDisplay } from \"../FormDisplay/model\";\n\nexport interface ResponseDisplayProps {\n readonly display: Display;\n readonly loading: boolean;\n onActionResponse(data: unknown, action: string): void;\n onTrackNextStep?: (stepName: string, stepIndex: number, stepData: Record<string, unknown>, isLastStep: boolean) => void;\n onTrackPreviousStep?: (fromStepName: string, fromStepIndex: number, toStepName: string, toStepIndex: number) => void;\n onTrackSubmit?: (stepName: string, stepIndex: number, completedData: Record<string, unknown>, totalSteps: number) => void;\n /**\n * Callback to track a FORM_SUBMIT dispatch that failed outright (issue #1373).\n */\n onTrackSubmitFailure?: (stepName: string, stepIndex: number, totalSteps: number, reason: string) => void;\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /** Zero-based step to open the form on, instead of the first. */\n readonly initialStep?: number;\n /** Open the date/time step on the soonest day that has times. */\n readonly preselectFirstAvailableDate?: boolean;\n /** Fired with the step index when initialStep is applied. */\n onTrackInitialStep?: (stepIndex: number) => void;\n onFormNext?: (data: FormNextData) => Promise<unknown>;\n stepUpdate?: FormStepUpdateDisplay;\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n}\n\n// TODO: Rename this to ResponseDisplay\nexport const ResponseDisplay: FC<ResponseDisplayProps> = (props) => {\n const {\n display,\n onActionResponse,\n loading,\n onTrackNextStep,\n onTrackPreviousStep,\n onTrackSubmit,\n onTrackSubmitFailure,\n currentStepDataRef,\n initialStep,\n preselectFirstAvailableDate,\n onTrackInitialStep,\n onFormNext,\n stepUpdate,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n } = props;\n\n // TODO: Do we need these others? isList and isCarousel?\n return (\n <div className=\"xapp-search-response-display\">\n {isForm(display) && (\n <FormDisplay\n form={display}\n loading={loading}\n onActionResponse={onActionResponse}\n onTrackNextStep={onTrackNextStep}\n onTrackPreviousStep={onTrackPreviousStep}\n onTrackSubmit={onTrackSubmit}\n onTrackSubmitFailure={onTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={onTrackInitialStep}\n onFormNext={onFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={onTrackHandoffRendered}\n onTrackHandoffNoRender={onTrackHandoffNoRender}\n onTrackHandoffScheduled={onTrackHandoffScheduled}\n onTrackHandoffError={onTrackHandoffError}\n />\n )}\n {isList(display) && <SearchResponseListDisplay list={display} />}\n {isCarousel(display) && <SearchResponseCarouselDisplay carousel={display} />}\n </div>\n );\n};\n","import React, { FC } from \"react\";\n\nexport interface SearchResponseHtmlProps {\n readonly html: string;\n}\n\nexport const SearchResponseHtml: FC<SearchResponseHtmlProps> = props => {\n const { html } = props;\n return (\n <div\n className=\"xapp-search-response-html\"\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n};","import React, { FC } from \"react\";\n\nexport interface SearchResponseTextProps {\n readonly text: string;\n}\n\nexport const SearchResponseText: FC<SearchResponseTextProps> = props => {\n const { text } = props;\n return (\n <div className=\"xapp-search-response-text\">\n <p>\n {text}\n </p>\n </div>\n );\n};","import React, { FC, useEffect, useRef } from \"react\";\n\nimport { log } from \"../../utils\";\n\nexport interface SearchResponseAudioProps {\n readonly audio: string;\n onAudioChange(isOn: boolean): void;\n}\n\nexport const SearchResponseAudio: FC<SearchResponseAudioProps> = props => {\n const { audio, onAudioChange } = props;\n\n const audioRef = useRef(null);\n\n useEffect(() => {\n const audioElement = audioRef.current as unknown as HTMLAudioElement;\n \n const handleAudioEnd = () => {\n log(\"Audio finished playing\");\n onAudioChange(false);\n };\n \n const handleAudioPlay = () => {\n log(\"Audio started playing\");\n onAudioChange(true);\n };\n \n if (audioElement) {\n audioElement.addEventListener(\"ended\", handleAudioEnd);\n audioElement.addEventListener(\"play\", handleAudioPlay);\n }\n\n return () => {\n if (audioElement) {\n audioElement.removeEventListener(\"ended\", handleAudioEnd);\n audioElement.removeEventListener(\"play\", handleAudioPlay);\n }\n };\n }, [audio, onAudioChange]);\n\n return (\n <audio ref={audioRef} autoPlay={true} src={audio} />\n );\n};","import React, { FC, useContext } from \"react\";\nimport { ResponseOutput } from \"stentor-models\";\nimport { SearchResponseHtml } from \"../SearchResponseHtml\";\nimport { SearchResponseText } from \"../SearchResponseText\";\nimport { SearchResponseAudio } from \"../SearchResponseAudio\";\nimport styles from \"./SearchResponseOutputSpeech.module.scss\";\nimport { parseAudio } from \"../../utils/parseAudio\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\n\nexport interface SearchResponseOutputSpeechProps {\n readonly outputSpeech: ResponseOutput | string;\n onAudioChange(isOn: boolean): void;\n}\n\nexport const SearchResponseOutputSpeech: FC<SearchResponseOutputSpeechProps> = props => {\n const { outputSpeech, onAudioChange } = props;\n \n const text = typeof outputSpeech === \"string\" ? outputSpeech : outputSpeech?.displayText;\n const html = typeof outputSpeech === \"string\" ? undefined : outputSpeech?.html;\n const ssml = typeof outputSpeech === \"string\" ? undefined : outputSpeech?.ssml;\n\n const config = useContext(SearchWidgetConfigContext);\n\n // play the firts audio if present\n let audioUrl: string | undefined;\n\n if (!!config.isVoiceEnabled) {\n const mp3s = ssml ? parseAudio(ssml) : [];\n audioUrl = mp3s.length > 0 ? mp3s[0] : undefined;\n }\n\n return (\n <div\n className={styles.xapp_search_response_output_speech}>\n {!!html && <SearchResponseHtml html={html} />}\n {!!text && !html && <SearchResponseText text={text} />}\n {!!audioUrl && <SearchResponseAudio audio={audioUrl} onAudioChange={onAudioChange} />}\n </div>\n );\n}\n","export function parseAudio(ssml: string): string[] {\n const regex = /<audio\\s+src\\s*=\\s*\"(.+?)\"\\s*\\/?>/g;\n const matches: string[] = [];\n let match: string[] | null;\n\n while ((match = regex.exec(ssml)) !== null) {\n matches.push(match[1]);\n }\n\n return matches;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isLinkoutSuggestion = isLinkoutSuggestion;\n/**\n * Determines if the suggestion is a LinkOutSuggestion\n *\n * @param {(LinkOutSuggestion | Suggestion)} suggestion\n * @returns {suggestion is LinkOutSuggestion}\n */\nfunction isLinkoutSuggestion(suggestion) {\n if (!suggestion) {\n return false;\n }\n return suggestion.url !== undefined;\n}\n//# sourceMappingURL=isLinkoutSuggestion.js.map","import React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./Button.module.scss\";\n\nexport interface ButtonProps {\n readonly className?: string;\n readonly expand?: boolean;\n onClick(): void;\n}\n\nexport const Button: FC<PropsWithChildren<ButtonProps>> = props => {\n const { className, expand, onClick } = props;\n return (\n <button\n type=\"button\"\n className={`${styles.xapp_search_btn} ${expand ? styles['xapp_search_btn__expand'] : \"\"} ${className || \"\"}`}\n onClick={onClick}\n >{props.children}</button>\n );\n};","import React, { FC, useCallback } from \"react\";\nimport { isLinkoutSuggestion } from \"stentor-guards/lib/isLinkoutSuggestion\";\nimport { SuggestionTypes } from \"stentor-models\";\nimport { getActionLabel } from \"../../utils/getActionLabel\";\nimport { Button } from \"../Button\";\nimport styles from \"./SuggestedAction.module.scss\";\n\nexport interface SuggestedActionProps {\n readonly action: SuggestionTypes;\n onClick(action: SuggestionTypes): void;\n readonly className?: string;\n}\n\nexport const SuggestedAction: FC<SuggestedActionProps> = props => {\n const { action, className, onClick } = props;\n\n const handleClick = useCallback(() => {\n onClick(action);\n }, [action, onClick])\n\n if (isLinkoutSuggestion(action)) {\n return (\n <span className={`${styles.xapp_search_suggested_action} ${className || \"\"}`}>\n <a href={action.url}>{getActionLabel(action)}</a>\n </span>\n );\n } else {\n return (\n <Button\n className={`${styles.xapp_search_suggested_action} ${className || \"\"}`}\n onClick={handleClick}\n > {getActionLabel(action)}</Button >\n );\n }\n}","import React, { FC } from \"react\";\nimport { SuggestionTypes } from \"stentor-models\";\nimport { SuggestedAction } from \"../SuggestedAction\";\nimport styles from \"./SuggestedActions.module.scss\";\n\n\nexport interface SuggestedActionsProps {\n readonly actions: readonly SuggestionTypes[];\n onActionClick(action: SuggestionTypes): void;\n}\n\nexport const SuggestedActions: FC<SuggestedActionsProps> = props => {\n const { actions, onActionClick } = props;\n return (\n <div className={styles.xapp_search_suggested_actions}>\n <div className={styles.xapp_search_suggested_actions__actions}>\n {actions.map((act, index) => (\n <SuggestedAction\n key={index}\n action={act}\n className={styles.xapp_search_suggested_actions__item}\n onClick={onActionClick}\n />))}\n </div>\n </div>\n );\n};","import React, { FC, PropsWithChildren } from \"react\";\n\nimport styles from \"./SearchResponsePart.module.scss\";\n\nexport interface SearchResponsePartProps {\n extraClass?: string;\n}\n\nexport const SearchResponsePart: FC<PropsWithChildren<SearchResponsePartProps>> = (props) => {\n const { extraClass } = props;\n\n // A modifier names a rule in THIS module (`&.noHeaderForm`), and the build hashes module\n // classes -- so it has to be looked up, not passed through. Applied as the bare string it\n // never matched, and a form with no header kept the 86px reserved for one as a blank band.\n // An unknown name still passes through as-is, so a genuinely global class keeps working.\n const modifier = extraClass\n ? (styles as Record<string, string | undefined>)[extraClass] || extraClass\n : \"\";\n\n return (\n <div className={`${styles.xapp_search_response_part} ${modifier}`}>\n {props.children}\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { Response, SuggestionTypes } from \"stentor-models\";\n\nimport { SearchResponseBubble } from \"../SearchResponseBubble\";\nimport { SearchResponseDisplay } from \"../ResponseDisplay\";\nimport { SearchResponseOutputSpeech } from \"../SearchResponseOutputSpeech\";\nimport { SuggestedActions } from \"../SuggestedActions\";\nimport { isForm } from \"../../utils/guards\";\nimport { FormNextData, FormStepUpdateDisplay } from \"../FormDisplay/model\";\n\nimport { SearchResponsePart } from \"./SearchResponsePart\";\n\nimport styles from \"./FormResponse.module.scss\";\n\nexport interface FormResponseProps {\n readonly response: Response;\n readonly className?: string;\n readonly loading: boolean;\n onActionClick(action: SuggestionTypes): void;\n onActionResponse(data: unknown, action: string): void;\n onAudioChange(isOn: boolean): void;\n onTrackNextStep?: (stepName: string, stepIndex: number, stepData: Record<string, unknown>, isLastStep: boolean) => void;\n onTrackPreviousStep?: (fromStepName: string, fromStepIndex: number, toStepName: string, toStepIndex: number) => void;\n onTrackSubmit?: (stepName: string, stepIndex: number, completedData: Record<string, unknown>, totalSteps: number) => void;\n /**\n * Callback to track a FORM_SUBMIT dispatch that failed outright (issue #1373).\n */\n onTrackSubmitFailure?: (stepName: string, stepIndex: number, totalSteps: number, reason: string) => void;\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /** Zero-based step to open the form on, instead of the first. */\n readonly initialStep?: number;\n /** Open the date/time step on the soonest day that has times. */\n readonly preselectFirstAvailableDate?: boolean;\n /** Fired with the step index when initialStep is applied. */\n onTrackInitialStep?: (stepIndex: number) => void;\n onFormNext?: (data: FormNextData) => Promise<unknown>;\n stepUpdate?: FormStepUpdateDisplay;\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n}\n\n/**\n * FormResponse displays the data from the handler\n */\nexport const FormResponse: FC<FormResponseProps> = (props) => {\n const {\n response,\n className,\n onActionClick,\n onActionResponse,\n onAudioChange,\n loading,\n onTrackNextStep,\n onTrackPreviousStep,\n onTrackSubmit,\n onTrackSubmitFailure,\n currentStepDataRef,\n initialStep,\n preselectFirstAvailableDate,\n onTrackInitialStep,\n onFormNext,\n stepUpdate,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n } = props;\n\n const { outputSpeech, displays } = response;\n const actions = typeof outputSpeech === \"object\" ? outputSpeech.suggestions : undefined;\n\n return (\n <div className={`${styles.xapp_search_response} ${className || \"\"}`}>\n {!!outputSpeech && (\n <SearchResponsePart>\n <SearchResponseBubble>\n <SearchResponseOutputSpeech\n outputSpeech={outputSpeech}\n onAudioChange={onAudioChange}\n />\n </SearchResponseBubble>\n </SearchResponsePart>\n )}\n\n {!!actions?.length && actions?.length > 0 && (\n <SuggestedActions actions={actions} onActionClick={onActionClick} />\n )}\n\n {!!displays?.length &&\n displays?.length > 0 &&\n displays.map((display, index) => {\n const noHeaderForm: boolean =\n isForm(display) && (!display.header || display.header.length === 0);\n\n return (\n <SearchResponsePart\n key={index}\n extraClass={noHeaderForm ? \"noHeaderForm\" : \"\"}>\n <SearchResponseDisplay\n display={display}\n onActionResponse={onActionResponse}\n loading={loading}\n onTrackNextStep={onTrackNextStep}\n onTrackPreviousStep={onTrackPreviousStep}\n onTrackSubmit={onTrackSubmit}\n onTrackSubmitFailure={onTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={onTrackInitialStep}\n onFormNext={onFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={onTrackHandoffRendered}\n onTrackHandoffNoRender={onTrackHandoffNoRender}\n onTrackHandoffScheduled={onTrackHandoffScheduled}\n onTrackHandoffError={onTrackHandoffError}\n />\n </SearchResponsePart>\n );\n })}\n </div>\n );\n};\n","/**\n * Service for tracking form widget interaction events\n *\n * API Endpoint: POST /cms/widget/events\n * @see https://github.com/XappMedia/chat-widget/blob/master/docs/widget-events-api.md\n */\n\nimport { readInternalTrafficMark, visitIdentity } from \"@xapp/chat-widget-core\";\nimport { StentorApi } from \"../api/stentor-api\";\nimport {\n WidgetEventMetadata,\n WidgetEvent,\n FormOpenEventData,\n EngagedEventData,\n NextStepEventData,\n PreviousStepEventData,\n StepChangeEventData,\n SubmitEventData,\n SubmitFailureEventData,\n CloseEventData,\n PartialDataEventData,\n HandoffRenderedEventData,\n HandoffNoRenderEventData,\n HandoffScheduledEventData,\n HandoffErrorEventData,\n} from \"../types/events\";\nimport { log, err } from \"../utils\";\nimport { getStoredTrackingParameters } from \"../utils/tracking\";\n\n/**\n * Service for tracking form widget interaction events.\n * This service provides methods to track user interactions with the form widget\n * without blocking the user experience (all tracking is async and errors are logged).\n *\n * Events are sent to POST /cms/widget/events and stored in OpenSearch as:\n * - load -> eventName: \"WIDGET_FORM_LOAD\"\n * - form_open -> eventName: \"WIDGET_FORM_OPEN\"\n * - engaged -> eventName: \"WIDGET_FORM_ENGAGED\"\n * - next_step -> eventName: \"WIDGET_FORM_STEP\"\n * - previous_step -> eventName: \"WIDGET_FORM_PREV_STEP\"\n * - step_change -> eventName: \"WIDGET_FORM_STEP_CHANGE\"\n * - submit -> eventName: \"WIDGET_FORM_SUBMIT\"\n * - close -> eventName: \"WIDGET_FORM_CLOSE\"\n * - partial_data -> eventName: \"WIDGET_FORM_ABANDON\"\n * - handoff_rendered -> eventName: \"WIDGET_FORM_HANDOFF_RENDERED\"\n * - handoff_no_render -> eventName: \"WIDGET_FORM_HANDOFF_NO_RENDER\"\n * - handoff_scheduled -> eventName: \"WIDGET_FORM_HANDOFF_SCHEDULED\"\n * - handoff_error -> eventName: \"WIDGET_FORM_HANDOFF_ERROR\"\n */\n/**\n * Input that counts as a visitor touching the page. Deliberately broad and document-level: the\n * point is to tell a person from a scripted browser, and a script that drives the form through the\n * DOM produces none of these - as long as only real gestures count, which is why the listener\n * below checks isTrusted. Browsers set that flag only on genuine user input; anything a script\n * dispatches is untrusted and cannot set it.\n */\nconst INTERACTION_EVENTS = [\"pointerdown\", \"keydown\", \"scroll\", \"touchstart\"];\n\nexport class EventTrackingService {\n private api: StentorApi;\n private sessionId: string;\n private formId: string;\n /** When the form opened, so every later event can report how long the visit has lasted. */\n private openedAt?: number;\n /** When the visitor first touched anything. Stays undefined when nobody ever did. */\n private firstInteractionAt?: number;\n private stopWatchingForInteraction?: () => void;\n\n constructor(api: StentorApi, sessionId: string, formId: string) {\n this.api = api;\n this.sessionId = sessionId;\n this.formId = formId;\n }\n\n /**\n * A tracker on the visit's session (started now if the form hasn't sent anything yet), so\n * events sent before the first request - the load - carry the session the visit's open and\n * submit events will.\n */\n public static forVisit(api: StentorApi, formId: string): EventTrackingService {\n return new EventTrackingService(api, api.visitSession().sessionId, formId);\n }\n\n /**\n * Track a form_open event when the form widget is first displayed\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_OPEN\"\n */\n public async trackFormOpen(data: FormOpenEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata({ isOpen: true });\n this.watchForFirstInteraction();\n const event: WidgetEvent = {\n eventType: \"form_open\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] form_open event tracked: ${data.formName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track form_open event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track an engaged event the first time a user takes a genuine action on\n * the form (manual open, chip click, or first step transition).\n * Additive to form_open - does not replace it. Callers are responsible\n * for only calling this once per session.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_ENGAGED\"\n */\n public async trackEngaged(data: EngagedEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"engaged\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] engaged event tracked: ${data.formName} (${data.trigger})`);\n } catch (error) {\n err(`[EventTracking] Failed to track engaged event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a next_step event when user navigates to the next form step\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_STEP\"\n */\n public async trackNextStep(data: NextStepEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"next_step\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] next_step event tracked: ${data.completedStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track next_step event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a previous_step event when user navigates back to a previous step\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_PREV_STEP\"\n */\n public async trackPreviousStep(data: PreviousStepEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"previous_step\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] previous_step event tracked: ${data.fromStepName} -> ${data.toStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track previous_step event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a step_change event for any step navigation (forward or backward)\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_STEP_CHANGE\"\n */\n public async trackStepChange(data: StepChangeEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"step_change\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] step_change event tracked: ${data.fromStepName} -> ${data.toStepName} (${data.direction})`);\n } catch (error) {\n err(`[EventTracking] Failed to track step_change event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a submit event when user submits the final form\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_SUBMIT\"\n */\n public async trackSubmit(data: SubmitEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"submit\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] submit event tracked: ${data.finalStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track submit event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a submit that failed to reach the server, after retries.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_SUBMIT_FAILURE\"\n *\n * trackSubmit above fires on this endpoint *before* the FORM_SUBMIT dispatch that\n * actually creates the lead, so a submit event alone never proved a lead existed.\n * This is its counter-signal: submit events minus submit_failure events is the\n * number of submissions that were genuinely dispatched (issue #1373).\n */\n public async trackSubmitFailure(data: SubmitFailureEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"submit_failure\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] submit_failure event tracked: ${data.finalStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track submit_failure event: ${error}`);\n // Don't throw - the user is already being shown the failure.\n }\n }\n\n /**\n * Track a close event when user explicitly closes the form widget\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_CLOSE\"\n */\n public async trackClose(data: CloseEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"close\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] close event tracked: ${data.lastStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track close event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a partial_data event when user abandons form (tab close or timeout)\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_ABANDON\"\n *\n * @param data - Event data including abandonmentReason (\"close_tab\" | \"timeout\")\n */\n public async trackPartialData(data: PartialDataEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"partial_data\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] partial_data event tracked: ${data.lastStepName} (${data.abandonmentReason})`);\n } catch (error) {\n err(`[EventTracking] Failed to track partial_data event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_rendered event when a booking-widget handoff step's anchor\n * gains content within its render timeout.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_RENDERED\"\n */\n public async trackHandoffRendered(data: HandoffRenderedEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_rendered\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] handoff_rendered event tracked: ${data.stepName} (${data.provider})`);\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_rendered event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_no_render event when a booking-widget handoff step's render\n * timeout elapses with an empty anchor.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_NO_RENDER\"\n */\n public async trackHandoffNoRender(data: HandoffNoRenderEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_no_render\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] handoff_no_render event tracked: ${data.stepName} (${data.provider})`);\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_no_render event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_scheduled event when the partner script invokes the\n * configured success callback. This is how the booking outcome reaches\n * stentor_events -- joinable on sessionId with the lead.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_SCHEDULED\"\n */\n public async trackHandoffScheduled(data: HandoffScheduledEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_scheduled\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] handoff_scheduled event tracked: ${data.stepName} (${data.provider})`);\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_scheduled event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_error event when a booking-widget handoff step's partner\n * script fails to load, or its scriptSrc is rejected.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_ERROR\"\n */\n public async trackHandoffError(data: HandoffErrorEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_error\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] handoff_error event tracked: ${data.stepName} (${data.provider})`);\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_error event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a load event: the widget loaded on a page. Sent once per page load (the caller\n * guards that), keepalive and fire-and-forget, so it never blocks rendering.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_LOAD\"\n *\n * @param loadMetadata - page, browser and agent fields from chat-widget-core's\n * buildLoadEventMetadata. They win over the stored attribution: they describe this page.\n * @returns true if the request was queued\n */\n public trackLoad(loadMetadata: Record<string, string>): boolean {\n try {\n const metadata = this.buildMetadata();\n // buildMetadata reports the full href; a load event sends only what\n // buildLoadEventMetadata allowed through, never the raw query string.\n delete metadata.currentUrl;\n const event: WidgetEvent = {\n eventType: \"load\",\n metadata: { ...metadata, ...loadMetadata },\n data: {},\n };\n\n return this.api.trackEventBeacon(event, \"form\");\n } catch (error) {\n err(`[EventTracking] Failed to queue load event: ${error}`);\n return false;\n }\n }\n\n /**\n * Track a partial_data event using beacon/keepalive for page unload scenarios.\n * Use this when the page is being unloaded and you need reliable delivery.\n *\n * @param data - Event data including abandonmentReason (\"close_tab\" | \"timeout\")\n * @returns true if the beacon was queued, false otherwise\n */\n public trackPartialDataBeacon(data: PartialDataEventData): boolean {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"partial_data\",\n metadata,\n data,\n };\n\n return this.api.trackEventBeacon(event);\n } catch (error) {\n err(`[EventTracking] Failed to queue partial_data beacon: ${error}`);\n return false;\n }\n }\n\n /**\n * Build event metadata from current context.\n *\n * Each optional enrichment (currentUrl, UTM/click-id params) is isolated in its\n * own try/catch. localStorage access in particular can throw synchronously - not just\n * return null - in Safari ITP, a sandboxed iframe without allow-same-origin, or under an\n * enterprise storage policy. Without isolation, one such throw used to take down metadata\n * building entirely, silently dropping the event (including userAgent/currentUrl, which\n * don't depend on storage) via the try/catch in trackFormOpen et al. See issue #1504.\n */\n private buildMetadata({ isOpen = false } = {}): WidgetEventMetadata {\n const now = new Date();\n const nowMs = Date.now();\n if (isOpen && this.openedAt === undefined) {\n this.openedAt = nowMs;\n }\n const metadata: WidgetEventMetadata = {\n timestamp: now.toISOString(),\n sessionId: this.sessionId || 'unknown',\n formId: this.formId || 'unknown',\n userAgent: navigator.userAgent,\n };\n\n // Our own crawler, so its funnel events don't read as an AI agent's.\n const internal = readInternalTrafficMark();\n if (internal) {\n metadata.internal = internal;\n }\n\n // How long the visit has lasted, and how long it took the visitor to touch anything.\n // Both are omitted rather than zeroed when unknown: a 0 would read as a real measurement\n // of an instant bounce, which is exactly what these are used to judge.\n if (this.openedAt !== undefined) {\n metadata.msOnPage = String(Math.max(0, nowMs - this.openedAt));\n if (this.firstInteractionAt !== undefined) {\n metadata.msToFirstInteraction = String(Math.max(0, this.firstInteractionAt - this.openedAt));\n }\n }\n\n // Environment. Isolated like every other enrichment below - a browser that throws here\n // must still produce an event, not a silent drop (issue #1504).\n try {\n metadata.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch (e) {\n // Intl unavailable or throwing - skip timezone\n }\n\n try {\n metadata.language = navigator.language;\n // Screen against viewport: a real browser puts its own chrome between the two, so a\n // viewport exactly the size of the screen is a headless default.\n metadata.screenWidth = String(window.screen.width);\n metadata.screenHeight = String(window.screen.height);\n metadata.viewportWidth = String(window.innerWidth);\n metadata.viewportHeight = String(window.innerHeight);\n } catch (e) {\n // Screen/navigator unavailable (sandboxed frame) - skip the environment fields\n }\n\n // Who and which visit, shared with the chat widget on the page. The visitor id is also the\n // form's user id. Sending an event is what keeps the visit alive. Never throws.\n const { visitorId, visitId } = visitIdentity();\n metadata.userId = visitorId;\n metadata.visitorId = visitorId;\n metadata.visitId = visitId;\n\n // Add current URL (exclude localhost for privacy)\n try {\n const href = new URL(window.location.href);\n if (!href?.host.toLowerCase().startsWith('localhost')) {\n metadata.currentUrl = window.location.href;\n }\n } catch (e) {\n // If URL parsing fails, skip currentUrl\n }\n\n // Add tracking parameters from localStorage\n try {\n const trackingParams = this.getTrackingParameters();\n Object.assign(metadata, trackingParams);\n } catch (e) {\n // localStorage unavailable - skip UTM/click-id params\n }\n\n return metadata;\n }\n\n /**\n * Releases anything this tracker is holding on the page.\n *\n * The interaction listeners otherwise live until a trusted gesture fires one of them, which\n * may never happen: FormWidget's embedded mode mounts and unmounts inside a host app, and a\n * widget unmounted before anyone touches it would leave four document listeners - and the\n * closures behind them - accumulating on the page.\n */\n public dispose(): void {\n this.stopWatchingForInteraction?.();\n }\n\n /**\n * Carries a visit's timing onto a replacement tracker.\n *\n * FormWidget builds a new EventTrackingService every time an intentRequest resolves to a FORM\n * display, and that happens again mid-visit on a chip click. form_open fires only once per\n * mounted widget, so the replacement never calls trackFormOpen and would never learn when the\n * visit began - every later event would silently report no dwell and no interaction, for\n * exactly the multi-step flow these fields exist to measure.\n *\n * The previous tracker's listener is torn down and a fresh one armed here, so a gesture that\n * arrives after the handover still lands on the tracker actually sending events.\n */\n public adoptVisitFrom(previous?: EventTrackingService | null): void {\n if (!previous || previous === this || previous.openedAt === undefined) {\n return;\n }\n\n this.openedAt = previous.openedAt;\n this.firstInteractionAt = previous.firstInteractionAt;\n\n previous.stopWatchingForInteraction?.();\n if (this.firstInteractionAt === undefined) {\n this.watchForFirstInteraction();\n }\n }\n\n /**\n * Records when the visitor first touches the page, then stops listening.\n *\n * Listeners are passive and one-shot, so this costs nothing after the first input and cannot\n * interfere with scrolling. Absence is the signal that matters: a scripted browser drives the\n * form through the DOM and never fires any of these.\n */\n private watchForFirstInteraction(): void {\n if (this.stopWatchingForInteraction || this.firstInteractionAt !== undefined) {\n return;\n }\n if (typeof document === 'undefined') {\n return;\n }\n\n try {\n const onInteraction = (event: Event): void => {\n // A script can dispatch pointerdown as easily as we can listen for it, so an\n // untrusted event proves nothing. Ignored without tearing the listener down, or\n // one synthetic event would also destroy the real signal that follows it.\n if (!event.isTrusted) {\n return;\n }\n if (this.firstInteractionAt === undefined) {\n this.firstInteractionAt = Date.now();\n }\n this.stopWatchingForInteraction?.();\n };\n\n this.stopWatchingForInteraction = (): void => {\n for (const name of INTERACTION_EVENTS) {\n document.removeEventListener(name, onInteraction, true);\n }\n this.stopWatchingForInteraction = undefined;\n };\n\n for (const name of INTERACTION_EVENTS) {\n document.addEventListener(name, onInteraction, { capture: true, passive: true });\n }\n } catch (e) {\n // Listener registration unavailable - the fields simply stay absent\n }\n }\n\n /**\n * Get this form's tracking parameters from localStorage\n */\n private getTrackingParameters(): Record<string, string> {\n return getStoredTrackingParameters(this.api.trackingScope) as Record<string, string>;\n }\n\n /**\n * Send event to backend API\n */\n private async sendEvent(event: WidgetEvent): Promise<void> {\n try {\n await this.api.trackEvent(event.eventType, event);\n } catch (error) {\n // Log error but don't throw - we don't want to block user flow\n err(`[EventTracking] API call failed: ${error}`);\n }\n }\n}\n","import React, { FC, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { uuid } from \"@xapp/chat-widget-core\";\nimport { Response, SuggestionTypes } from \"stentor-models\";\nimport { StentorApi, wasDroppedAfterFinal } from \"../../api\";\nimport { FormWidgetConfig } from \"../../config\";\nimport { useSearchStore } from \"../../store\";\nimport { getActionLabel } from \"../../utils/getActionLabel\";\nimport { log, err } from \"../../utils\";\nimport { getAllTrackingParameters } from \"../../utils/tracking\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\nimport { useLoading } from \"../../utils/useLoading\";\nimport { useTrustedForm } from \"../../utils/useTrustedForm\";\nimport { getMetaCookies } from \"../../utils/metaCookies\";\nimport { SpinnerIcon } from \"../icons\";\nimport { FormResponse } from \"../FormResponse\";\nimport { FormNextData, FormStepUpdateDisplay } from \"../FormDisplay\";\nimport { EventTrackingService } from \"../../services/EventTrackingService\";\nimport { EngagementTrigger } from \"../../types/events\";\n\nimport styles from \"./FormWidget.module.scss\";\n\n/**\n * Interface for form step data in event tracking\n */\ninterface FormStep {\n name?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for FORM display type used in event tracking\n */\ninterface FormDisplay {\n type: \"FORM\";\n steps?: FormStep[];\n [key: string]: unknown;\n}\n\n/**\n * Backoff between FORM_SUBMIT attempts; its length sets the retry count (3 attempts).\n *\n * Only FORM_SUBMIT is retried: it is the request that creates the lead, and losing it\n * loses the lead outright (issue #1373). StentorApi.send already retries once on a\n * non-ok status, but a transport failure -- fetch rejecting, the case where nothing\n * reaches the server at all -- got no retry and no handler.\n *\n * Retrying a lead-creating POST can duplicate it if the request landed but the response\n * did not. `extras.eventId` is minted once per submission and resent unchanged on every\n * attempt (see getSubmitEventId), so the client side already carries a stable\n * idempotency key -- but nothing consumes it on this path yet: contact-capture-handler's\n * FormActionResponseData does not declare `extras` and never reads `attributes.data`, so\n * the id is dropped before the lead is built, and the lead write itself has no dedupe of\n * any kind. Plumbing it through and keying a dedupe on it is tracked separately.\n */\nconst SUBMIT_RETRY_DELAYS_MS = [1000, 2000];\n\nconst wait = (ms: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n\nasync function dispatchWithRetry<T>(attempt: () => Promise<T>, delays: number[]): Promise<T> {\n let lastError: unknown;\n\n for (let i = 0; i <= delays.length; i++) {\n if (i > 0) {\n await wait(delays[i - 1]);\n }\n\n try {\n return await attempt();\n } catch (error) {\n lastError = error;\n err(`FORM_SUBMIT attempt ${i + 1} of ${delays.length + 1} failed: ${error}`);\n }\n }\n\n throw lastError;\n}\n\nexport const AUDIO_WAIT_NOTHING = 0,\n AUDIO_WAIT_CLOSE = 1,\n AUDIO_WAIT_MINIMIZE = 2;\n\nexport interface FormWidgetProps {\n readonly config: FormWidgetConfig;\n /**\n * Optional initial response to display\n */\n readonly response?: Response;\n\n readonly docked?: boolean;\n /**\n * Rendering inside a container the host page provided and sized (see `isEmbedded`).\n *\n * Drops the framing that makes the widget read as a floating card -- the desktop\n * max-width, border, radius and shadow -- so it fills the customer's div instead.\n */\n readonly embedded?: boolean;\n /**\n * Zero-based step to open the form on, instead of the first.\n *\n * For previews that want to show a particular step -- get.xapp.ai's booking\n * preview opens on the date and time step, because the calendar is the part\n * worth showing. Applied once, when the form arrives; an index the form has\n * no step for is ignored.\n */\n readonly initialStep?: number;\n /**\n * Open the date/time step on the soonest day that has times, rather than on\n * \"Select a date to see the available times.\"\n *\n * For a preview that lands straight on that step: an empty column beside a\n * calendar reads as a form with nothing to offer. Off by default -- on a real\n * booking page a preselected date is one the customer never chose.\n */\n readonly preselectFirstAvailableDate?: boolean;\n /**\n * True when the form was activated by a proactive auto-open trigger\n * (delay/scroll%/exit-intent/inactivity) rather than a genuine user\n * action. Used to keep the `engaged` signal limited to real engagement.\n */\n readonly openedByTrigger?: boolean;\n /**\n * Label of a chip to auto-select after the form loads.\n * If the first response contains chips/suggestions, the form will\n * automatically click the chip matching this label.\n */\n readonly preselectChipLabel?: string;\n /**\n * Callback when preselectChipLabel has been used (to clear it)\n */\n readonly onPreselectChipUsed?: () => void;\n /**\n * Callback invoked when the user submits the final form step.\n *\n * Useful for firing external conversion tracking (e.g. a Meta Pixel\n * `Lead` event) from the embedding page. It receives ONLY a non-PII\n * `eventId` — the same id sent to the backend with the lead — so a\n * browser-side pixel event can be deduplicated against the server-side\n * Conversions API event. The submitted payload (which contains PII) is\n * deliberately never exposed to third-party trackers.\n */\n readonly onSubmit?: (eventId?: string) => void;\n}\n\nexport const FormWidget: FC<FormWidgetProps> = (props) => {\n const { config } = props;\n\n return (\n <SearchWidgetConfigContext.Provider value={config}>\n <FormWidgetRaw\n docked={props.docked}\n embedded={props.embedded}\n initialStep={props.initialStep}\n preselectFirstAvailableDate={props.preselectFirstAvailableDate}\n openedByTrigger={props.openedByTrigger}\n preselectChipLabel={props.preselectChipLabel}\n onPreselectChipUsed={props.onPreselectChipUsed}\n onSubmit={props.onSubmit}\n response={props.response}\n />\n </SearchWidgetConfigContext.Provider>\n );\n};\n\nconst FormWidgetRaw: FC<\n Pick<\n FormWidgetProps,\n | \"docked\"\n | \"embedded\"\n | \"initialStep\"\n | \"preselectFirstAvailableDate\"\n | \"openedByTrigger\"\n | \"response\"\n | \"preselectChipLabel\"\n | \"onPreselectChipUsed\"\n | \"onSubmit\"\n >\n> = (props) => {\n const {\n docked,\n embedded,\n initialStep,\n preselectFirstAvailableDate,\n openedByTrigger,\n preselectChipLabel,\n onPreselectChipUsed,\n onSubmit,\n } =\n props;\n\n const [state, dispatch] = useSearchStore();\n const { loading, run } = useLoading();\n\n const { query, sendRequest, active } = state;\n\n const [response, setResponse] = useState<Response | undefined>(props.response);\n\n // A FORM_STEP_UPDATE display pulled out of a (fire-and-forget) FORM_SUBMIT\n // response, e.g. a booking-widget handoff step's externalWidget.config. Each\n // detected update is a fresh object from the API response, so FormDisplay's\n // effect on this prop always fires for a genuine new update.\n const [stepUpdate, setStepUpdate] = useState<FormStepUpdateDisplay | undefined>(undefined);\n\n const [audioOn, setAudioOn] = useState<boolean>(false);\n\n const [waitingOnAudioToFinish, setwaitingOnAudioToFinish] =\n useState<number>(AUDIO_WAIT_NOTHING);\n\n // why don't we just pass it in as a prop?\n const config = useContext(SearchWidgetConfigContext);\n\n // TrustedForm injects a third-party script that begins certifying the\n // session on mount. A preview must not generate a certificate with\n // ActiveProspect for a visit that isn't a real lead, so demo mode withholds\n // the script URL and the hook no-ops.\n const getTrustedFormData = useTrustedForm(\n config.api.demoMode ? undefined : config.trustedForm?.scriptUrl\n );\n\n const api = useMemo(() => {\n return StentorApi.getApi({\n key: config.api.key,\n url: config.api.url,\n intentId: config.intentId,\n // Carried through so the preview guarantee lives in one place.\n demoMode: config.api.demoMode,\n // prefetchQuery: config.autoGreeting\n });\n }, [config]);\n\n // Event tracking service - initialize with session and form info\n const eventTracker = useRef<EventTrackingService | null>(null);\n const formData = useRef<Record<string, unknown>>({});\n // Ref to sync current step's live data (before step completion)\n const currentStepDataRef = useRef<Record<string, unknown>>({});\n const currentStepRef = useRef<number>(0);\n const formSubmittedRef = useRef<boolean>(false);\n // Guards the docked auto-mount request so it fires exactly once per mount. See the effect below.\n // This never resets, which is correct only because `docked` is fixed for a mounted instance\n // (it is derived once in Form.tsx from config.autoOpen and does not toggle). If `docked` ever\n // becomes a runtime-togglable prop, this guard would suppress the legitimate second request and\n // must reset on the docked false->true transition.\n const dockedRequestSent = useRef<boolean>(false);\n\n // One id per submission, shared between the FORM_SUBMIT payload (sent to the\n // backend, which forwards it to Meta's Conversions API) and the browser Pixel\n // `Lead` event via onSubmit — so Meta deduplicates the two. Lazily created so\n // whichever submit handler runs first mints it and the other reuses it.\n const submitEventIdRef = useRef<string | undefined>(undefined);\n const getSubmitEventId = useCallback((): string => {\n const existing = submitEventIdRef.current;\n if (existing) {\n return existing;\n }\n const id = uuid();\n submitEventIdRef.current = id;\n return id;\n }, []);\n // Ref to store form display info for event tracking (avoids useEffect dependency on response)\n const formDisplayRef = useRef<FormDisplay | null>(null);\n // Ref to store the current form's id for event tracking (mirrors eventTracker's private formId)\n const formIdRef = useRef<string>(\"unknown\");\n // Flag to prevent race condition where timeout fires after close/submit\n const abandonEventSentRef = useRef<boolean>(false);\n // Fires the `form_open` event at most once per mounted widget instance. Without this guard,\n // any intentRequest that resolves to a FORM display re-fires WIDGET_FORM_OPEN - e.g. a\n // chip click (handleActionClick) routed back through intentRequest after the form already\n // opened once. Each re-fire still carries full tracking metadata, but it inflates the OPEN\n // denominator the bounce/conversion funnel is measured against. See issue #1504.\n const formOpenSentRef = useRef<boolean>(false);\n // Fires the `engaged` event at most once per session (first genuine user action)\n const engagementSentRef = useRef<boolean>(false);\n const trackEngagement = useCallback((trigger: EngagementTrigger) => {\n if (!eventTracker.current || engagementSentRef.current) {\n return;\n }\n engagementSentRef.current = true;\n eventTracker.current.trackEngaged({\n formName: formIdRef.current,\n trigger,\n firstStepName: formDisplayRef.current?.steps?.[0]?.name,\n });\n }, []);\n\n const handleCancel = useCallback(() => {\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: true,\n sendRequest: false,\n });\n }, [dispatch]);\n\n const handleClose = useCallback(() => {\n // Track close and partial_data events if form wasn't submitted and abandon event not already sent.\n // Note: These are intentionally fire-and-forget (not awaited) to avoid blocking the UI.\n // The close event captures the UI action, while partial_data captures abandonment analytics\n // with abandonmentReason for funnel analysis. Both events serve different purposes.\n if (eventTracker.current && !formSubmittedRef.current && !abandonEventSentRef.current) {\n const form = formDisplayRef.current;\n if (form) {\n const totalSteps = form.steps?.length || 1;\n const currentStep = currentStepRef.current;\n // Merge completed step data with current step's live data\n const allFormData = { ...formData.current, ...currentStepDataRef.current };\n const hasData = Object.keys(allFormData).length > 0;\n\n // Send close event (captures the UI close action)\n eventTracker.current.trackClose({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n formData: hasData ? allFormData : undefined,\n });\n\n // Send partial_data event (captures abandonment with reason for funnel analysis)\n eventTracker.current.trackPartialData({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n partialData: hasData ? allFormData : undefined,\n abandonmentReason: \"widget_close\",\n });\n\n abandonEventSentRef.current = true;\n }\n }\n\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: false,\n sendRequest: false,\n });\n api.channelActionRequest({ data: { result: {}, step: \"\", form: \"\" } }, \"FORM_CLOSE\").then(\n (closeResponse) => {\n log(\n `ACTION Request (FORM_CLOSE). Data: Response: ${JSON.stringify(closeResponse)}`\n );\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n }\n );\n }, [api, dispatch]);\n\n // Release the event tracker's document listeners when the widget goes away. Embedded mode\n // mounts and unmounts inside a host app, and a visit nobody interacted with would otherwise\n // leave its interaction listeners behind on every unmount.\n useEffect(() => {\n return () => {\n eventTracker.current?.dispose();\n };\n }, []);\n\n // Extract and store tracking parameters on mount\n // Note: This is safe to run even if tracking params were already extracted\n // (e.g., by contact-app). The function is idempotent and will just refresh\n // the stored values with the same data from the URL.\n useEffect(() => {\n const trackingParameters = getAllTrackingParameters(window.location.href, {\n persistToLocalStorage: true,\n persistenceDays: 30,\n preferUrlParameters: true,\n scope: api.trackingScope,\n });\n\n // Log tracking parameters for debugging (development only)\n if (process.env.NODE_ENV === \"development\" && Object.keys(trackingParameters).length > 0) {\n log(\"[FormWidget] Captured tracking parameters:\", trackingParameters);\n }\n }, [api]);\n\n // Track partial_data on page unload using sendBeacon for reliable delivery\n useEffect(() => {\n const handleBeforeUnload = () => {\n // Merge completed step data with current step's live data\n const allFormData = { ...formData.current, ...currentStepDataRef.current };\n\n // Track abandon event if form wasn't submitted and no abandon event sent yet\n if (eventTracker.current && !formSubmittedRef.current && !abandonEventSentRef.current) {\n const form = formDisplayRef.current;\n if (form) {\n const totalSteps = form.steps?.length || 1;\n const currentStep = currentStepRef.current;\n\n eventTracker.current.trackPartialDataBeacon({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n partialData: allFormData,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n completionPercentage: Math.round((currentStep / totalSteps) * 100),\n abandonmentReason: \"close_tab\",\n });\n abandonEventSentRef.current = true;\n }\n }\n };\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n return () => window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n }, []);\n\n // Track partial_data when tab is hidden until midnight (abandoned tab scenario)\n useEffect(() => {\n let midnightTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const calculateMsUntilMidnight = (): number => {\n const now = new Date();\n const midnight = new Date(now);\n midnight.setHours(24, 0, 0, 0); // Next midnight\n return midnight.getTime() - now.getTime();\n };\n\n const sendTimeoutEvent = () => {\n // Merge completed step data with current step's live data\n const allFormData = { ...formData.current, ...currentStepDataRef.current };\n\n // Check all flags to prevent race conditions\n if (eventTracker.current && !formSubmittedRef.current && !abandonEventSentRef.current) {\n const form = formDisplayRef.current;\n if (form) {\n const totalSteps = form.steps?.length || 1;\n const currentStep = currentStepRef.current;\n\n // Use beacon for reliable delivery\n eventTracker.current.trackPartialDataBeacon({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n partialData: allFormData,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n completionPercentage: Math.round((currentStep / totalSteps) * 100),\n abandonmentReason: \"timeout\",\n });\n\n // Mark abandon event sent to prevent duplicate events\n abandonEventSentRef.current = true;\n }\n }\n };\n\n const handleVisibilityChange = () => {\n if (document.hidden) {\n // Tab became hidden - start timer until midnight\n const msUntilMidnight = calculateMsUntilMidnight();\n midnightTimeoutId = setTimeout(sendTimeoutEvent, msUntilMidnight);\n } else {\n // Tab became visible - cancel the midnight timer\n if (midnightTimeoutId) {\n clearTimeout(midnightTimeoutId);\n midnightTimeoutId = null;\n }\n }\n };\n\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n return () => {\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n if (midnightTimeoutId) {\n clearTimeout(midnightTimeoutId);\n }\n };\n }, []);\n\n const intentRequest = useCallback(\n (\n request: { query?: string; intentId?: string },\n options?: { engagementTrigger?: EngagementTrigger }\n ) => {\n dispatch({\n query: request.query,\n intentId: request.intentId,\n type: \"set-query\",\n });\n\n run(() =>\n api.intentRequest(request).then((intentResponse) => {\n setResponse(intentResponse);\n dispatch({\n type: \"set-response\",\n response: intentResponse,\n query: request.query,\n intentId: request.intentId,\n });\n\n // Initialize event tracker when form is loaded\n const formDisplay = intentResponse?.displays?.find((d) => {\n const display = d as unknown as { type?: string };\n return display?.type === \"FORM\";\n }) as FormDisplay | undefined;\n if (formDisplay) {\n formDisplayRef.current = formDisplay;\n // The visit's session: the one the load event already reported\n const { sessionId } = api.visitSession();\n const formId = (formDisplay as { name?: string }).name || \"unknown\";\n formIdRef.current = formId;\n // A later FORM display - a chip click, say - is the same visit, so the\n // replacement inherits when it started and whether anyone has touched it.\n // Without that, every event after the first chip click loses its dwell.\n const previousTracker = eventTracker.current;\n eventTracker.current = new EventTrackingService(api, sessionId, formId);\n eventTracker.current.adoptVisitFrom(previousTracker);\n\n // Track form_open event once per mounted widget instance - the first\n // genuine surfacing of the form (docked render, trigger-activated open,\n // or manual open). A later intentRequest resolving to a FORM display\n // again (e.g. a chip click) is not a new surfacing and must not re-fire\n // WIDGET_FORM_OPEN. See `engaged` for genuine user intent.\n if (!formOpenSentRef.current) {\n formOpenSentRef.current = true;\n const totalSteps = formDisplay.steps?.length || 1;\n const firstStepName = formDisplay.steps?.[0]?.name;\n eventTracker.current.trackFormOpen({\n formName: formId,\n totalSteps,\n firstStepName,\n lastStepIndex: 0,\n });\n }\n\n if (options?.engagementTrigger) {\n trackEngagement(options.engagementTrigger);\n }\n }\n })\n );\n },\n [api, dispatch, run, trackEngagement]\n );\n\n const channelActionRequest = useCallback(\n (data: any, action: string): Promise<void> => {\n const dispatchOnce = () =>\n api.channelActionRequest(data, action).then((response) => {\n log(\n `ACTION Request (${action}). Data: ${JSON.stringify(\n data\n )} Response: ${JSON.stringify(response)}`\n );\n\n // A submit suppressed because the session already saw a final one\n // never reached the server. That is usually correct duplicate\n // protection, but it is also how a wrongly-latched session loses a\n // lead in silence, so say so rather than logging it as a success.\n if (wasDroppedAfterFinal(response)) {\n err(\n `ACTION Request (${action}) was suppressed: this session already sent a final submit.`\n );\n }\n\n if (response.outputSpeech || response.displays) {\n dispatch({\n type: \"set-response\",\n response,\n query: \"\",\n });\n }\n\n // FormDisplay awaits the FORM_SUBMIT dispatch, but only to learn\n // whether it failed -- it still advances on click and does not read\n // a return value. So a FORM_STEP_UPDATE in the response -- e.g. a\n // booking-widget handoff step's externalWidget.config -- is surfaced\n // back to FormDisplay via this prop rather than by threading a\n // return value through onActionResponse.\n if (action === \"FORM_SUBMIT\" && response.displays) {\n const update = (response.displays as unknown as FormStepUpdateDisplay[]).find(\n (display) => display?.type === \"FORM_STEP_UPDATE\"\n );\n if (update) {\n setStepUpdate(update);\n }\n }\n\n // Server side context (usually session params)\n if (response.context?.active && response.context.active.length > 0) {\n const context = response.context.active[0].parameters || {};\n\n dispatch({\n type: \"set-context\",\n context,\n });\n }\n\n if (!!data.autoClose) {\n setwaitingOnAudioToFinish(AUDIO_WAIT_CLOSE);\n } else if (!!data.autoMinimize) {\n setwaitingOnAudioToFinish(AUDIO_WAIT_MINIMIZE);\n } else {\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n }\n });\n\n if (action === \"FORM_SUBMIT\") {\n // Rejects once the retries are exhausted. FormDisplay awaits this and\n // turns a rejection into a visible error the user can retry from --\n // before, it was an unhandled rejection and the lead just vanished.\n return run(() => dispatchWithRetry(dispatchOnce, SUBMIT_RETRY_DELAYS_MS));\n }\n\n // Every other action stays fire-and-forget, but is no longer allowed to\n // become an unhandled rejection.\n return run(dispatchOnce).catch((error) => {\n err(`ACTION Request (${action}) failed: ${error}`);\n });\n },\n [api, dispatch, run]\n );\n\n useEffect(() => {\n // if we need to send, it is active and we have an autoGreeting or intentId\n //\n // The dockedRequestSent guard is load-bearing. This effect dispatches set-modal-state\n // below, which flips `active` false -> true, and `active` is in the dep array — so the\n // effect re-runs. The non-docked branch is protected because that same dispatch sets\n // sendRequest to false, but `docked` short-circuits the condition, so a docked widget\n // fired intentRequest (and therefore trackFormOpen) twice on every mount.\n if (\n (docked && !dockedRequestSent.current) ||\n (sendRequest && active && (config.autoGreeting || config.intentId))\n ) {\n if (docked) {\n dockedRequestSent.current = true;\n }\n api.resetSession();\n // Docked auto-mount and proactive auto-open triggers are impressions,\n // not user intent - only a genuine, non-auto-triggered activation counts\n // as a manual open for the `engaged` signal.\n const engagementTrigger: EngagementTrigger | undefined =\n !docked && !openedByTrigger ? \"manual_open\" : undefined;\n intentRequest(\n { query: config.autoGreeting, intentId: config.intentId },\n { engagementTrigger }\n );\n dispatch({\n type: \"set-modal-state\",\n active: true,\n minimized: false,\n sendRequest: false,\n });\n }\n }, [\n docked,\n openedByTrigger,\n sendRequest,\n active,\n intentRequest,\n dispatch,\n config.autoGreeting,\n api,\n config.intentId,\n ]);\n\n useEffect(() => {\n if (!audioOn) {\n if (waitingOnAudioToFinish === AUDIO_WAIT_CLOSE) {\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: false,\n sendRequest: false,\n });\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n } else if (waitingOnAudioToFinish === AUDIO_WAIT_MINIMIZE) {\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: true,\n sendRequest: false,\n });\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n }\n }\n }, [audioOn, dispatch, waitingOnAudioToFinish]);\n\n const handleActionClick = useCallback(\n (item: SuggestionTypes) => {\n const text = getActionLabel(item);\n // A chip click is always a genuine user action, whether or not the\n // form was originally opened manually.\n intentRequest({ query: text }, { engagementTrigger: \"chip_click\" });\n },\n [intentRequest]\n );\n\n // Auto-select a chip based on preselectChipLabel when response has suggestions\n useEffect(() => {\n if (!preselectChipLabel || !response) {\n return;\n }\n\n // Look for suggestions in the response - outputSpeech can be string or ResponseOutput\n const outputSpeech = response.outputSpeech;\n const suggestions =\n typeof outputSpeech === \"object\" && outputSpeech !== null\n ? outputSpeech.suggestions\n : undefined;\n if (!suggestions || suggestions.length === 0) {\n return;\n }\n\n // Find a chip matching the preselectChipLabel\n const matchingChip = suggestions.find(\n (chip) => getActionLabel(chip).toLowerCase() === preselectChipLabel.toLowerCase()\n );\n\n if (matchingChip) {\n log(`Auto-selecting chip: ${getActionLabel(matchingChip)}`);\n // Small delay to ensure UI is rendered before clicking\n setTimeout(() => {\n handleActionClick(matchingChip);\n }, 100);\n }\n\n // Clear the preselect label so we don't re-trigger\n if (onPreselectChipUsed) {\n onPreselectChipUsed();\n }\n }, [response, preselectChipLabel, handleActionClick, onPreselectChipUsed]);\n\n const handleActionResponse = useCallback(\n (data: unknown, action: string) => {\n if (!action) {\n action = (data as any).action;\n }\n // Tell the server the visitors TZ offset\n (data as any).timezoneOffset = new Date().getTimezoneOffset();\n\n if (action === \"FORM_SUBMIT\") {\n const trustedFormData = getTrustedFormData();\n if (trustedFormData && (data as any).result) {\n (data as any).result = { ...(data as any).result, ...trustedFormData };\n }\n // Carry the shared event id + Meta cookies so the backend can send\n // a deduplicated, high-match Conversions API Lead event.\n (data as any).extras = {\n ...(data as any).extras,\n eventId: getSubmitEventId(),\n ...getMetaCookies(),\n };\n }\n\n // Returned so FormDisplay can await the FORM_SUBMIT dispatch and surface a\n // failure rather than losing the lead silently (issue #1373).\n return channelActionRequest(data, action);\n },\n [channelActionRequest, getTrustedFormData, getSubmitEventId]\n );\n\n const handleFormNext = useCallback(\n (data: FormNextData) => {\n return api.channelActionRequest(data, \"FORM_NEXT\");\n },\n [api]\n );\n\n const handleAudioChange = (isOn: boolean) => {\n setAudioOn(isOn);\n };\n\n // Tracking callbacks\n // Note: We intentionally fire BOTH specific events (next_step/previous_step) AND generic events (step_change).\n // - next_step/previous_step: Rich context for specific navigation analytics\n // - step_change: Unified view of all navigation for funnel analysis\n // This dual-event pattern is per the Widget Events API spec. May consolidate later based on analytics needs.\n const handleTrackInitialStep = useCallback((stepIndex: number) => {\n // The form opened straight on this step, so it is where the visitor\n // actually is. currentStepRef is otherwise only written by the\n // next/previous handlers, which need an explicit navigation to fire --\n // leaving it on 0 for a form opened via initialStep, and under-reporting\n // lastStepIndex and completionPercentage on every abandonment path.\n //\n // Deliberately not trackEngagement: nobody engaged with anything by\n // being shown a step.\n currentStepRef.current = stepIndex;\n }, []);\n\n const handleTrackNextStep = useCallback(\n (\n stepName: string,\n stepIndex: number,\n stepData: Record<string, unknown>,\n isLastStep: boolean\n ) => {\n // Update form data ref and reset current step data for the new step\n formData.current = { ...formData.current, ...stepData };\n currentStepDataRef.current = {}; // Reset live data for new step\n currentStepRef.current = stepIndex + 1; // Moving to next step\n\n // Completing a step is a genuine user action, whether or not the\n // form was originally opened manually.\n trackEngagement(\"step_transition\");\n\n if (eventTracker.current) {\n const form = formDisplayRef.current;\n const nextStepName = form?.steps?.[stepIndex + 1]?.name;\n const totalSteps = form?.steps?.length || 1;\n\n // Track next_step event (specific forward navigation with step data)\n eventTracker.current.trackNextStep({\n completedStepName: stepName,\n completedStepIndex: stepIndex,\n nextStepName,\n stepData,\n isLastStep,\n });\n\n // Track step_change event (generic navigation for unified funnel view)\n if (nextStepName) {\n eventTracker.current.trackStepChange({\n fromStepName: stepName,\n fromStepIndex: stepIndex,\n toStepName: nextStepName,\n toStepIndex: stepIndex + 1,\n direction: \"forward\",\n lastStepIndex: stepIndex + 1,\n totalSteps,\n });\n }\n }\n },\n [trackEngagement]\n );\n\n const handleTrackPreviousStep = useCallback(\n (fromStepName: string, fromStepIndex: number, toStepName: string, toStepIndex: number) => {\n // Update current step ref and reset current step data for the new step\n currentStepDataRef.current = {}; // Reset live data for new step\n currentStepRef.current = toStepIndex;\n\n if (eventTracker.current) {\n const totalSteps = formDisplayRef.current?.steps?.length || 1;\n\n // Track previous_step event (specific backward navigation)\n eventTracker.current.trackPreviousStep({\n fromStepName,\n fromStepIndex,\n toStepName,\n toStepIndex,\n lastStepIndex: toStepIndex,\n totalSteps,\n });\n\n // Track step_change event (generic navigation for unified funnel view)\n eventTracker.current.trackStepChange({\n fromStepName,\n fromStepIndex,\n toStepName,\n toStepIndex,\n direction: \"backward\",\n lastStepIndex: toStepIndex,\n totalSteps,\n });\n }\n },\n []\n );\n\n const handleTrackSubmit = useCallback(\n (\n stepName: string,\n stepIndex: number,\n completedData: Record<string, unknown>,\n totalSteps: number\n ) => {\n // Guard against double-firing the submit event: a double-click before the\n // \"submitting\" UI state flushes, a re-render, or a retry can invoke this\n // callback more than once for the same submission. Only the first call\n // should ever track/notify.\n if (formSubmittedRef.current) {\n return;\n }\n formSubmittedRef.current = true;\n\n // Include TrustedForm cert URL in submit event if available\n const trustedFormData = getTrustedFormData();\n const dataWithTrustedForm = trustedFormData\n ? { ...completedData, ...trustedFormData }\n : completedData;\n\n formData.current = dataWithTrustedForm;\n\n if (eventTracker.current) {\n eventTracker.current.trackSubmit({\n finalStepName: stepName,\n finalStepIndex: stepIndex,\n completedData: dataWithTrustedForm,\n totalSteps,\n });\n }\n\n // Notify the embedding page that a submit happened (e.g. to fire\n // external conversion tracking). Deliberately passes no data: the\n // submitted payload contains PII (and the TrustedForm cert URL) and\n // must not be handed to third-party trackers.\n // ...unless this is a preview. onSubmit exists so the host can\n // fire external conversion tracking — a Meta Pixel Lead event, per\n // its own doc comment. That reaches a third-party ad platform, so\n // it is the most consequential signal demo mode has to suppress:\n // it is driven purely by UI completion and would otherwise fire for\n // a session that never touched the backend.\n if (onSubmit && !config.api.demoMode) {\n try {\n onSubmit(getSubmitEventId());\n } catch (error) {\n err(\"[FormWidget] onSubmit callback threw:\", error);\n }\n }\n },\n [getTrustedFormData, onSubmit, getSubmitEventId, config.api.demoMode]\n );\n\n // The FORM_SUBMIT dispatch failed after its retries, so the lead was not created.\n // handleTrackSubmit above has already recorded the submit; this is the counter-signal\n // that keeps that from reading as a success (issue #1373). The formSubmittedRef guard\n // is deliberately not consulted -- the submit event it gated has already gone out,\n // and this event is what corrects it.\n const handleTrackSubmitFailure = useCallback(\n (stepName: string, stepIndex: number, totalSteps: number, reason: string) => {\n eventTracker.current?.trackSubmitFailure({\n finalStepName: stepName,\n finalStepIndex: stepIndex,\n totalSteps,\n reason,\n });\n },\n []\n );\n\n // Booking-widget handoff step tracking. formName/sessionId are carried on\n // every event via eventTracker's own metadata (see EventTrackingService),\n // matching how the other track* handlers above don't pass them explicitly.\n const handleTrackHandoffRendered = useCallback((stepName: string, provider: string) => {\n eventTracker.current?.trackHandoffRendered({ stepName, provider });\n }, []);\n\n const handleTrackHandoffNoRender = useCallback((stepName: string, provider: string) => {\n eventTracker.current?.trackHandoffNoRender({ stepName, provider });\n }, []);\n\n const handleTrackHandoffScheduled = useCallback((stepName: string, provider: string, payload?: unknown) => {\n eventTracker.current?.trackHandoffScheduled({ stepName, provider, payload });\n }, []);\n\n const handleTrackHandoffError = useCallback((stepName: string, provider: string) => {\n eventTracker.current?.trackHandoffError({ stepName, provider });\n }, []);\n\n const displayContainer: boolean = !!query || !!response;\n\n if (docked) {\n // we might want to put a wrapper around this for docked mode\n return (\n <div\n className={`${styles.xapp_form_widget} ${embedded ? styles.embedded : \"\"} ${\n loading ? styles.loading : \"\"\n }`}>\n <div\n className={`${styles[\"xapp_form_widget__content\"]} ${\n loading ? styles.loading : \"\"\n }`}\n >\n {response ? (\n <FormResponse\n response={response}\n className={styles[\"xapp_form_widget__response\"]}\n onActionClick={handleActionClick}\n onActionResponse={handleActionResponse}\n onAudioChange={handleAudioChange}\n loading={loading}\n onTrackNextStep={handleTrackNextStep}\n onTrackPreviousStep={handleTrackPreviousStep}\n onTrackSubmit={handleTrackSubmit}\n onTrackSubmitFailure={handleTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={handleTrackInitialStep}\n onFormNext={handleFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={handleTrackHandoffRendered}\n onTrackHandoffNoRender={handleTrackHandoffNoRender}\n onTrackHandoffScheduled={handleTrackHandoffScheduled}\n onTrackHandoffError={handleTrackHandoffError}\n />\n ) : (\n <div className={styles[\"xapp_form_widget__spinner\"]}>\n <SpinnerIcon />\n </div>\n )}\n </div>\n </div>\n );\n }\n\n return (\n <div\n className={`${styles.xapp_form_widget} ${embedded ? styles.embedded : \"\"} ${\n loading && !response ? styles.loading : \"\"\n }`}>\n {displayContainer && (\n <div\n className={`${styles[\"xapp_form_widget__content\"]} ${\n loading && !response ? styles.loading : \"\"\n }`}\n >\n {!response && loading && (\n <div className={styles[\"xapp_form_widget__spinner\"]}>\n <SpinnerIcon />\n </div>\n )}\n\n {response && (\n <FormResponse\n response={response}\n className={styles[\"xapp_form_widget__response\"]}\n onActionClick={handleActionClick}\n onActionResponse={handleActionResponse}\n onAudioChange={handleAudioChange}\n loading={loading}\n onTrackNextStep={handleTrackNextStep}\n onTrackPreviousStep={handleTrackPreviousStep}\n onTrackSubmit={handleTrackSubmit}\n onTrackSubmitFailure={handleTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={handleTrackInitialStep}\n onFormNext={handleFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={handleTrackHandoffRendered}\n onTrackHandoffNoRender={handleTrackHandoffNoRender}\n onTrackHandoffScheduled={handleTrackHandoffScheduled}\n onTrackHandoffError={handleTrackHandoffError}\n />\n )}\n </div>\n )}\n\n {response && !!handleCancel && (\n <div className={styles[\"xapp_form_widget__close\"]} onClick={handleClose}>\n {\"\\u2715\"}\n </div>\n )}\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport {\n FormWidgetDropdownTheme,\n FormWidgetFontTheme,\n FormWidgetTextTheme,\n FormWidgetButtonTheme,\n FormWidgetStepTitleTheme,\n FormWidgetTheme,\n FormWidgetCardTheme,\n FormWidgetCheckboxTheme,\n FormWidgetChipsTheme,\n FormWidgetDateTheme,\n FormWidgetSideButtonTheme,\n FormWidgetExternalWidgetTheme,\n} from \"@xapp/stentor-form-widget-channel\";\n\nimport { err } from \"../../utils\";\n\nexport interface WidgetStylesheetProps {\n readonly theme?: FormWidgetTheme;\n}\n\n/**\n * Injects the styles\n *\n * @param props\n * @returns\n */\nexport const WidgetStylesheet: FC<WidgetStylesheetProps> = (props) => {\n const { theme } = props;\n\n // Load external font if specified\n React.useEffect(() => {\n const currentFontLink = theme?.font?.link;\n\n if (currentFontLink) {\n loadExternalFont(currentFontLink);\n }\n\n // Cleanup function to remove font link when component unmounts or font changes\n return () => {\n if (currentFontLink) {\n const linkId = \"xapp-form-widget-font\";\n const existingLink = document.getElementById(linkId);\n // Only remove if it's the font we loaded in this effect\n if (existingLink && existingLink.getAttribute(\"href\") === currentFontLink) {\n existingLink.remove();\n }\n }\n };\n }, [theme?.font?.link]);\n\n // Apply the theme as CSS custom properties on :root via the CSSOM instead of\n // injecting a <style> tag: setProperty() is not governed by CSP style-src, so\n // the widget themes correctly under a strict policy (style-src 'self', no\n // 'unsafe-inline') without needing a nonce.\n const entriesKey = JSON.stringify(buildStyleVariables(theme));\n React.useLayoutEffect(() => {\n const entries = JSON.parse(entriesKey) as Array<[string, string]>;\n applyThemeVariables(entries);\n return () => removeThemeVariables(entries);\n }, [entriesKey]);\n\n return null;\n};\n\n/**\n * Loads an external font by injecting a link tag into the document head\n * Automatically adds font-display=swap optimization for Google Fonts\n */\nexport function loadExternalFont(fontUrl: string): void {\n // Validate URL format and security\n try {\n const url = new URL(fontUrl);\n if (url.protocol !== \"https:\") {\n console.warn(\"Only HTTPS font URLs are allowed:\", fontUrl);\n return;\n }\n\n // Optional: Restrict to trusted font providers\n const trustedDomains = [\n \"fonts.googleapis.com\",\n \"fonts.gstatic.com\",\n \"use.typekit.net\",\n \"use.fontawesome.com\",\n \"cdn.jsdelivr.net\",\n \"unpkg.com\",\n \"cdnjs.cloudflare.com\",\n ];\n\n if (!trustedDomains.includes(url.hostname)) {\n console.warn(\"Font URL from untrusted domain:\", url.hostname);\n // Still proceed but warn - in production you might want to block this\n }\n\n // Add font-display=swap for Google Fonts if not already present\n if (url.hostname === \"fonts.googleapis.com\" && !url.searchParams.has(\"display\")) {\n url.searchParams.set(\"display\", \"swap\");\n fontUrl = url.toString();\n }\n } catch (error) {\n console.error(\"Invalid font URL:\", fontUrl, error);\n return;\n }\n\n const linkId = \"xapp-form-widget-font\";\n\n // Remove existing font link if present\n const existingLink = document.getElementById(linkId);\n if (existingLink) {\n existingLink.remove();\n }\n\n // Create and inject new font link\n const link = document.createElement(\"link\");\n link.id = linkId;\n link.rel = \"stylesheet\";\n link.href = fontUrl;\n link.crossOrigin = \"anonymous\"; // Add security attribute\n document.head.appendChild(link);\n}\n\n// All instances apply their theme variables to the same target (:root), so a\n// per-variable ref-count ensures an unmounting instance only removes a variable\n// when no other mounted instance still relies on it.\nconst appliedVariableCounts = new Map<string, number>();\n\nfunction applyThemeVariables(entries: Array<[string, string]>): void {\n const root = document.documentElement;\n for (const [key, value] of entries) {\n root.style.setProperty(key, value);\n appliedVariableCounts.set(key, (appliedVariableCounts.get(key) ?? 0) + 1);\n }\n}\n\nfunction removeThemeVariables(entries: Array<[string, string]>): void {\n const root = document.documentElement;\n for (const [key] of entries) {\n const remaining = (appliedVariableCounts.get(key) ?? 1) - 1;\n if (remaining <= 0) {\n appliedVariableCounts.delete(key);\n root.style.removeProperty(key);\n } else {\n appliedVariableCounts.set(key, remaining);\n }\n }\n}\n\n/**\n * Generates the [cssVariableName, value] pairs for a form-widget theme, e.g.\n * [\"--xapp-form-widget-background-color\", \"#ffffff\"].\n */\nfunction themeVariables(widgetTheme?: FormWidgetTheme): StyleGenerator {\n const theme: FormWidgetTheme = widgetTheme || {};\n return withPrefix(\n \"--xapp-form-widget-\",\n union(\n single(\"background-color\", theme?.backgroundColor),\n single(\"header-background-color\", theme?.headerBackgroundColor),\n single(\"header-text-color\", theme?.headerTextColor),\n single(\"primary-button-color\", theme?.primaryButtonColor),\n single(\"primary-button-text-color\", theme?.primaryButtonTextColor),\n single(\"secondary-button-color\", theme?.secondaryButtonColor),\n single(\"secondary-button-text-color\", theme?.secondaryButtonTextColor),\n single(\"border-color\", theme?.borderColor),\n // The stylesheet reads two steps of the radius scale and nothing emitted\n // either, so neither could be set at all. One theme value drives both.\n single(\"border-radius-md\", theme?.borderRadius),\n single(\"border-radius-xl\", theme?.borderRadius),\n withPrefix(\"font-\", union(getFontStyle(theme?.font))),\n withPrefix(\"text-\", union(getTextStyle(theme?.text))),\n withPrefix(\"back-button-\", union(getBackButtonStyle(theme))),\n withPrefix(\"button-\", union(getButtonStyle(theme?.button))),\n withPrefix(\"step-title-\", union(getStepTitleStyle(theme?.stepTitle))),\n withPrefix(\"final-button-\", union(getFinalButtonStyle(theme))),\n withPrefix(\"dropdown-\", union(getDropdownStyle(theme?.dropdown))),\n withPrefix(\"checkbox-\", union(getCheckboxStyle(theme?.checkbox))),\n withPrefix(\"chips-\", union(getChipsStyle(theme?.chips))),\n withPrefix(\"date-\", union(getDateStyle(theme?.date))),\n withPrefix(\"card-\", union(getCardStyle(theme?.card))),\n withPrefix(\"side-button-\", union(getSideButtonStyle(theme?.sideButton))),\n withPrefix(\"external-widget-\", union(getExternalWidgetStyle(theme?.externalWidget)))\n )\n );\n}\n\n/**\n * Collects the defined theme CSS variables as [name, value] entries, skipping\n * empty values.\n */\nexport function buildStyleVariables(theme?: FormWidgetTheme): Array<[string, string]> {\n const entries: Array<[string, string]> = [];\n const gen = themeVariables(theme);\n let result = gen.next();\n while (result.done === false) {\n const [key, value] = result.value;\n if (value !== undefined && value !== null && value !== \"\") {\n entries.push([key, value]);\n }\n result = gen.next();\n }\n return entries;\n}\n\nexport function buildStyleContent(widgetTheme?: FormWidgetTheme): string {\n const body = buildStyleVariables(widgetTheme)\n .map(([key, value]) => `\\t${key}: ${value};`)\n .join(\"\\n\");\n return `\\n:root {\\n${body}\\n}\\n`;\n}\n\nfunction* getFontStyle(style?: FormWidgetFontTheme): StyleGenerator {\n if (style) {\n yield [\"family\", style.fontFamily];\n }\n}\n\nfunction* getSideButtonStyle(style?: FormWidgetSideButtonTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-dark\", darken(style.backgroundColor, 10)];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n yield [\"top\", style.top];\n yield [\"min-length\", style.minLength];\n }\n}\n\n/**\n * The back control, including which of its two shapes to draw.\n *\n * The variant is emitted as display toggles rather than threaded to the component as a prop:\n * the theme reaches FormStepDisplay only as CSS variables, and the alternative was passing it\n * through Form -> FormDisplay -> FormStepDisplay purely so a button could pick a shape.\n * The component renders both a label and an arrow; exactly one of them is ever displayed.\n */\n/** A step's opening heading. Absent leaves it left-aligned body text, as today. */\nfunction* getStepTitleStyle(style?: FormWidgetStepTitleTheme): StyleGenerator {\n if (style) {\n yield [\"align\", style.align];\n yield [\"font-size\", style.fontSize];\n yield [\"font-weight\", style.fontWeight];\n yield [\"color\", style.color];\n }\n}\n\n/**\n * Final-step layout. `\"above\"` is emitted as nothing at all -- the scss defaults ARE that\n * layout -- so only `\"inline\"` produces variables.\n */\nfunction* getFinalButtonStyle(theme?: FormWidgetTheme): StyleGenerator {\n if (theme?.finalButtonPlacement === \"inline\") {\n // row-reverse: the submit button comes first in the DOM, so reversing puts the back\n // control on the left and submit beside it, on one line.\n yield [\"direction\", \"row-reverse\"];\n yield [\"gap\", \"24px\"];\n yield [\"nav-flex\", \"0 0 auto\"];\n yield [\"nav-align\", \"center\"];\n yield [\"container-padding\", \"20px 0\"];\n yield [\"nav-padding\", \"20px 0\"];\n }\n}\n\n/** Shape and type of the advance buttons. Absent leaves MUI's own metrics in place. */\nfunction* getButtonStyle(style?: FormWidgetButtonTheme): StyleGenerator {\n if (style) {\n yield [\"font-size\", style.fontSize];\n yield [\"font-weight\", style.fontWeight];\n yield [\"padding\", style.padding];\n yield [\"radius\", style.borderRadius];\n yield [\"shadow\", style.boxShadow];\n }\n}\n\nfunction* getBackButtonStyle(theme?: FormWidgetTheme): StyleGenerator {\n const icon = theme?.backButtonVariant === \"icon\";\n const back = theme?.backButton;\n\n // Defaults reproduce the labelled filled button every existing form has.\n yield [\"label-display\", icon ? \"none\" : \"inline\"];\n yield [\"icon-display\", icon ? \"inline-flex\" : \"none\"];\n\n if (icon) {\n const color = back?.color;\n yield [\"background\", \"transparent\"];\n yield [\"border\", `${back?.borderWidth || \"1px\"} solid ${back?.borderColor || color || \"currentColor\"}`];\n // The arrow is a text glyph, and glyph weight depends on the font -- Poppins barely\n // thickens it. A stroke thickens it the same in any font.\n yield [\"icon-stroke\", back?.iconStroke];\n yield [\"radius\", \"50%\"];\n // The default is now MUI's elevation (so the labelled button keeps it); a ring doesn't\n // want one.\n yield [\"shadow\", \"none\"];\n yield [\"size\", \"44px\"];\n yield [\"padding\", \"0\"];\n // Always emitted for the icon. The scss fallback is the BUTTON TEXT colour, which is right\n // for the labelled variant (it sits on the primary fill) and wrong here: the icon has no\n // fill, so a usually-white text colour made the arrow and its ring vanish on a light page.\n // `currentColor`, which takes the page's own text colour -- legible on the page by\n // definition. NOT `inherit`: that is a CSS-wide keyword, so `--x: inherit` makes the\n // custom property itself inherit (from nothing, on :root) rather than holding the word,\n // and var() falls straight through to the white default. `currentColor` is an ordinary\n // value, substitutes cleanly, and `color: currentColor` computes as inherit.\n yield [\"color\", color || \"currentColor\"];\n yield [\"color-hover\", back?.colorHover || color || \"currentColor\"];\n }\n}\n\nfunction* getTextStyle(style?: FormWidgetTextTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-dark\", darken(style.backgroundColor, 3)];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n // Absent leaves the field borderless, which is what every form that never set these\n // already looks like -- the scss defaults are a zero width and a transparent colour.\n yield [\"border-color\", style.borderColor];\n yield [\"border-width\", style.borderWidth];\n yield [\"border-color-focus\", style.borderColorFocus || style.borderColor];\n // MUI's filled input draws its own underline as a ::before/::after on the root. It is a\n // straight 1px line across the full width, so on a field that now has a rounded border\n // it reads as a darker bar running past the corners. A themed border replaces it;\n // without one it is still the field's only affordance, so it stays.\n yield [\"underline-display\", style.borderWidth ? \"none\" : undefined];\n // With no underline to meet, the bottom corners round like the top ones again.\n yield [\"bottom-radius\", style.borderWidth ? \"var(--xapp-form-widget-border-radius-sm, 8px)\" : undefined];\n // The address autocomplete paints its box on the ROOT, which also holds the dropdown\n // adornment. Only when a border is themed -- otherwise these stay unset and the root\n // keeps MUI's own filled look, which is what every other form has.\n if (style.borderWidth) {\n yield [\"root-background\", style.backgroundColor];\n yield [\"root-border\", `${style.borderWidth} solid ${style.borderColor || \"transparent\"}`];\n yield [\"root-radius\", \"var(--xapp-form-widget-border-radius-sm, 8px)\"];\n yield [\"input-background\", \"transparent\"];\n }\n }\n}\n\nfunction* getDropdownStyle(style?: FormWidgetDropdownTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getCheckboxStyle(style?: FormWidgetCheckboxTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getChipsStyle(style?: FormWidgetChipsTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-selected\", style.backgroundColorSelected];\n yield [\"background-color-dark\", darken(style.backgroundColor, 20)];\n yield [\"color\", style.color];\n yield [\"color-selected\", style.colorSelected];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getDateStyle(style?: FormWidgetDateTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-selected\", style.backgroundColorSelected];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getCardStyle(style?: FormWidgetCardTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getExternalWidgetStyle(style?: FormWidgetExternalWidgetTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"padding\", style.padding];\n yield [\"min-height\", style.minHeight];\n }\n}\n\ndeclare type StyleGenerator = Generator<[string, string | undefined], void, never>;\n\n// function* empty(): StyleGenerator {}\n\nfunction* withPrefix(prefix: string, gen: StyleGenerator): StyleGenerator {\n let result = gen.next();\n while (!result.done) {\n yield [`${prefix}${result.value[0]}`, result.value[1]];\n result = gen.next();\n }\n}\n\nfunction* union(...children: StyleGenerator[]): StyleGenerator {\n for (const child of children) {\n let result = child.next();\n while (result.done === false) {\n yield result.value;\n result = child.next();\n }\n }\n}\n\nfunction* single(key: string, value: string | undefined): StyleGenerator {\n yield [key, value];\n}\n\nfunction darken(colorIn: string | undefined, amount: number) {\n if (!colorIn) {\n return colorIn;\n }\n\n let r: number | undefined, g: number | undefined, b: number | undefined, a: number | undefined;\n let colorOut;\n\n try {\n // Parse the color format\n if (colorIn.startsWith(\"#\")) {\n // Hex format\n const hexMatch = colorIn.match(/\\w\\w/g);\n if (hexMatch) {\n [r, g, b] = hexMatch.map((x) => parseInt(x, 16));\n }\n } else if (colorIn.startsWith(\"rgb\")) {\n // RGB or RGBA format\n const rgba = parseRgb(colorIn);\n if (rgba) {\n ({ r, g, b, a } = rgba);\n }\n }\n\n if (r === undefined || g === undefined || b === undefined) {\n err(`Darken: Unsupported color format: ${colorIn}`);\n return colorIn;\n }\n\n if (a !== undefined) {\n // Just darkened backdrop?\n if (r === 0 && g === 0 && b === 0) {\n a = a + amount / 100;\n } else {\n // Adjust luminance for RGBA\n const luminance = 0.3 * r + 0.59 * g + 0.11 * b;\n const newLuminance = luminance * (1 - amount / 100);\n const ratio = newLuminance / luminance;\n r = Math.round(r * ratio);\n g = Math.round(g * ratio);\n b = Math.round(b * ratio);\n }\n\n colorOut = `rgba(${r}, ${g}, ${b}, ${a})`;\n } else {\n // Darken the color for RGB or Hex\n r = Math.max(0, r - amount);\n g = Math.max(0, g - amount);\n b = Math.max(0, b - amount);\n\n colorOut = `#${r.toString(16).padStart(2, \"0\")}${g.toString(16).padStart(2, \"0\")}${b\n .toString(16)\n .padStart(2, \"0\")}`;\n }\n } catch (e) {\n err(`Darken: Unsupported color format: ${colorIn} - Error: ${e}`);\n }\n\n return colorOut;\n}\n\nfunction parseRgb(colorString: string): { r: number; g: number; b: number; a?: number } | null {\n const rgbaRegex = /^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+),\\s*([\\d.]+)\\)$/;\n const rgbRegex = /^rgb?\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/;\n\n let match: string[] | null;\n\n // eslint-disable-next-line no-cond-assign\n if ((match = colorString.match(rgbaRegex))) {\n const r = parseInt(match[1]);\n const g = parseInt(match[2]);\n const b = parseInt(match[3]);\n const a = parseFloat(match[4]);\n\n return { r, g, b, a };\n // eslint-disable-next-line no-cond-assign\n } else if ((match = colorString.match(rgbRegex))) {\n const r = parseInt(match[1]);\n const g = parseInt(match[2]);\n const b = parseInt(match[3]);\n\n return { r, g, b };\n } else {\n return null;\n }\n}\n","export enum classNames {\n XAPP_FORM_BUTTON = \"xapp-form-button\"\n}\n","import React, { FC } from \"react\";\n\nimport styles from \"./SideButton.module.scss\";\n\nexport interface SideButtonProps {\n readonly onClick?: () => void;\n readonly position?: string;\n readonly label?: string;\n /**\n * Keeps the button in the DOM but off screen, so host scripts that click it still work.\n */\n readonly hidden?: boolean;\n}\n\nexport const SideButton: FC<SideButtonProps> = (props) => {\n const { onClick, position, label, hidden } = props;\n\n const sideButtonPositionClass = position?.toLowerCase() === \"right\" ? styles.right : styles.left;\n\n return (\n <div\n onClick={onClick}\n className={`${styles.xapp_form_sticky_button} ${sideButtonPositionClass}`}\n data-xapp-form-side-button=\"true\"\n // Inline rather than the `hidden` attribute: the module class sets display and would win.\n style={hidden ? { display: \"none\" } : undefined}\n aria-hidden={hidden || undefined}>\n \n {/* <svg\n className={styles.xapp_form_sticky_button_left_img}\n width=\"69\"\n height=\"43\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n version=\"1.1\">\n <path\n d=\"M0 0v43h68.4a38 38 0 0 1-32.71-18.66l-3.36-5.68A38 38 0 0 0 0 0Z\"\n fill=\"#EF7E45\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n />\n </svg> */}\n\n <span>{label || \"Schedule Now\"}</span>\n\n {/* <svg\n className={styles.xapp_form_sticky_button_right_img}\n width=\"69\"\n height=\"43\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n version=\"1.1\"\n transform=\"matrix(1,0,0,-1,0,0)\">\n <path\n d=\"M0 0v43h68.4a38 38 0 0 1-32.71-18.66l-3.36-5.68A38 38 0 0 0 0 0Z\"\n fill=\"#EF7E45\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n />\n </svg> */}\n </div>\n );\n};\n\nexport default SideButton;\n","import { useEffect, useRef, useCallback, useMemo } from \"react\";\nimport { FormWidgetEnv } from \"@xapp/stentor-form-widget-channel\";\n\ntype AutoOpenConfig = FormWidgetEnv[\"autoOpen\"];\n\nexport interface UseAutoOpenTriggersOptions {\n config?: AutoOpenConfig;\n isActive: boolean;\n onOpen: () => void;\n hasInteracted: boolean;\n}\n\n/** Default sessionStorage key for tracking dismissed state */\nexport const DEFAULT_SESSION_KEY = \"xafw-auto-open-dismissed\";\nconst DEFAULT_EXIT_INTENT_THRESHOLD = 50;\nconst MIN_DELAY = 0;\nconst MAX_DELAY = 300000; // 5 minutes\nconst MIN_SCROLL_PERCENT = 0;\nconst MAX_SCROLL_PERCENT = 100;\n\n/**\n * Validates and clamps a delay/inactivity value to safe bounds\n */\nfunction validateDelay(value: number | undefined): number | undefined {\n if (typeof value !== \"number\" || value < MIN_DELAY) return undefined;\n return Math.min(value, MAX_DELAY);\n}\n\n/**\n * Validates and clamps scroll percentage to 0-100\n */\nfunction validateScrollPercent(value: number | undefined): number | undefined {\n if (typeof value !== \"number\") return undefined;\n return Math.max(MIN_SCROLL_PERCENT, Math.min(value, MAX_SCROLL_PERCENT));\n}\n\n/**\n * Validates exit intent threshold (must be positive)\n */\nfunction validateThreshold(value: number | undefined): number {\n if (typeof value !== \"number\" || value < 0) return DEFAULT_EXIT_INTENT_THRESHOLD;\n return value;\n}\n\n/**\n * Checks if the form was already dismissed this session\n */\nfunction isDismissed(sessionKey: string): boolean {\n try {\n return sessionStorage.getItem(sessionKey) === \"true\";\n } catch {\n // Private browsing or sessionStorage not available\n return false;\n }\n}\n\n/**\n * Returns true if any behavior-based auto-open trigger (delay, scrollPercent,\n * exitIntent, inactivity) is configured.\n *\n * Used to distinguish \"open immediately\" (`enabled` alone) from \"open once a\n * trigger condition is met\" (`enabled` + `triggers`).\n */\nexport function hasAutoOpenTriggers(config?: AutoOpenConfig): boolean {\n const triggers = config?.triggers;\n // Compare the *validated* values, not the raw config. The hook below arms its listeners\n // off the validated values too, so reading the raw ones here lets the two disagree: a\n // config like `{ delay: -1 }` would look like a configured trigger (so the form waits\n // instead of opening immediately) while the hook discards it (so no trigger ever fires)\n // -- and the form would silently never open at all.\n return (\n validateDelay(triggers?.delay) !== undefined ||\n validateScrollPercent(triggers?.scrollPercent) !== undefined ||\n !!triggers?.exitIntent ||\n validateDelay(triggers?.inactivity) !== undefined\n );\n}\n\n/**\n * Checks if current URL matches any of the provided patterns\n */\nfunction matchesUrlPatterns(patterns?: string[]): boolean {\n if (!patterns || patterns.length === 0) {\n return true;\n }\n const currentUrl = window.location.href;\n return patterns.some((pattern) => currentUrl.includes(pattern));\n}\n\n/**\n * Checks if viewport width meets minimum requirement\n */\nfunction meetsMinimumWidth(minimumWidth?: number): boolean {\n if (typeof minimumWidth !== \"number\") {\n return true;\n }\n return window.innerWidth >= minimumWidth;\n}\n\n/**\n * Checks if device supports touch (for disabling exit intent on touch devices)\n */\nfunction isTouchDevice(): boolean {\n return \"ontouchstart\" in window || navigator.maxTouchPoints > 0;\n}\n\n/**\n * Hook for auto-opening the form widget based on configurable triggers.\n *\n * Supports:\n * - delay: Timer-based trigger (milliseconds)\n * - scrollPercent: Scroll-based trigger (0-100)\n * - exitIntent: Mouse leaving viewport trigger\n * - inactivity: User idle trigger (milliseconds)\n *\n * Modes:\n * - 'any' (default): First trigger that fires opens the form\n * - 'all': All configured triggers must fire before opening\n */\nexport function useAutoOpenTriggers({\n config,\n isActive,\n onOpen,\n hasInteracted,\n}: UseAutoOpenTriggersOptions): void {\n const triggersRef = useRef<Set<string>>(new Set());\n const hasOpenedRef = useRef(false);\n const inactivityTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n const sessionKey = config?.sessionKey || DEFAULT_SESSION_KEY;\n const mode = config?.mode || \"any\";\n const triggers = config?.triggers;\n\n // Extract and validate primitive values to use as stable dependencies\n const delay = validateDelay(triggers?.delay);\n const scrollPercent = validateScrollPercent(triggers?.scrollPercent);\n const exitIntent = triggers?.exitIntent;\n const exitIntentThreshold = validateThreshold(triggers?.exitIntentThreshold);\n const inactivity = validateDelay(triggers?.inactivity);\n const patterns = config?.patterns;\n const minimumWidth = config?.minimumWidth;\n\n // Serialize patterns array to create a stable dependency\n // This prevents effect re-runs when array reference changes but contents are identical\n const patternsKey = useMemo(() => JSON.stringify(patterns ?? []), [patterns]);\n\n // Calculate which triggers are configured\n const configuredTriggers = useRef<string[]>([]);\n\n // Get list of configured triggers\n const getConfiguredTriggers = useCallback((): string[] => {\n const list: string[] = [];\n if (triggers?.delay !== undefined) list.push(\"delay\");\n if (triggers?.scrollPercent !== undefined) list.push(\"scrollPercent\");\n if (triggers?.exitIntent) list.push(\"exitIntent\");\n if (triggers?.inactivity !== undefined) list.push(\"inactivity\");\n return list;\n }, [triggers?.delay, triggers?.scrollPercent, triggers?.exitIntent, triggers?.inactivity]);\n\n // Check if we should open based on mode and fired triggers\n const checkAndOpen = useCallback(\n (triggerName: string) => {\n if (hasOpenedRef.current) return;\n\n triggersRef.current.add(triggerName);\n\n if (mode === \"any\") {\n // Open on first trigger\n hasOpenedRef.current = true;\n onOpen();\n } else if (mode === \"all\") {\n // Check if all configured triggers have fired\n const configured = configuredTriggers.current;\n const allFired = configured.every((t) => triggersRef.current.has(t));\n if (allFired) {\n hasOpenedRef.current = true;\n onOpen();\n }\n }\n },\n [mode, onOpen]\n );\n\n useEffect(() => {\n // Reset state when config changes\n triggersRef.current = new Set();\n hasOpenedRef.current = false;\n configuredTriggers.current = getConfiguredTriggers();\n }, [getConfiguredTriggers]);\n\n useEffect(() => {\n // Guard conditions - skip if any are true\n const hasTriggers =\n delay !== undefined ||\n scrollPercent !== undefined ||\n exitIntent ||\n inactivity !== undefined;\n if (!hasTriggers) return;\n if (isActive) return;\n if (hasInteracted) return;\n if (isDismissed(sessionKey)) return;\n if (!matchesUrlPatterns(patterns)) return;\n if (!meetsMinimumWidth(minimumWidth)) return;\n\n const timers: NodeJS.Timeout[] = [];\n const listeners: Array<{\n target: EventTarget;\n event: string;\n handler: EventListener;\n options?: AddEventListenerOptions;\n }> = [];\n\n const addListener = (\n target: EventTarget,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions\n ) => {\n target.addEventListener(event, handler, options);\n listeners.push({ target, event, handler, options });\n };\n\n // Delay trigger\n if (typeof delay === \"number\" && delay > 0) {\n const timer = setTimeout(() => {\n checkAndOpen(\"delay\");\n }, delay);\n timers.push(timer);\n }\n\n // Scroll trigger (throttled with requestAnimationFrame for performance)\n if (typeof scrollPercent === \"number\") {\n const targetPercent = scrollPercent;\n let scrollTicking = false;\n\n const checkScrollPercent = () => {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const docHeight = document.documentElement.scrollHeight;\n const windowHeight = window.innerHeight;\n const scrollableHeight = docHeight - windowHeight;\n\n if (scrollableHeight <= 0) return;\n\n const currentPercent = (scrollTop / scrollableHeight) * 100;\n if (currentPercent >= targetPercent) {\n checkAndOpen(\"scrollPercent\");\n }\n scrollTicking = false;\n };\n\n const handleScroll = () => {\n if (!scrollTicking) {\n scrollTicking = true;\n // Use requestAnimationFrame for throttling if available, otherwise execute directly\n if (typeof requestAnimationFrame === \"function\") {\n requestAnimationFrame(checkScrollPercent);\n } else {\n checkScrollPercent();\n }\n }\n };\n\n addListener(window, \"scroll\", handleScroll, { passive: true });\n // Check immediately in case already scrolled\n checkScrollPercent();\n }\n\n // Exit intent trigger (skip on touch devices)\n if (exitIntent && !isTouchDevice()) {\n const threshold = exitIntentThreshold ?? DEFAULT_EXIT_INTENT_THRESHOLD;\n\n const handleMouseOut = (e: Event) => {\n const mouseEvent = e as MouseEvent;\n // Only trigger when mouse leaves through the top\n if (mouseEvent.clientY <= threshold) {\n checkAndOpen(\"exitIntent\");\n }\n };\n\n addListener(document, \"mouseout\", handleMouseOut);\n }\n\n // Inactivity trigger (uses separate ref to avoid array manipulation issues)\n if (typeof inactivity === \"number\" && inactivity > 0) {\n const resetInactivityTimer = () => {\n if (inactivityTimerRef.current) {\n clearTimeout(inactivityTimerRef.current);\n }\n inactivityTimerRef.current = setTimeout(() => {\n checkAndOpen(\"inactivity\");\n }, inactivity);\n };\n\n // Start the timer\n resetInactivityTimer();\n\n // Reset on user activity (passive listeners for better performance)\n const activityEvents = [\"mousemove\", \"keydown\", \"scroll\", \"click\", \"touchstart\"];\n activityEvents.forEach((event) => {\n addListener(document, event, resetInactivityTimer, { passive: true });\n });\n }\n\n // Cleanup\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n if (inactivityTimerRef.current) {\n clearTimeout(inactivityTimerRef.current);\n inactivityTimerRef.current = null;\n }\n listeners.forEach(({ target, event, handler, options }) => {\n target.removeEventListener(event, handler, options);\n });\n };\n }, [\n // Use primitive values as dependencies to avoid re-running on object reference changes\n delay,\n scrollPercent,\n exitIntent,\n exitIntentThreshold,\n inactivity,\n patternsKey, // Serialized patterns for stable comparison\n minimumWidth,\n isActive,\n hasInteracted,\n sessionKey,\n checkAndOpen,\n ]);\n}\n","/*! Copyright (c) 2026, XAPPmedia */\nimport { useEffect } from \"react\";\n\n/**\n * Body attribute a host page sets to declare \"a form widget already *is* this page\".\n *\n * The standalone contact/booking page (`@xapp/contact-app`, serving contact.xapp.ai,\n * book.xapp.ai and sche.dule.pro) renders a docked form as its whole content, then injects\n * the chat widget on top when the URL carries `?chatWidgetKey=`. That widget arrives with\n * the App's Studio-configured ActionBar, which offers a Contact button and a Book button\n * into the very form already filling the screen.\n *\n * The page has to say so, because nothing the widget can observe would tell it. A docked\n * form in the DOM is not the same claim - plenty of pages embed one *and* want a separate\n * one from the bar.\n *\n * The reader is `@xapp/chat-widget`'s `useIsFormPage`, and its stylesheet also keys the\n * form-widget side button off this. Those packages ship separately, so this string is the\n * contract between them - the same arrangement `[data-xapp-form-side-button]` already uses.\n * Do not rename it on one side only. XappMedia/chat-widget#1626.\n */\nexport const FORM_PAGE_ATTRIBUTE = \"data-xapp-form-page\";\n\n/**\n * Companion reference count, so two markers on one page do not clear each other on the way\n * out. Mirrors the `data-xapp-action-bar-count` the chat widget keeps for the same reason.\n */\nexport const FORM_PAGE_COUNT_ATTRIBUTE = \"data-xapp-form-page-count\";\n\nfunction readCount(): number {\n const raw = parseInt(document.body.getAttribute(FORM_PAGE_COUNT_ATTRIBUTE) || \"0\", 10);\n return Number.isNaN(raw) ? 0 : raw;\n}\n\n/**\n * Declares this page to be a form page, and returns the release for it.\n *\n * Imperative form of {@link useFormPageMarker}, for pages that are not React.\n */\nexport function markFormPage(): () => void {\n if (typeof document === \"undefined\" || !document.body) {\n return () => undefined;\n }\n\n document.body.setAttribute(FORM_PAGE_COUNT_ATTRIBUTE, String(readCount() + 1));\n document.body.setAttribute(FORM_PAGE_ATTRIBUTE, \"true\");\n\n let released = false;\n return () => {\n // Idempotent: a double release must not drop the count below what other markers hold.\n if (released) {\n return;\n }\n released = true;\n\n const remaining = Math.max(0, readCount() - 1);\n if (remaining === 0) {\n document.body.removeAttribute(FORM_PAGE_ATTRIBUTE);\n document.body.removeAttribute(FORM_PAGE_COUNT_ATTRIBUTE);\n } else {\n document.body.setAttribute(FORM_PAGE_COUNT_ATTRIBUTE, String(remaining));\n }\n };\n}\n\n/**\n * Declares this page to be a form page for as long as the component is mounted.\n *\n * @param enabled pass false to render without making the claim\n */\nexport function useFormPageMarker(enabled = true): void {\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n return markFormPage();\n }, [enabled]);\n}\n","/**\n * The div the widget renders into.\n *\n * App.tsx looks this up first and only appends its own if the host page did not already\n * provide one -- which is what makes embedding possible at all.\n */\nexport const APP_ELEMENT_ID = \"xapp-form-widget\";\n\n/**\n * Class the host page puts on its own `#xapp-form-widget` div to opt into inline rendering.\n *\n * ```html\n * <div id=\"xapp-form-widget\" class=\"embedded\" style=\"width: 400px; height: 600px;\"></div>\n * ```\n */\nexport const EMBEDDED_CLASS = \"embedded\";\n\n/**\n * Namespaced alias for {@link EMBEDDED_CLASS}.\n *\n * `embedded` is short enough that a host page's own CSS framework may already style it;\n * this gives those customers a class that cannot collide.\n */\nexport const XAPP_EMBEDDED_CLASS = \"xapp-embedded\";\n\n/**\n * Is the widget rendering inside a container the host page laid out and sized itself?\n *\n * Embedded, the customer's div is the frame: the widget must fill it rather than open a\n * fixed, full-viewport modal over the page.\n *\n * @param element - the container to inspect; defaults to looking up {@link APP_ELEMENT_ID}.\n */\nexport function isEmbedded(element?: Element | null): boolean {\n const host =\n element ??\n (typeof document !== \"undefined\" ? document.getElementById(APP_ELEMENT_ID) : null);\n\n if (!host) {\n return false;\n }\n\n // classList, not className.includes -- a customer class of `not-embedded-at-all` must\n // not opt them in.\n return host.classList.contains(EMBEDDED_CLASS) || host.classList.contains(XAPP_EMBEDDED_CLASS);\n}\n","/**\n * Remembers the last click on the page between the bundle running and the form mounting.\n *\n * The form mounts on window load, and only then knows its triggerSelector, so a visitor who\n * clicks the customer's \"Schedule\" button in that gap would otherwise get nothing and think the\n * button is dead. Form asks for that click on mount and opens if it matched.\n */\n\n// Long enough for a slow page's load event, short enough that a click the visitor has\n// forgotten about does not pop the form open later.\nexport const EARLY_CLICK_MAX_AGE_MS = 10000;\n\nlet lastClick: { readonly target: Element; readonly at: number } | undefined;\n\nlet recording = false;\n\nconst record = (event: MouseEvent) => {\n if (event.target instanceof Element) {\n lastClick = { target: event.target, at: Date.now() };\n }\n};\n\nexport function startRecordingEarlyClicks(): void {\n if (recording) {\n return;\n }\n recording = true;\n // Capture phase, so a host page handler that stops propagation cannot hide the click.\n document.addEventListener(\"click\", record, true);\n}\n\n/**\n * Stops recording and returns the last recorded click target, if it is recent enough.\n */\nexport function takeEarlyClick(): Element | undefined {\n document.removeEventListener(\"click\", record, true);\n recording = false;\n\n const click = lastClick;\n lastClick = undefined;\n\n if (!click || Date.now() - click.at > EARLY_CLICK_MAX_AGE_MS) {\n return undefined;\n }\n return click.target;\n}\n","import React, { FC, useCallback, useEffect, useMemo, useState } from \"react\";\nimport { FormWidgetTheme } from \"@xapp/stentor-form-widget-channel\";\n\nimport { FormWidgetConfig } from \"../../config\";\nimport { log, err } from \"../../utils\";\nimport { SearchStoreProvider, useSearchDispatch, useSearchState } from \"../../store\";\nimport { ModalDialog } from \"../ModalDialog\";\nimport { FormWidget } from \"../FormWidget\";\nimport { WidgetStylesheet } from \"../WidgetStylesheet\";\nimport { classNames } from \"../../constants/variables\";\nimport SideButton from \"../SideButton/SideButton\";\nimport { useAutoOpenTriggers, hasAutoOpenTriggers, DEFAULT_SESSION_KEY } from \"../../hooks\";\nimport { isEmbedded } from \"../../utils/isEmbedded\";\nimport { takeEarlyClick } from \"../../utils/earlyClicks\";\n\nimport { StentorApi } from \"../../api\";\n\nimport styles from \"./Form.module.scss\";\n\nexport interface FormProps {\n readonly config: FormWidgetConfig;\n readonly theme?: FormWidgetTheme;\n /**\n * Optional elements that will act as the button to enable the modal search.\n */\n readonly button?: JSX.Element | string;\n readonly buttonElementLookup?: () => Promise<HTMLElement>;\n}\n\n/**\n * FormContainer is the main entry point for the Form widget. It provides the context for the\n * form and handles the button click events.\n * It is a wrapper around the Form component.\n */\nexport const FormContainer: FC<FormProps> = (props) => {\n return (\n <SearchStoreProvider>\n <Form\n config={props.config}\n theme={props.theme}\n button={props.button}\n buttonElementLookup={props.buttonElementLookup}\n />\n </SearchStoreProvider>\n );\n};\n\n/**\n * Form is the main component for the Form widget. It provides the context for the\n * form and handles the button click events.\n */\n/**\n * Options that can be passed when programmatically opening the form\n */\nexport interface OpenFormOptions {\n /**\n * Label of a chip to auto-select after the form loads.\n * If the first step of the form contains chips, the form will\n * automatically click the chip matching this label.\n */\n preselectChipLabel?: string;\n}\n\nexport const Form: FC<FormProps> = (props) => {\n const { config, theme } = props;\n\n const dispatch = useSearchDispatch();\n\n const { active, minimized } = useSearchState();\n\n // Store preselectChipLabel when form is opened programmatically\n const [preselectChipLabel, setPreselectChipLabel] = useState<string | undefined>();\n\n // Track if user has interacted with the form (for auto-open triggers)\n const [hasInteracted, setHasInteracted] = useState(false);\n\n // Track if the form was opened by an auto-trigger (vs manually)\n const [openedByTrigger, setOpenedByTrigger] = useState(false);\n\n // The host page opts into inline rendering by pre-creating `#xapp-form-widget` with the\n // `embedded` class and sizing it itself; App.tsx's renderWidget then renders into that\n // div rather than appending a floating one.\n //\n // Read once at mount, not per render: renderWidget guarantees the element exists before\n // React mounts into it, so there is nothing to wait for, and re-querying the document on\n // every render would do it on every keystroke. It also pins the layout for the session --\n // a host page whose CSS framework or A/B tool churns classes cannot flip the widget\n // between an inline form and a full-screen modal mid-conversation.\n const [embedded] = useState(isEmbedded);\n\n // `autoOpen.enabled` with no behavior-based triggers configured means \"open\n // immediately on load\" (docked, no close button). If triggers ARE configured,\n // `enabled` only turns the feature on -- the widget must wait for a trigger\n // to fire (which sets `active` via handleAutoOpen) rather than bypassing it.\n const immediateAutoOpen = !!config.autoOpen?.enabled && !hasAutoOpenTriggers(config.autoOpen);\n\n // Open-only, never a toggle: a host page can wire its own buttons to our side button while\n // Studio also binds them via triggerSelector (squeaksservices.com did both), and a <button>\n // gets focus and click from one mouse press. Toggles from any two of those cancel out.\n const openModal = useCallback(\n (options?: OpenFormOptions) => {\n // Store the preselect label if provided\n if (options?.preselectChipLabel) {\n setPreselectChipLabel(options.preselectChipLabel);\n }\n dispatch({\n type: \"open-modal-state\",\n });\n },\n [dispatch]\n );\n\n // Event handler for DOM events (onclick, onfocus)\n const handleFocus = useCallback(() => {\n openModal();\n }, [openModal]);\n\n // API function that accepts options (for window.xafwControl.openForm)\n const openFormWithOptions = useCallback(\n (options?: OpenFormOptions) => {\n openModal(options);\n },\n [openModal]\n );\n\n const formStatus = useCallback(() => {\n return { active, minimized };\n }, [active, minimized]);\n\n const api = useMemo(() => {\n return StentorApi.getApi({\n key: config.api.key,\n url: config.api.url,\n // Must match the config FormWidget passes below: getApi caches per url+key+intentId, so\n // this and FormWidget's call share one instance only if their intentId agrees. Form also\n // sends FORM_CLOSE from here, which needs the right intentId for overrideKey.\n intentId: config.intentId,\n // Carried through so the preview guarantee lives in one place.\n demoMode: config.api.demoMode,\n // prefetchQuery: config.autoGreeting\n });\n }, [config]);\n\n const handleClose = useCallback(() => {\n // Clear preselectChipLabel when form closes\n setPreselectChipLabel(undefined);\n // Mark as interacted to prevent auto-open triggers from firing again\n setHasInteracted(true);\n // Only persist dismissal if the form was opened by an auto-trigger\n // This prevents manual opens from blocking future auto-triggers\n if (openedByTrigger) {\n try {\n const sessionKey = config.autoOpen?.sessionKey || DEFAULT_SESSION_KEY;\n sessionStorage.setItem(sessionKey, \"true\");\n } catch {\n // Private browsing or sessionStorage not available - ignore\n }\n setOpenedByTrigger(false);\n }\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: false,\n sendRequest: false,\n });\n\n api.channelActionRequest({ data: { result: {}, step: \"\", form: \"\" } }, \"FORM_CLOSE\").then(\n (response) => {\n log(`ACTION Request (FORM_CLOSE). Data: Response: ${JSON.stringify(response)}`);\n }\n );\n }, [api, config.autoOpen?.sessionKey, dispatch, openedByTrigger]);\n\n // Callback for auto-open triggers\n const handleAutoOpen = useCallback(() => {\n setOpenedByTrigger(true);\n dispatch({\n type: \"set-modal-state\",\n active: true,\n minimized: false,\n sendRequest: true,\n });\n }, [dispatch]);\n\n // Set up auto-open triggers (delay, scroll, exit intent, inactivity)\n useAutoOpenTriggers({\n config: config.autoOpen,\n isActive: active,\n onOpen: handleAutoOpen,\n hasInteracted,\n });\n\n // This sets up the button\n useEffect(() => {\n const elements = document.getElementsByClassName(\n classNames.XAPP_FORM_BUTTON\n ) as HTMLCollectionOf<HTMLElement>;\n\n // we found the button by class\n if (elements.length) {\n log(`Assigning ${elements.length} button(s) by class: ${classNames.XAPP_FORM_BUTTON}`);\n\n Array.from(elements).forEach((element) => {\n element.onclick = handleFocus;\n element.onfocus = handleFocus;\n });\n } else {\n // we didn't find the button by class, let's try by id\n const el = document.getElementById(classNames.XAPP_FORM_BUTTON);\n if (el) {\n log(`Assigning one button by id: ${classNames.XAPP_FORM_BUTTON})}`);\n el.onclick = handleFocus;\n el.onfocus = handleFocus;\n } else {\n log(`Cannot assign buttons by class or id: ${classNames.XAPP_FORM_BUTTON})}`);\n }\n }\n\n window.xafwControl = { openForm: openFormWithOptions, formStatus };\n }, [formStatus, handleFocus, openFormWithOptions]);\n\n // Opens the form from existing elements on the customer's site matched by\n // config.triggerSelector (e.g. a dead CTA left over from a prior integration), so the widget\n // can be installed without the customer editing anything. Additive to (never replaces) the\n // xapp-form-button binding above.\n //\n // One capture-phase listener on the document rather than one per element: it covers\n // elements the page adds later, clicks on an element's children, and host handlers that\n // stop propagation, with nothing to watch or time out.\n useEffect(() => {\n const triggerSelector = config.triggerSelector;\n // Taken whether or not a selector is configured, which also stops the recorder.\n const earlyClick = takeEarlyClick();\n if (!triggerSelector) {\n return undefined;\n }\n\n try {\n document.querySelector(triggerSelector);\n } catch (e) {\n // An invalid selector can never become valid -- log once rather than on every click.\n err(`Invalid triggerSelector \"${triggerSelector}\": ${e}`);\n return undefined;\n }\n\n if (earlyClick?.closest(triggerSelector)) {\n log(`Opening for a triggerSelector \"${triggerSelector}\" click made before the form loaded`);\n handleFocus();\n }\n\n const onClick = (event: MouseEvent) => {\n const target = event.target instanceof Element ? event.target.closest(triggerSelector) : null;\n if (!target) {\n return;\n }\n // Only suppress navigation for a literal dead link (the common leftover-CTA\n // case) -- never stopPropagation, never overwrite an existing listener/onclick.\n if (\n target instanceof HTMLAnchorElement &&\n (target.getAttribute(\"href\") === \"#\" || target.getAttribute(\"href\") === \"\")\n ) {\n event.preventDefault();\n }\n handleFocus();\n };\n\n document.addEventListener(\"click\", onClick, true);\n\n return () => {\n document.removeEventListener(\"click\", onClick, true);\n };\n }, [config.triggerSelector, handleFocus]);\n\n let button: JSX.Element;\n\n // if the passed in a button, use it\n if (props.button) {\n if (typeof props.button === \"object\") {\n // If they provided a button, we add the onClick\n button = (\n <props.button.type\n {...props.button.props}\n onClick={handleFocus}\n onFocus={handleFocus}\n />\n );\n } else {\n // We are using an ID for the button, just put in a placeholder\n button = <></>;\n }\n } else {\n // no button prop provided so use default search container\n button = <></>;\n }\n\n return (\n <div className={styles.xapp_form}>\n <WidgetStylesheet theme={theme} />\n\n {/*\n Hidden when embedded: the side button is a `position: fixed` page-edge tab\n that opens the floating modal, so it would both escape the customer's\n container and offer a second way into a form already on the page.\n */}\n {config.sideButtonLabel && !immediateAutoOpen && !embedded && (\n <SideButton\n onClick={handleFocus}\n label={config.sideButtonLabel}\n position={theme?.sideButton?.position}\n hidden={config.hideSideButton}\n />\n )}\n\n {button}\n\n {(active || immediateAutoOpen) && (\n <ModalDialog\n disableBackdrop={immediateAutoOpen}\n embedded={embedded}\n onClose={handleClose}>\n <FormWidget\n docked={immediateAutoOpen}\n embedded={embedded}\n openedByTrigger={openedByTrigger}\n config={config}\n preselectChipLabel={preselectChipLabel}\n onPreselectChipUsed={() => setPreselectChipLabel(undefined)}\n />\n </ModalDialog>\n )}\n </div>\n );\n};\n","import { SearchDispatch } from \"./SearchDispatch\";\nimport { useSearchStore } from \"./useSearchStore\";\n\nexport function useSearchDispatch(): SearchDispatch {\n return useSearchStore()[1];\n}\n","\n\nexport function getBasePathFromWidgetSource(): { path: string, key?: string } {\n const xappScriptNode = document?.getElementById(\"xapp-form-js\") as HTMLScriptElement | undefined;\n const path = getBasePath(xappScriptNode?.src);\n return path;\n}\n\n// https://dev-widget.xapp.media/xapp-form-widget.js?key=f3af5f1f-cfc1-4ca7-a1e9-a411288d5190\n\nexport function getBasePath(path?: string): { path: string, key?: string } {\n if (!path) {\n return { path: \"\" };\n }\n const lastPathSep = path.lastIndexOf(\"/\");\n let result = \"\";\n if (lastPathSep >= 0) {\n result = path.substr(0, lastPathSep);\n }\n\n const url = new URL(path);\n const params = new URLSearchParams(url.search);\n const key = params.get(\"key\") || \"\";\n\n return { path: result, key };\n}","import { FormWidgetEnv, FormWidgetTheme } from \"@xapp/stentor-form-widget-channel\";\n\nimport { FormWidgetConfig, getBasePathFromWidgetSource } from \"../config\";\n\n/**\n * Parses the widget environment to extract the configuration and theme.\n *\n * @param env\n * @returns An array containing the configuration and theme, config in index 0 and theme in index 1.\n */\nexport function parseWidgetEnv(env: FormWidgetEnv): [FormWidgetConfig, FormWidgetTheme] {\n // Use accountKey if provided, otherwise try to get key from script tag URL\n const key = env.connection?.accountKey || getBasePathFromWidgetSource().key || \"\";\n\n const config: FormWidgetConfig = {\n api: {\n url: env.connection?.serverUrl || \"\",\n key,\n },\n\n suggestionsUrl: env.autocompleteSuggestionsUrl,\n autoGreeting: env.autoGreeting || \"contact us\",\n intentId: env.intentId,\n sideButtonLabel: env.sideButtonLabel,\n hideSideButton: env.hideSideButton,\n googleMapsApiKey: env.googleMapsApiKey,\n mapsBaseUrl: env.mapsBaseUrl,\n autoOpen: env.autoOpen,\n disabled: env.disabled,\n trustedForm: env.trustedForm,\n triggerSelector: env.triggerSelector,\n };\n\n const theme = env.theme;\n\n return [config, theme];\n}\n","import {\n FormWidgetTheme,\n PartnerFormFraming,\n PartnerFormStyle,\n} from \"@xapp/stentor-form-widget-channel\";\n\n/**\n * The reserved preset name that forces the partner style off for a single form,\n * whatever the partner record says. A permanent per-form exception.\n */\nexport const STYLE_PRESET_NONE = \"none\";\n\nexport interface FormStyleContext {\n /**\n * True only for the stand-alone booking page. A form embedded on the customer's\n * own website is the customer's own chrome -- the preset must never apply there,\n * or every embedded form belonging to a styled partner would silently change\n * appearance.\n */\n readonly standalone?: boolean;\n /**\n * The form's own tri-state preset -- see FormWidgetEnv.stylePreset.\n */\n readonly stylePreset?: string;\n /**\n * Canonical code of the partner the form belongs to.\n */\n readonly partnerCode?: string;\n /**\n * The customer's own theme, which the preset merges over.\n */\n readonly customerTheme?: FormWidgetTheme;\n /**\n * Looks a named style bundle up. API-served, with a code fallback.\n */\n readonly getPresetStyle?: (preset: string) => PartnerFormStyle | undefined;\n}\n\nexport interface ResolvedFormStyle {\n /**\n * The preset that applied, or undefined when the form is left alone.\n */\n readonly preset?: string;\n /**\n * The theme to hand the widget: the customer's, with the preset merged over it.\n */\n readonly theme?: FormWidgetTheme;\n /**\n * The partner chrome to draw around the form, if the preset defines any.\n */\n readonly framing?: PartnerFormFraming;\n}\n\n/**\n * Works out which named style bundle applies to a form, or undefined for none.\n *\n * `stylePreset` is tri-state and overrides the partner record either way:\n * absent inherits `formStyle.enabled`, a name forces on, \"none\" forces off.\n */\nexport function resolveStylePresetName(context: FormStyleContext): string | undefined {\n const { standalone, stylePreset, partnerCode, getPresetStyle } = context;\n\n if (!standalone) {\n return undefined;\n }\n\n if (stylePreset === STYLE_PRESET_NONE) {\n return undefined;\n }\n\n if (stylePreset) {\n return stylePreset;\n }\n\n if (!partnerCode) {\n return undefined;\n }\n\n return getPresetStyle?.(partnerCode)?.enabled ? partnerCode : undefined;\n}\n\n/**\n * Resolves the preset and applies it, returning the theme the widget should use and\n * the framing it should draw.\n */\nexport function resolveFormStyle(context: FormStyleContext): ResolvedFormStyle {\n const { customerTheme, getPresetStyle } = context;\n\n const preset = resolveStylePresetName(context);\n const style = preset ? getPresetStyle?.(preset) : undefined;\n\n if (!style) {\n return { theme: customerTheme };\n }\n\n return {\n preset,\n theme: mergeFormWidgetTheme(customerTheme, style.theme),\n framing: style.framing,\n };\n}\n\n/**\n * Merges a preset theme *over* a customer theme: the preset wins where it defines a\n * value, and the customer's values survive everywhere the preset is silent. Nested\n * groups (font, text, card, standAlone, ...) merge rather than replace, so a preset\n * that only sets `font.fontFamily` keeps the customer's `font.link`.\n */\nexport function mergeFormWidgetTheme(\n base?: FormWidgetTheme,\n override?: FormWidgetTheme\n): FormWidgetTheme | undefined {\n if (!override) {\n return base;\n }\n\n if (!base) {\n return override;\n }\n\n return deepMerge(\n base as unknown as PlainObject,\n override as unknown as PlainObject\n ) as FormWidgetTheme;\n}\n\ntype PlainObject = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction deepMerge(base: PlainObject, override: PlainObject): PlainObject {\n const merged: PlainObject = { ...base };\n\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined) {\n continue;\n }\n\n const existing = merged[key];\n merged[key] =\n isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;\n }\n\n return merged;\n}\n","import { PartnerFormStyle } from \"@xapp/stentor-form-widget-channel\";\n\n/**\n * CostGuide's approved form look, as a named style bundle.\n *\n * ONE definition, exported so every consumer reads the same values: the code\n * fallback in contact-app's partner registry, and the Storybook story that shows\n * the look. Duplicating it drifts -- the story and the registry had already\n * diverged on the button colours, which is how a CostGuide-preset form ended up\n * rendering a stock magenta Continue button inside a teal frame.\n *\n * Once `public.partnerBranding.formStyle` ships (XappMedia/stentor-api#5753) the\n * API-served bundle wins and this is only reached when that fetch fails.\n *\n * Colour notes, all from the approved design:\n * - #1aacbe is the frame border, the buttons and the selected chip/date state.\n * - #22a2b4 is the tab -- deliberately a DIFFERENT teal from the border.\n * - #eef8fa is the card interior the framed step sits on.\n */\nexport const COST_GUIDE_FORM_STYLE: PartnerFormStyle = {\n enabled: true,\n theme: {\n // No visible container. The widget root paints a border in this colour, and with the\n // frame and tab gone it was the last box left around a form that should sit flat on the\n // page -- their own form has no outer border at all. Transparent rather than removing\n // the rule, so the layout keeps the same box metrics.\n borderColor: \"transparent\",\n // The approved design's inputs and buttons are slightly squarer than stock.\n // The frame's own card is square regardless of this -- see FormFrame.\n borderRadius: \"8px\",\n // White, not the pale teal card interior. That tint existed to separate the framed card\n // from the page behind it; with no frame it just makes the form look like a panel.\n backgroundColor: \"#ffffff\",\n // The step header was a teal bar with white text, which read as a tab even once the real\n // tab was gone. On white with dark text it reads as a heading, which is what it is.\n headerBackgroundColor: \"#ffffff\",\n headerTextColor: \"#1c3f47\",\n // CostGuide's own advance button is orange, not teal -- `.btn-orange {background:#fb9b26}`\n // in their main.css, which `.btn-next` uses. Teal was our reading of their older design.\n primaryButtonColor: \"#fb9b26\",\n primaryButtonTextColor: \"#ffffff\",\n // BOTH buttons, because a step that sets `nextLabel` routes to the SECONDARY one -- and\n // every step of the CostGuide form sets one (\"Next: Contact Info\", \"Next: book your\n // estimate\"). Setting only the primary leaves the button the visitor actually presses\n // its stock magenta.\n secondaryButtonColor: \"#fb9b26\",\n secondaryButtonTextColor: \"#ffffff\",\n text: {\n color: \"#1c3f47\",\n // The fill was never claimed here, so it fell through to the customer's own theme --\n // Erie ships `rgba(0, 0, 0, 0.06)`, a grey wash that reads as disabled next to\n // CostGuide's white fields. A pale tint of their own palette instead. The hover and\n // focus shades derive from this automatically (`darken(backgroundColor, 3)`).\n //\n // Not white: without a border on the input a white field is invisible on the white\n // form. Their fields are white WITH a 1px border, which we cannot match until the\n // input border is themable -- `border: 0 !important` is hardcoded in\n // FormFieldTextInput.module.scss.\n backgroundColor: \"#ffffff\",\n // Outlined fields, now that the border is themable. Their own:\n // `.main-form input:focus {border:2px solid #92dae1}`, and the resting border is the\n // same family a shade lighter. White fill is safe once there is a border to read.\n borderColor: \"#cfe3e7\",\n borderWidth: \"1px\",\n borderColorFocus: \"#92dae1\",\n },\n chips: {\n // Both states. Only the selected pair was set, so an UNSELECTED chip fell through to\n // the customer's own theme -- on book.xapp.ai that rendered American Dream's maroon\n // pills inside an otherwise entirely teal form. A chip spends most of its life\n // unselected, so it was the resting state that looked wrong.\n //\n // Same class as the stock magenta Continue button this file's header records: a\n // themable surface the preset does not claim is a surface the customer keeps.\n backgroundColor: \"#d6eef2\",\n color: \"#1c3f47\",\n backgroundColorSelected: \"#1aacbe\",\n colorSelected: \"#ffffff\",\n },\n date: {\n backgroundColorSelected: \"#1aacbe\",\n },\n // Their advance button is chunky: 20px bold on a 10px radius with a heavy drop shadow\n // (`.btn-next {padding:17px 25px; font-size:20px; font-weight:700; border-radius:10px;\n // box-shadow:0 4px 5px 4px rgba(0,0,0,.15)}`). Ours was a stock MUI button wearing\n // their orange -- right colour, half the presence.\n button: {\n fontSize: \"20px\",\n fontWeight: \"700\",\n padding: \"17px 25px\",\n borderRadius: \"10px\",\n boxShadow: \"0 4px 5px 4px rgba(0, 0, 0, 0.15)\",\n },\n\n // Back and submit on one row, as theirs are -- the circle on the left, the button beside\n // it -- rather than submit centred above with back stranded underneath.\n finalButtonPlacement: \"inline\",\n\n // Their step heading: centred, 24px, dark teal (`.main-form .ms-title {font-size:24px;\n // color:#174146}`). Ours was left-aligned body text, which read as a label.\n stepTitle: {\n align: \"center\",\n fontSize: \"24px\",\n fontWeight: \"700\",\n color: \"#174146\",\n },\n\n // An icon-only circle with an arrow, which is what their back control is --\n // `.btn-back svg {fill:#a0cdd3}`, hover `#174146` on both the ring and the arrow.\n backButtonVariant: \"icon\",\n backButton: {\n color: \"#a0cdd3\",\n borderColor: \"#a0cdd3\",\n colorHover: \"#174146\",\n // 1px read as hairline next to a 20px bold button beside it.\n borderWidth: \"2px\",\n iconStroke: \"0.8px\",\n },\n\n font: {\n // Poppins, which is what their own page loads: `family=Poppins:300,400,700` on\n // match.costguide.com. Montserrat came from their embed loader, which still requests\n // it -- but the page the visitor compares us against is set in Poppins.\n fontFamily: \"Poppins, Arial, Verdana, sans-serif\",\n link: \"https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;700&display=swap\",\n },\n standAlone: {\n backgroundColor: \"rgb(243, 248, 251)\",\n },\n externalWidget: {\n // Their booking embed is tall; without this the page jumps as it mounts.\n minHeight: \"600px\",\n },\n },\n // No framing. There was a \"BOOK YOUR ESTIMATE\" tab and a bordered card around every step,\n // matching CostGuide's design as it stood when this preset was written. Their own form no\n // longer has either (match.costguide.com, checked 2026-09-20): it is a plain card with the\n // fields on it. Ours read as a box inside a box -- the widget's own rounded container, then\n // the tab, then a second squared border inside that.\n //\n // FormDisplay renders `framing ? <FormFrame> : stepDisplay`, so leaving this off is what\n // removes the tab AND the inner card; there is no separate switch for either.\n};\n"],"names":["jsxRuntime","require$$0","react","require$$1","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","__generator","body","f","y","t","_","label","sent","trys","ops","g","Object","create","Iterator","prototype","verb","Symbol","iterator","this","n","v","op","TypeError","call","pop","length","push","__spreadArray","to","from","pack","ar","i","l","Array","slice","concat","SuppressedError","reduce","prev","cur","index","UTM_PARAMETERS","CLICK_ID_PARAMETERS","ATTRIBUTION_PARAMETERS","toolResultToValue","text","content","filter","part","type","map","join","isError","ok","message","JSON","parse","_a","HomeownerMcpClient","mcpUrl","fetchImpl","nextId","fetch","undefined","callTool","name","args","response","Error","method","headers","Accept","stringify","jsonrpc","id","params","arguments","status","json","error","code","INTERNAL_TRAFFIC_VALUE","COUNT_ATTRIBUTE$1","RESTORE_ATTRIBUTE","PINNED_PROPERTIES","readCount$1","count","Number","getAttribute","isFinite","lockBodyScroll","document","window","restorePoint","inlineStyles","styles","property","style","getPropertyValue","scrollY","pageYOffset","captureRestorePoint","setAttribute","position","top","left","right","width","overflow","String","released","remaining","removeAttribute","serialized","parsed","takeRestorePoint","forEach","setProperty","removeProperty","scrollTo","HEIGHT_PROPERTY","OFFSET_TOP_PROPERTY","KEYBOARD_INSET_PROPERTY","COUNT_ATTRIBUTE","readCount","root","publish","viewport","visualViewport","height","offsetTop","layoutHeight","innerHeight","rawInset","Math","max","inset","round","trackVisualViewport","documentElement","frame","onChange","requestAnimationFrame","addEventListener","removeEventListener","cancelAnimationFrame","clear","readInset","getComputedStyle","parseFloat","scrollIntoViewIfPossible","element","scrollIntoView","block","behavior","uuid","d","Date","getTime","replace","c","r","random","floor","toString","VISITOR_ID_STORAGE_KEY","VISIT_STORAGE_KEY","ID","fallback","w","__xappVisitIdentity","read","key","localStorage","getItem","write","setItem","asId","test","visitorId","stored","page","IconButton_1","props","Icon","icon","jsx","tabIndex","className","onClick","children","MessageBubble_1","SuggestionsGroupHeading_1","addTestLeadAttribute_1","attributes","sessionStorage","isTestLeadSession","readInternalTrafficMark_1","useBodyScrollLock_1","enabled","useEffect","useScrollFocusedIntoView_1","lastInset","onFocusIn","event","target","onViewportChange","opened","activeElement","useVisualViewportProperties_1","uuid_1","visitIdentity_1","now","current","raw","visit","at","parseVisit","visitId","visitorId_1","DEFAULT_CONFIG","extractUtmParameters","extractClickIds","customParameterPrefix","persistToLocalStorage","persistenceDays","preferUrlParameters","storageKeyPrefix","scope","encodeURIComponent","isValidParameterValue","getStoredTrackingParameters","parameters","prefix","param","data","expires","removeItem","keys","storageKeys","startsWith","paramName","getAllTrackingParameters","url","config","location","href","finalConfig","__assign","urlParameters","urlObj","URL","console","warn","searchParams","get","extractTrackingParametersFromUrl","storedParameters","expirationTime","entries","storeTrackingParameters","getCurrentDateString","toISOString","log","_i","xaLogLevel","err","isCarousel","display","isList","isForm","RootReducer","state","action","query","responseQuery","responseIntentId","intentId","context","active","minimized","sendRequest","x","throwBadKind","DEFAULT_SEARCH_STATE","DEFAULT_SEARCH_STORE","SearchStoreContext","React","createContext","SearchStoreProvider","reducer","useReducer","initialState","_jsx","Provider","useSearchStore","useContext","useSearchState","styleInject","css","ref","insertAt","head","getElementsByTagName","createElement","firstChild","insertBefore","appendChild","styleSheet","cssText","createTextNode","ModalDialog","embedded","useBodyScrollLock","useVisualViewportProperties","useScrollFocusedIntoView","_jsxs","disableBackdrop","onClose","DROPPED_AFTER_FINAL","API_INSTANCES","Map","DEMO_READ_REQUEST_TYPES","Set","StentorApi","sessionSent","prefetchSemaphore","responseCache","defineProperty","getCachedTrackingParameters","cachedTrackingParams","ts","trackingScope","getApi","cacheKey","demoMode","apiCacheKey","existing","api","set","prefetchQuery","prefetch","launchRequest","send","rawQuery","platform","channel","intentRequest","request","channelActionRequest","_this","isFinal","final","session","hadFinal","overrideKey","catch","trackEvent","eventType","trackingUrl","getTrackingUrl","requestBody","events","mode","statusText","processed","error_1","trackEventBeacon","widgetType","keepalive","parsedUrl","origin","match","resetSession","visitSession","sessionId","userId","getCachedResponse","hit","_c","has","newSession","_b","host","toLowerCase","rwgToken","merchantId","environment","enablePreferredTime","service","urlParams","URLSearchParams","search","placeId","trackingParams","assign","addTestLeadAttribute","isNewSession","Authorization","waitTimeInMs","setTimeout","resolver","currentTime","start","fetchResponse","_d","finally","getActionLabel","title","SearchWidgetConfigContext","suggestionsUrl","isVoiceEnabled","autoGreeting","useLoading","useState","setState","mounted","useRef","useCallback","run","shift","runCounter","delta","useMemo","loading","TRUSTED_FORM_CERT_FIELD","TRUSTED_FORM_PING_FIELD","useTrustedForm","scriptUrl","isValidTrustedFormUrl","querySelector","script","async","src","onerror","certInput","pingInput","getCookie","cookie","escaped","RegExp","decodeURIComponent","LeftAngleIcon","viewBox","xmlns","stroke","fill","strokeLinecap","RightAngleIcon","SearchIcon","version","SpinnerIcon","offset","stopOpacity","stopColor","strokeWidth","attributeName","repeatCount","dur","path","focusable","CheckIcon","CheckBoxIcon","CheckBoxOutlineIcon","RadioCheckedIcon","RadioUncheckedIcon","ArrowDropDownIcon","ChevronLeftIcon","ChevronRightIcon","SearchResponseBubble","MessageBubble","firstIndex","val","patterns","res","patterns_1","pattern","indexOf","domainEnds","portEnds","pathEnds","queryEnds","parsers","rest","charAt","ellipsis","reduceLink","maxLength","parts","parsers_1","parser","newIndex","substring","getText","overflows","tryReduce","allButPathLength","available","newPathStart","Card","item","imageUrl","image","alt","accessibilityText","description","CarouselItem","Carousel","list","listRef","scrollIterate","func","container","items","getElementsByClassName","containerRect","getBoundingClientRect","length_1","itemRect","size","scrollLeft","handlePrev","prevPos","handleNext","IconButton","SearchResponseCarouselDisplay","carousel","Cards","SearchResponseListDisplay","SuggestionsGroupHeading","_Fragment","addContextPrefix","input","ignore","functionNames","fn","TEMPLATE_REGEX","replaceValues","o","values","_match","trimmedKey","trim","s","u","a","h","$","M","weekdays","split","months","ordinal","m","z","utcOffset","abs","date","year","month","clone","add","ceil","p","D","ms","Q","S","O","b","locale","$L","utc","$u","$x","$offset","$d","NaN","UTC","init","$y","getFullYear","$M","getMonth","$D","getDate","$W","getDay","$H","getHours","$m","getMinutes","$s","getSeconds","$ms","getMilliseconds","$utils","isValid","isSame","startOf","endOf","isAfter","isBefore","$g","unix","valueOf","toDate","$locale","weekStart","$set","min","daysInMonth","subtract","format","invalidDate","meridiem","monthsShort","weekdaysMin","weekdaysShort","getTimezoneOffset","diff","toJSON","toUTCString","Y","extend","$i","isDayjs","en","Ls","exports","day","hour","minute","second","timeZoneName","Intl","DateTimeFormat","hour12","timeZone","formatToParts","parseInt","tz","toLocaleString","$timezone","offsetName","guess","find","isNaN","resolvedOptions","setDefault","local","getUTCFullYear","getUTCMonth","getUTCDate","getUTCDay","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","$localOffset","isUTC","dayjs","utcPlugin","timezonePlugin","DEFAULT_SLOT_MINUTES","DEFAULT_HORIZON_DAYS","DEFAULT_DATE_FIELD_NAME","DEFAULT_DATE_TIME_FIELD_NAME","DEFAULT_TIME_ZONE_FIELD_NAME","FIXED_OFFSET","WEEKDAYS","CLOCK_TIME","clockToMinutes","clock","exec","hours","minutes","pad","minutesToClock","wrapped","toCalendarDate","TIMEZONE_NAME_STYLES","formatTimezoneLabel","timezone","TIMEZONE_NAME_STYLES_1","named","toOffsetIso","calendarDate","normalized","timeZoneOf","schedule","formatClock","hours24","formatOfferingLabel","offering","end","horizonDaysOf","horizon","horizonDays","isOffering","filterElapsed","offerings","lead","leadTimeMinutes","buffer","cutoff","zonedInstant","generateOfferings","offeringsByDate","exception","exceptions","findException","isArray","spans","weekday","weekdayOf","days","slotMinutes","duration","durationMinutes","spans_1","span","isDateSelectable","today","todayInZone","firstSelectableDate","isBusy","NO_MATCH_STEP_IDS","classifyAnchor","anchor","stepEls","querySelectorAll","hasLoading","SCRIPT_ORIGIN_ATTRIBUTE","useExternalWidget","externalWidget","options","onRendered","onNoRender","onError","onFallback","outcome","setOutcome","suppressedScheduledCount","setSuppressedScheduledCount","hasMountedRef","scheduledFiredRef","suppressedScheduledRef","outcomeSettledRef","optionsRef","provider","scriptSrc","hostname","getExternalWidgetProvider","globalConfig","successCallbackKey","successCallbackKey_1","payload","onScheduled","configGlobal","settle","nextOutcome","notify","fallbackStep","protocol","isValidScriptSrc","timeoutId","observer","getElementById","anchorId","timeoutMs","renderTimeoutMs","extensions","handleNoRender","evaluate","el","onTimeout","currentAnchor","MutationObserver","observe","childList","subtree","cacheBust","includes","clearTimeout","disconnect","FormFieldSelect","field","onFieldChange","errorMessage","selectValue","setSelectValue","radioValue","setRadioValue","onCheckboxChange","checked","prevOptions","option","onRadioChange","useId","titleId","helperId","invalid","radio","xapp_select_title_container","xapp_select_container","role","xapp_select_option","xapp_checkbox_select","xapp_checkbox_select_checked","xapp_select_input","xapp_select_icon","xapp_select_label","xapp_select_helper","VARIANT_ELEMENTS","h1","h2","h3","h4","h5","h6","subtitle1","subtitle2","body1","body2","inherit","button","caption","overline","PALETTE_COLORS","primary","secondary","warning","info","success","textPrimary","textSecondary","textDisabled","FormFieldCard","color","variant","Text","xapp_form_card","xapp_form_card_body","header","xapp_form_card_header","xapp_form_card_header_title","subheader","xapp_form_card_header_subheader","media","xapp_form_card_media","xapp_form_card_content","xapp_form_card_text","whiteSpace","textAlign","align","isSelectableItem","FormFieldChips","selectedFromProps","selected","selectedChips","setSelectedChips","flexDirection","alignContent","alignItems","_prevOptions","handleChipClick","isActionableItem","FORMAT_PROPS","PHONE","inputMode","autoComplete","EMAIL","ZIP_CODE","ADDRESS","DEFAULT_PROPS","NAME_AUTOCOMPLETE","fullname","yourname","customername","contactname","firstname","fname","givenname","lastname","lname","surname","familyname","email","emailaddress","phone","phonenumber","telephone","tel","mobile","mobilephone","cellphone","zip","zipcode","postalcode","postcode","address","streetaddress","street","city","town","province","company","companyname","organization","business","businessname","formatToInputProps","isLastField","mapped","enterKeyHint","autoCompleteFromName","FormFieldTextInput","required","setText","focused","setFocused","textareaRef","autosize","multiline","rows","useLayoutEffect","textarea","lineHeight","maxHeight","rowsMax","Infinity","scrollHeight","currentLength","isAtLimit","showCounter","inputHelpers","__rest","shrink","controlProps","xapp_text_input_control","placeholder","onFocus","onBlur","xapp_text_input_container","xapp_text_input_text","xapp_text_input_error","xapp_text_input_root","xapp_text_input_focused","xapp_text_input_multiline","htmlFor","xapp_text_input_label","xapp_text_input_asterisk","xapp_text_input_helper","xapp_text_input_counter","FormFieldDropdown","freeFormErrorMessage","freeFormId","freeFormHelperId","selectedItem","dropValue","setDropValue","freeFormValue","setFreeFormValue","freeFormInput","showFreeForm","setShowFreeForm","onFieldChangeRef","process","env","NODE_ENV","currentFreeFormFieldName","freeFormFieldName","prevSelectedItem","messageFieldName","classNames","names","Calendar","shouldDisableDate","minDate","maxDate","referenceDate","showDaysOutsideCurrentMonth","fixedWeekNumber","getDayClassName","classes","labelId","gridRef","focusOnRender","setMonth","focusedDay","setFocusedDay","valueKey","isOutOfRange","isDisabled","closestEnabled","clamped","candidate","tabbableDay","timestamp","focus","walked","monthJump","onDayKeyDown","edge","direction","scan","preventDefault","moveFocus","previousDisabled","nextDisabled","weeks","first","weeksInMonth","week","__","weeksOf","disabled","row","outside","isToday","daySelected","dayToday","onDayClick","onKeyDown","parseBusyDays","busyDays","entry","isBusyDay","dateString","dayString","some","busyDay","isMatch","str","regexPattern","escapeRegExp","isBusinessDay","availableDays","DEFAULT_BUSY_DAYS","blockWeekends","blockCurrentDay","blockNextBusinessDays","FormFieldDate","MAX_DATE","TODAY","dateTimeValue","setDateTimeValue","disabledDays","nextBusinessDay","guard","currentDayAvailableUntil","isDisabledByBusyDays","defaultBusyDays","isPast","isBeyondMaxDate","newValue","ISO_DATE","toInputDate","FormFieldDateRange","initialFrom","preselecteDates","initialTo","range","setRange","change","fromId","toId","TIMES_LABEL","TIMEZONE_NOTICE_PREFIX","offeringKey","FormFieldDateTime","preselectFirstAvailable","selectedDate","setSelectedDate","selectedKey","setSelectedKey","fieldValue","datetime","preselected","previousGroup","hasSchedule","scheduleTimezone","timezoneUsable","isUsableTimezone","notice","visitorTimezone","hostTimezone","visitorName","timezoneNotice","group","Fragment","highlight","isPlaceSuggestion","placePrediction","mapSuggestion","suggestion","structured_formatting","main_text","structuredFormat","mainText","secondary_text","secondaryText","main_text_matched_substrings","matches","startOffset","endOffset","AddressAutocompleteService","baseUrl","apiKey","getPlacePredictions","callback","components","regionCodes","includedRegionCodes","language","languageCode","lat","lng","locationBias","circle","center","latitude","longitude","radius","componentRestrictions","country","suggestions","getPlaceDetails","LocationOnIcon","FormFieldTextInputAddress","googleMapsApiKey","mapsBaseUrl","requireSelection","isFreeSolo","setAddress","setOptions","_e","open","setOpen","_f","_g","activeIndex","setActiveIndex","listboxId","optionId","listboxRef","textRef","onTextChange","autocompleteService","showGoogleAttribution","endsWith","wait","timeout","debounced","debounce","queryParams","mapsUrlQueryParams","results","visibleOptions","popupOpen","listbox","HTMLElement","scrollTop","offsetHeight","clientHeight","close","select","description_1","details","formattedAddress","activeOption","autoCapitalize","spellCheck","stopPropagation","chosen","onMouseDown","hidden","onMouseMove","fontWeight","isEmptyString","validateUSPhoneNumber","sanitizedNumber","isEmpty","obj","constructor","isFormStepExternalWidget","hasFieldValue","SCHEDULING_CHIPS_NAMES","leadFieldNamesOf","dateTimeField","dateFieldName","dateTimeFieldName","timeZoneFieldName","isGroupableFieldField","mandatoryGroup","FormStepDisplay","stepData","prefilledFields","hasNotifiedPrefill","prevFieldsRef","formStep","fields","fieldTests","mandatoryGroups","setMandatoryGroups","fieldConditions","setFieldConditions","fieldErrors","setFieldErrors","isSubmitting","setIsSubmitting","schedulingDisabled","flag","isSchedulingDisabled","rawOfferingsByDate","parseOfferingsByDate","isHiddenSchedulingField","isSchedulingField","nextStep","onNextStep","prevStep","onPrevStep","handleData","handleDataWithLabels","onDataWithLabels","getData","getDataWithLabels","currentStepIndex","totalSteps","onTrackNextStep","currentStepDataRef","isActive","externalWidgetConfigPending","onTrackHandoffRendered","onTrackHandoffNoRender","onTrackHandoffScheduled","onTrackHandoffError","onExternalWidgetFallback","submitError","hideIntro","externalWidgetConfig","externalWidgetOutcome","externalWidgetContentShown","setExternalWidgetContentShown","childElementCount","checkConditions","newConditions","context_1","safeIncludes","searchElement","objA","objB","keysA","keysB","keysA_1","shallowEqualBooleanMap","groups","groupName","hasOwnProperty","visibleStepValues","stepValues","visibleValues","chipsSelectedFromProps","condition","conditionWithThis","Function","validate","errors","corrections","valid","isFormDropdownInput","mandatory","mandatoryError","isFormDateRangeInput","isCompleteRange","isFormDateTimeInput","selection","isCompleteDateTime","isFormTextInput","validateZipCode","formattedZip","trimmed","toUpperCase","formatZipCode","validatePhoneNumber","formattedNumber","formatUSPhoneNumber","isFormChipsInput","isFormDateInput","isFormCheckInput","minRequired","maxAllowed","fieldNames","fieldError","errorMessage_1","obj1","obj2","keys1","keys2","keys1_1","attr1","attr2","fieldErrorsEqual","continueToNext","pushData","isLastStep","nextAction","pushedData","pushedLabels","clearedData","clearedLabels","name_1","augmentedData","dataWithLabels","applyTimes","fieldName","startTimes","endTimes","joinedStart","joinedEnd","ordinalSuffix","formField","valueLabels_1","startTimes_1","endTimes_1","chip","timedItem","startTime","endTime","arr","lastElement","joinWithAnd","word","number","getOrdinalSuffix","isNextDisabled","isFirst","delete","fullBleed","subtitle","warnBeforeUnloadMessage","backgroundColor","padding","marginBottom","borderRadius","border","gap","fontSize","iframe","frameBorder","allowFullScreen","stepFields","firstHiddenIndex","findIndex","fieldComponent","dropdownField","currentValue_1","freeFormError","_h","preselectFirstAvailableDate","_j","getFields","nextLabel","previousAction","previousLabel","FormFrame","framing","framed","tabLabel","introTitle","introSubtitle","introPlacement","intro","SimpleNavigationHeader","onHeaderClick","labelHeader","stepName","isShowCase","headerText","isInServiceArea","zipCodes","baseZip","supportedZip","extractZipFromAddress","before","FormDisplay","form","onActionResponse","onTrackPreviousStep","onTrackSubmit","onTrackSubmitFailure","initialStep","onTrackInitialStep","onFormNext","stepUpdate","currentStep","setCurrentStep","appliedInitialStep","stepOverrides","setStepOverrides","failedSubmitStep","setFailedSubmitStep","applyFormStepUpdate","handoffConfigSettledRef","awaitingHandoffConfig","setAwaitingHandoffConfig","externalWidgetWaitElapsed","setExternalWidgetWaitElapsed","activeStep","steps","timer","step_1","conditionWithThis_1","shouldWarnBeforeUnload","currentFormStep","warnBeforeUnload","handleBeforeUnload_1","returnValue","formData","formDataWithLabels","lastStepData","formSubmittedRef","submit","nextStepIndex","formStepItem","test_1","zip_code","currentStepDef","serverCallback","race","displays","onSubmitForm","fromStepIndex","fromStepName","step_2","test_2","submitStepIndex","safeStepIndex","stepIndex","reason","jumpToExternalWidgetFallback","activeStepHandsOff","activeStepFramed","hideLabelHeader","override","effectiveStep","staticExternalWidget","stepDisplay","onData","ResponseDisplay","SearchResponseHtml","html","dangerouslySetInnerHTML","__html","SearchResponseText","SearchResponseAudio","audio","onAudioChange","audioRef","audioElement","handleAudioEnd","handleAudioPlay","autoPlay","SearchResponseOutputSpeech","audioUrl","outputSpeech","displayText","ssml","mp3s","regex","parseAudio","isLinkoutSuggestion_1","isLinkoutSuggestion_2","isLinkoutSuggestion","Button","expand","SuggestedAction","handleClick","SuggestedActions","actions","onActionClick","xapp_search_suggested_actions","xapp_search_suggested_actions__actions","act","xapp_search_suggested_actions__item","SearchResponsePart","extraClass","modifier","xapp_search_response_part","FormResponse","noHeaderForm","SearchResponseDisplay","INTERACTION_EVENTS","EventTrackingService","formId","forVisit","trackFormOpen","metadata","buildMetadata","isOpen","watchForFirstInteraction","event_1","sendEvent","formName","trackEngaged","event_2","trigger","error_2","trackNextStep","event_3","completedStepName","error_3","trackPreviousStep","event_4","toStepName","error_4","trackStepChange","event_5","error_5","trackSubmit","event_6","finalStepName","error_6","trackSubmitFailure","event_7","error_7","trackClose","event_8","lastStepName","error_8","trackPartialData","event_9","abandonmentReason","error_9","trackHandoffRendered","event_10","error_10","trackHandoffNoRender","event_11","error_11","trackHandoffScheduled","event_12","error_12","trackHandoffError","event_13","error_13","trackLoad","loadMetadata","currentUrl","event_14","trackPartialDataBeacon","event_15","nowMs","openedAt","userAgent","navigator","internal","readInternalTrafficMark","msOnPage","firstInteractionAt","msToFirstInteraction","screenWidth","screen","screenHeight","viewportWidth","innerWidth","viewportHeight","visitIdentity","getTrackingParameters","dispose","stopWatchingForInteraction","adoptVisitFrom","previous","onInteraction_1","isTrusted","INTERACTION_EVENTS_2","INTERACTION_EVENTS_1","name_2","capture","passive","error_14","SUBMIT_RETRY_DELAYS_MS","FormWidget","FormWidgetRaw","docked","openedByTrigger","preselectChipLabel","onPreselectChipUsed","onSubmit","dispatch","setResponse","setStepUpdate","audioOn","setAudioOn","waitingOnAudioToFinish","setwaitingOnAudioToFinish","getTrustedFormData","trustedForm","eventTracker","currentStepRef","dockedRequestSent","submitEventIdRef","getSubmitEventId","formDisplayRef","formIdRef","abandonEventSentRef","formOpenSentRef","engagementSentRef","trackEngagement","firstStepName","handleCancel","handleClose","allFormData","hasData","lastStepIndex","totalStepsCompleted","partialData","closeResponse","trackingParameters","handleBeforeUnload","completionPercentage","midnightTimeoutId","sendTimeoutEvent","handleVisibilityChange","msUntilMidnight","midnight","setHours","intentResponse","formDisplay","previousTracker","engagementTrigger","dispatchOnce","wasDroppedAfterFinal","update","autoClose","autoMinimize","attempt","delays","lastError","dispatchWithRetry","handleActionClick","matchingChip","handleActionResponse","timezoneOffset","trustedFormData","extras","eventId","fbp","fbc","handleFormNext","handleAudioChange","isOn","handleTrackInitialStep","handleTrackNextStep","nextStepName","completedStepIndex","toStepIndex","handleTrackPreviousStep","handleTrackSubmit","completedData","dataWithTrustedForm","finalStepIndex","handleTrackSubmitFailure","handleTrackHandoffRendered","handleTrackHandoffNoRender","handleTrackHandoffScheduled","handleTrackHandoffError","displayContainer","WidgetStylesheet","theme","currentFontLink","font","link","fontUrl","linkId","existingLink","remove","rel","crossOrigin","loadExternalFont","entriesKey","gen","widgetTheme","withPrefix","union","single","headerBackgroundColor","headerTextColor","primaryButtonColor","primaryButtonTextColor","secondaryButtonColor","secondaryButtonTextColor","borderColor","fontFamily","getFontStyle","darken","borderWidth","borderColorFocus","getTextStyle","backButtonVariant","back","backButton","iconStroke","colorHover","getBackButtonStyle","boxShadow","getButtonStyle","getStepTitleStyle","stepTitle","finalButtonPlacement","getFinalButtonStyle","getDropdownStyle","dropdown","getCheckboxStyle","checkbox","backgroundColorSelected","colorSelected","getChipsStyle","chips","getDateStyle","getCardStyle","card","minLength","getSideButtonStyle","sideButton","minHeight","getExternalWidgetStyle","themeVariables","buildStyleVariables","entries_1","appliedVariableCounts","applyThemeVariables","entries_2","removeThemeVariables","children_1","child","colorIn","amount","colorOut","colorString","rgbaRegex","rgbRegex","hexMatch","rgba","luminance","ratio","padStart","SideButton","sideButtonPositionClass","DEFAULT_SESSION_KEY","validateDelay","validateScrollPercent","useAutoOpenTriggers","onOpen","hasInteracted","triggersRef","hasOpenedRef","inactivityTimerRef","sessionKey","triggers","delay","scrollPercent","exitIntent","exitIntentThreshold","inactivity","minimumWidth","patternsKey","configuredTriggers","getConfiguredTriggers","checkAndOpen","triggerName","allFired","every","isDismissed","matchesUrlPatterns","meetsMinimumWidth","timers","listeners","addListener","handler","targetPercent_1","scrollTicking_1","checkScrollPercent_1","scrollableHeight","maxTouchPoints","threshold_1","clientY","resetInactivityTimer_1","FORM_PAGE_ATTRIBUTE","FORM_PAGE_COUNT_ATTRIBUTE","markFormPage","useFormPageMarker","isEmbedded","classList","contains","lastClick","record","Element","FormContainer","Form","buttonElementLookup","setPreselectChipLabel","setHasInteracted","setOpenedByTrigger","immediateAutoOpen","autoOpen","hasAutoOpenTriggers","openModal","handleFocus","openFormWithOptions","formStatus","handleAutoOpen","elements","XAPP_FORM_BUTTON","onclick","onfocus","xafwControl","openForm","triggerSelector","earlyClick","click","takeEarlyClick","closest","HTMLAnchorElement","sideButtonLabel","hideSideButton","getBasePathFromWidgetSource","xappScriptNode","lastPathSep","lastIndexOf","substr","getBasePath","parseWidgetEnv","connection","accountKey","serverUrl","autocompleteSuggestionsUrl","STYLE_PRESET_NONE","resolveStylePresetName","standalone","stylePreset","partnerCode","getPresetStyle","resolveFormStyle","customerTheme","preset","mergeFormWidgetTheme","base","deepMerge","isPlainObject","merged","COST_GUIDE_FORM_STYLE","standAlone"],"mappings":"+zEAEA,IAAI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AYw+C,GAAUx+C,EAAU3V,GAASA,CAJnF,CAKJ,CAEA,OAAOq0D,CACX,CC/HO,IAAMC,GAA0C,CACnDrnD,SAAS,EACT+7C,MAAO,CAKHuB,YAAa,cAGb5V,aAAc,MAGdH,gBAAiB,UAGjByV,sBAAuB,UACvBC,gBAAiB,UAGjBC,mBAAoB,UACpBC,uBAAwB,UAKxBC,qBAAsB,UACtBC,yBAA0B,UAC1B/mD,KAAM,CACF0xB,MAAO,UAUPuf,gBAAiB,UAIjB+V,YAAa,UACbI,YAAa,MACbC,iBAAkB,WAEtBqB,MAAO,CAQHzX,gBAAiB,UACjBvf,MAAO,UACP62B,wBAAyB,UACzBC,cAAe,WAEnBxoC,KAAM,CACFuoC,wBAAyB,WAM7B13B,OAAQ,CACJ0gB,SAAU,OACVzK,WAAY,MACZoK,QAAS,YACTE,aAAc,OACdyW,UAAW,qCAKfI,qBAAsB,SAItBD,UAAW,CACPt1B,MAAO,SACP6e,SAAU,OACVzK,WAAY,MACZpV,MAAO,WAKX61B,kBAAmB,OACnBE,WAAY,CACR/1B,MAAO,UACPs1B,YAAa,UACbW,WAAY,UAEZP,YAAa,MACbM,WAAY,SAGhB/B,KAAM,CAIFsB,WAAY,sCACZrB,KAAM,kFAEVoL,WAAY,CACR/f,gBAAiB,sBAErB/lB,eAAgB,CAEZ+9B,UAAW","x_google_ignoreList":[12,36,37,38,53,70]}
1
+ {"version":3,"file":"index.es.js","sources":["../../chat-widget-core/dist/index.js","../src/utils/tracking.ts","../src/utils/index.ts","../src/utils/guards/isCarousel.ts","../src/utils/guards/isList.ts","../src/utils/guards/isForm.ts","../src/store/reducers/RootReducer.ts","../src/utils/guards/throwBadKind.ts","../src/store/SearchStoreContext.ts","../src/store/SearchStoreProvider.tsx","../src/store/useSearchStore.ts","../src/store/useSearchState.ts","../../../node_modules/style-inject/dist/style-inject.es.js","../src/components/ModalDialog/ModalDialog.tsx","../src/api/stentor-api.ts","../src/utils/getActionLabel.ts","../src/utils/SearchWidgetConfigContext.ts","../src/utils/useLoading.ts","../src/utils/useIsMounted.ts","../src/utils/useTrustedForm.ts","../src/utils/metaCookies.ts","../src/utils/ga4.ts","../src/components/icons/LeftAngleIcon/LeftAngleIcon.tsx","../src/components/icons/RightAngleIcon/RightAngleIcon.tsx","../src/components/icons/SearchIcon/SearchIcon.tsx","../src/components/icons/SpinnerIcon/SpinnerIcon.tsx","../src/components/icons/FieldIcons/FieldIcons.tsx","../src/components/SearchResponseBubble/SearchResponseBubble.tsx","../src/components/Card/utils.ts","../src/components/Card/Card.tsx","../src/components/Carousel/CarouselItem.tsx","../src/components/Carousel/Carousel.tsx","../src/components/SearchResponseCarouselDisplay/SearchResponseCarouselDisplay.tsx","../src/components/Cards/Cards.tsx","../src/components/SearchResponseListDisplay/SearchResponseListDisplay.tsx","../src/utils/comparator.ts","../src/utils/templating.ts","../src/utils/nextBusinessDayBlock.ts","../../../node_modules/dayjs/dayjs.min.js","../../../node_modules/dayjs/plugin/timezone.js","../../../node_modules/dayjs/plugin/utc.js","../src/utils/timeSlots.ts","../src/utils/useExternalWidget.ts","../src/components/FormFieldChips/FormFieldSelect.tsx","../src/components/FormFieldCard/FormFieldCard.tsx","../src/components/FormFieldChips/FormFieldChips.tsx","../src/utils/formatToInputProps.ts","../src/components/FormFieldTextInput/FormFieldTextInput.tsx","../src/components/FormFieldDropdown/FormFieldDropdown.tsx","../src/components/Calendar/Calendar.tsx","../src/utils/busyDays.ts","../src/components/FormFieldDate/dateAvailability.ts","../src/components/FormFieldDate/FormFieldDate.tsx","../src/components/FormFieldDateRange/FormFieldDateRange.tsx","../src/components/FormFieldDateTime/FormFieldDateTime.tsx","../../../node_modules/autosuggest-highlight/parse/index.js","../src/utils/AddressAutocompleteService.ts","../src/components/FormFieldTextInputAddress/FormFieldTextInputAddress.tsx","../src/components/FormStepDisplay/validators.ts","../src/components/FormStepDisplay/FormStepDisplay.tsx","../src/utils/guards/isField.ts","../src/components/FormFrame/FormFrame.tsx","../src/components/SimpleNavigationHeader/SimpleNavigationHeader.tsx","../src/utils/isInServiceArea.ts","../src/utils/extractZipFromAddress.ts","../src/components/FormDisplay/FormDisplay.tsx","../src/components/ResponseDisplay/ResponseDisplay.tsx","../src/components/SearchResponseHtml/SearchResponseHtml.tsx","../src/components/SearchResponseText/SearchResponseText.tsx","../src/components/SearchResponseAudio/SearchResponseAudio.tsx","../src/components/SearchResponseOutputSpeech/SearchResponseOutputSpeech.tsx","../src/utils/parseAudio.ts","../../../node_modules/stentor-guards/lib/isLinkoutSuggestion.js","../src/components/Button/Button.tsx","../src/components/SuggestedAction/SuggestedAction.tsx","../src/components/SuggestedActions/SuggestedActions.tsx","../src/components/FormResponse/SearchResponsePart.tsx","../src/components/FormResponse/FormResponse.tsx","../src/services/EventTrackingService.ts","../src/components/FormWidget/FormWidget.tsx","../src/components/WidgetStylesheet/WidgetStylesheet.tsx","../src/constants/variables.ts","../src/components/SideButton/SideButton.tsx","../src/hooks/useAutoOpenTriggers.ts","../src/hooks/useFormPageMarker.ts","../src/utils/isEmbedded.ts","../src/utils/earlyClicks.ts","../src/components/Form/Form.tsx","../src/store/useSearchDispatch.ts","../src/config/config.ts","../src/utils/parseWidgetEnv.ts","../src/utils/stylePreset.ts","../src/presets/costguide.ts"],"sourcesContent":["'use strict';\n\nvar jsxRuntime = require('react/jsx-runtime');\nvar react = require('react');\n\nvar IconButton = function (props) {\n var Icon = props.icon;\n return (jsxRuntime.jsx(\"div\", { tabIndex: props.tabIndex ? Number(props.tabIndex) : 0, className: \"xapp-search-icon-button \".concat(props.className || \"\"), onClick: props.onClick, children: jsxRuntime.jsx(\"div\", { className: \"xapp-search-icon-button__content\", children: jsxRuntime.jsx(Icon, {}) }) }));\n};\n\nvar MessageBubble = function (props) {\n return jsxRuntime.jsx(\"div\", { className: \"xappw-message-bubble\", children: props.children });\n};\n\n// compile time full switch-case verification\nfunction throwBadKind(x) {\n throw new Error(\"Unknown kind \" + x);\n}\n\nvar RichTextBoldSpan = function (props) {\n var format = props.format, text = props.text;\n return (jsxRuntime.jsx(\"span\", { \"data-rich-text-type\": \"bold\", className: \"xapp-search-rich-text-bold-span\", children: text.substring(format.start, format.end) }));\n};\n\nvar RichTextInputSpan = function (props) {\n var format = props.format, text = props.text, readOnly = props.readOnly, onClick = props.onClick;\n var defaultValue = format.text || text.substring(format.start, format.end);\n var _a = react.useState(defaultValue), value = _a[0], setValue = _a[1];\n var handleChange = react.useCallback(function (ev) {\n setValue(ev.target.value);\n }, []);\n var handleClick = react.useCallback(function (ev) {\n if (onClick) {\n var res = onClick(format);\n if (res === false) {\n ev.preventDefault();\n ev.stopPropagation();\n }\n }\n }, [onClick, format]);\n if (readOnly) {\n return (jsxRuntime.jsx(\"span\", { className: \"xapp-search-rich-text-input-span xapp-search-rich-text-input-span--readonly\", onClick: handleClick, children: defaultValue }));\n }\n return (jsxRuntime.jsx(\"input\", { type: \"text\", value: value, className: \"xapp-search-rich-text-input-span\", \"data-rich-text-type\": \"inputText\", onChange: handleChange, onClick: handleClick, readOnly: readOnly }));\n};\n\nvar RichTextNormalSpan = function (props) {\n var format = props.format, text = props.text;\n return (jsxRuntime.jsx(\"span\", { \"data-rich-text-type\": \"normal\", className: \"xapp-search-rich-text-normal-span\", children: text.substring(format.start, format.end) }));\n};\n\nvar RichTextSpan = function (props) {\n var format = props.format, text = props.text, readOnly = props.readOnly, onClick = props.onClick;\n var type = format.type;\n switch (type) {\n case \"normal\":\n return jsxRuntime.jsx(RichTextNormalSpan, { text: text, format: format, readOnly: readOnly });\n case \"bold\":\n return jsxRuntime.jsx(RichTextBoldSpan, { text: text, format: format, readOnly: readOnly });\n case \"inputText\":\n return (jsxRuntime.jsx(RichTextInputSpan, { text: text, format: format, readOnly: readOnly, onClick: onClick }));\n default:\n throwBadKind(type);\n }\n};\n\nfunction cleanRichTextValue(value) {\n var text = value.text, formats = value.formats;\n var newFormats = [];\n for (var _i = 0, formats_1 = formats; _i < formats_1.length; _i++) {\n var format = formats_1[_i];\n var type = format.type;\n switch (type) {\n case \"normal\":\n continue;\n case \"inputText\":\n newFormats.push(format);\n break;\n case \"bold\":\n if (newFormats.length > 0) {\n var prev = newFormats[newFormats.length - 1];\n if (prev.type === type && prev.end === format.start) {\n newFormats.pop();\n newFormats.push({\n type: type,\n start: prev.start,\n end: format.end\n });\n }\n }\n else {\n newFormats.push(format);\n }\n break;\n }\n }\n return {\n text: text,\n formats: newFormats\n };\n}\n\nfunction extendFormat(formats, length) {\n var res = [];\n var walkerIndex = 0;\n for (var _i = 0, formats_1 = formats; _i < formats_1.length; _i++) {\n var format = formats_1[_i];\n var start = format.start, end = format.end, type = format.type, text = format.text;\n if (walkerIndex < start) {\n res.push({\n type: \"normal\",\n start: walkerIndex,\n end: start\n });\n }\n res.push({\n type: type,\n start: start,\n end: end,\n text: text\n });\n walkerIndex = end;\n }\n if (walkerIndex < length) {\n res.push({\n type: \"normal\",\n start: walkerIndex,\n end: length\n });\n }\n return res;\n}\n\nfunction parseContent(node) {\n var children = node.childNodes;\n var formats = [];\n var text = \"\";\n children.forEach(function (child) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n var node_1 = child;\n var innerText = node_1.tagName === \"INPUT\" ? node_1.value : node_1.innerText;\n var type = node_1.dataset.richTextType;\n formats.push({\n type: type,\n start: text.length,\n end: text.length + innerText.length,\n });\n text += innerText;\n }\n if (child.nodeType === Node.TEXT_NODE) {\n var node_2 = child;\n var innerText = node_2.nodeValue;\n if (innerText) {\n formats.push({\n type: \"normal\",\n start: text.length,\n end: text.length + innerText.length,\n });\n text += innerText;\n }\n }\n });\n return cleanRichTextValue({\n text: text,\n formats: formats,\n });\n}\nfunction cleanContent(node) {\n var _a;\n var trash = [];\n var raw = node.childNodes;\n for (var i = 0; i < raw.length; i++) {\n var c = raw.item(i);\n if ((c === null || c === void 0 ? void 0 : c.nodeType) === Node.TEXT_NODE) {\n trash.push(c);\n }\n }\n for (var _i = 0, trash_1 = trash; _i < trash_1.length; _i++) {\n var c = trash_1[_i];\n try {\n (_a = c.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(c);\n }\n catch (_b) { }\n }\n}\nvar RichText = function (props) {\n var value = props.value, className = props.className, readOnly = props.readOnly, onInput = props.onInput, onChange = props.onChange, onSpanClick = props.onSpanClick;\n var formatsRaw = value.formats, text = value.text;\n var formats = react.useMemo(function () { return extendFormat(formatsRaw, text.length); }, [formatsRaw, text.length]);\n var handleInput = react.useCallback(function (ev) {\n var target = ev.currentTarget;\n var newValue = parseContent(target);\n if (onInput) {\n onInput(newValue);\n }\n }, [onInput]);\n var handleBlur = react.useCallback(function (ev) {\n var target = ev.currentTarget;\n var newValue = parseContent(target);\n cleanContent(target);\n if (onChange) {\n onChange(newValue);\n }\n }, [onChange]);\n return (jsxRuntime.jsx(\"div\", { id: props.id, className: \"xapp-search-rich-text \".concat(className || \"\"), contentEditable: !readOnly, suppressContentEditableWarning: true, onInput: handleInput, onBlur: handleBlur, onKeyDown: props.onKeyDown, children: formats.map(function (format, index) { return (jsxRuntime.jsx(RichTextSpan, { format: format, text: text, readOnly: readOnly, onClick: onSpanClick }, index)); }) }));\n};\n\nvar RichInput = function (props) {\n var id = props.id, value = props.value, type = props.type, autoFocus = props.autoFocus, spellCheck = props.spellCheck, tabIndex = props.tabIndex, maxLength = props.maxLength, enterKeyHint = props.enterKeyHint, onChange = props.onChange, onInput = props.onInput, onKeyDown = props.onKeyDown, onSearch = props.onSearch;\n var rich = value.formats.some(function (f) { return f.type === \"inputText\"; });\n var keyHint = enterKeyHint || (type === \"search\" ? \"search\" : \"send\");\n var handleChange = react.useCallback(function (ev) {\n if (onChange) {\n onChange({\n text: ev.target.value,\n formats: [],\n });\n }\n }, [onChange]);\n var handleRichChange = react.useCallback(function (val) {\n if (onChange) {\n onChange(val);\n }\n }, [onChange]);\n var handleInput = react.useCallback(function (ev) {\n if (onInput) {\n onInput({\n text: ev.target.value,\n formats: [],\n });\n }\n }, [onInput]);\n var handleRichInput = react.useCallback(function (val) {\n if (onInput) {\n onInput(val);\n }\n }, [onInput]);\n var handleKeyDown = react.useCallback(function (event) {\n if (onKeyDown) {\n onKeyDown(event);\n }\n }, [onKeyDown]);\n var inputRef = react.useRef(null);\n var inputNode = inputRef.current;\n react.useEffect(function () {\n if (inputNode && onSearch) {\n var handler_1 = function (ev) {\n var target = ev.target;\n if (target) {\n onSearch({\n text: target.value,\n formats: [],\n });\n }\n };\n inputNode.addEventListener(\"search\", handler_1);\n return function () {\n inputNode.removeEventListener(\"search\", handler_1);\n };\n }\n return undefined;\n }, [inputNode, onSearch]);\n return (jsxRuntime.jsx(\"div\", { className: \"xappw-rich-input \".concat(props.className), children: rich ? (jsxRuntime.jsx(RichText, { id: id, value: value, onChange: handleRichChange, onInput: handleRichInput, onKeyDown: handleKeyDown, className: \"xappw-rich-input__input \".concat(props.className, \"__input\") })) : (jsxRuntime.jsx(\"input\", { id: id, ref: inputRef, type: type, value: value.text, autoComplete: \"off\", enterKeyHint: keyHint, autoFocus: autoFocus, placeholder: props.placeholder, spellCheck: spellCheck, tabIndex: tabIndex ? Number(tabIndex) : 0, maxLength: maxLength, className: \"xappw-rich-input__input \".concat(props.className, \"__input\"), onFocus: props.onFocus, onChange: handleChange, onInput: handleInput, onKeyDown: handleKeyDown })) }));\n};\n\nvar SuggestionsGroupHeading = function (props) {\n return jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-group-heading\", children: props.label });\n};\n\nfunction getScrollContainer(node) {\n var walker = node;\n while (walker && !walker.classList.contains(\"xapp-search-result__suggestions\")) {\n walker = walker.parentElement;\n }\n return walker || undefined;\n}\nvar SuggestionsItem = function (props) {\n var data = props.data, current = props.current, ActionsComponent = props.actions, onClick = props.onClick, onHover = props.onHover, onSpanClick = props.onSpanClick;\n var handleClick = react.useCallback(function () {\n onClick(data);\n }, [data, onClick]);\n var handleHover = react.useCallback(function () {\n if (onHover) {\n onHover(data);\n }\n }, [data, onHover]);\n var handleSpanClick = react.useCallback(function (span) {\n if (onSpanClick) {\n return onSpanClick(data, span);\n }\n return undefined;\n }, [onSpanClick, data]);\n var ref = react.useRef(null);\n react.useEffect(function () {\n var node = ref.current;\n if (current && node) {\n var scrollContainer = getScrollContainer(node);\n if (scrollContainer) {\n var scrollBox = scrollContainer.getBoundingClientRect();\n var nodeBox = node.getBoundingClientRect();\n var maxTop = Math.max(scrollBox.top, nodeBox.top);\n var minBottom = Math.min(scrollBox.bottom, nodeBox.bottom);\n var visibleHeight = minBottom - maxTop;\n var actualHeight = nodeBox.height;\n if (visibleHeight < actualHeight * 0.99) {\n node.scrollIntoView({ behavior: \"smooth\" });\n }\n }\n }\n }, [current]);\n return (jsxRuntime.jsxs(\"div\", { ref: ref, className: \"xappw-suggestions-item \".concat(current ? \"xappw-suggestions-item--current\" : \"\"), onClick: handleClick, onMouseEnter: handleHover, children: [jsxRuntime.jsx(RichText, { value: data, className: \"xappw-suggestions-item__texts\", readOnly: true, onSpanClick: handleSpanClick }), ActionsComponent && (jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-item__actions\", children: jsxRuntime.jsx(ActionsComponent, { data: data, current: current }) }))] }));\n};\n\nvar SuggestionsGroup = function (props) {\n var group = props.group, currentIndex = props.currentIndex, itemActions = props.itemActions;\n var heading = group.heading, items = group.items;\n return (jsxRuntime.jsxs(\"div\", { className: \"xappw-suggestions-group\", children: [jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-group__heading\", children: jsxRuntime.jsx(SuggestionsGroupHeading, { label: heading }) }), jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-group__items\", children: items.map(function (item, itemIndex) { return (jsxRuntime.jsx(SuggestionsItem, { data: item, current: currentIndex === itemIndex, actions: itemActions, onClick: props.onItemClick, onHover: props.onItemHover, onSpanClick: props.onSpanClick }, itemIndex)); }) })] }));\n};\n\nfunction getItemsLength(result) {\n return result.reduce(function (prev, cur) { return prev + cur.items.length; }, 0);\n}\n\nvar SuggestionsList = function (props) {\n var suggestions = props.suggestions, itemActions = props.itemActions, className = props.className;\n var length = react.useMemo(function () {\n if (suggestions) {\n return getItemsLength(suggestions);\n }\n return 0;\n }, [suggestions]);\n var currentIndex = length >= 0 ? props.index : NaN;\n var indexWalker = 0;\n return (jsxRuntime.jsx(\"div\", { className: \"xappw-suggestions-list \".concat(className || \"\"), children: suggestions === null || suggestions === void 0 ? void 0 : suggestions.map(function (group, index) {\n var res = (jsxRuntime.jsx(SuggestionsGroup, { group: group, currentIndex: currentIndex - indexWalker, itemActions: itemActions, onItemClick: props.onItemClick, onItemHover: props.onItemHover, onSpanClick: props.onSpanClick }, index));\n indexWalker += group.items.length;\n return res;\n }) }));\n};\n\nfunction findItemByIndex(groups, index) {\n if (index >= 0) {\n for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {\n var group = groups_1[_i];\n for (var _a = 0, _b = group.items; _a < _b.length; _a++) {\n var item = _b[_a];\n if (index <= 0) {\n return item;\n }\n index--;\n }\n }\n }\n return undefined;\n}\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nfunction __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar order = [\"FAQ\", \"INTENT\", \"HISTORICAL\"];\nvar ordersMap = order.reduce(function (prev, cur, index) {\n prev[cur] = index;\n return prev;\n}, {});\nfunction compareSuggestionItems(left, right, direction) {\n return direction * (ordersMap[right.type] - ordersMap[left.type]);\n}\nfunction sortSuggestionItems(items, direction) {\n return __spreadArray([], items, true).sort(function (left, right) { return compareSuggestionItems(left, right, direction); });\n}\n\nfunction parseSuggestionsFormat(format) {\n var types = Object.keys(format);\n var type = types[0];\n var item = format[type];\n if (!item) {\n throw new Error();\n }\n return {\n type: type,\n start: item.start,\n end: item.end,\n };\n}\nfunction parseSuggestionsFormats(formats) {\n return formats.map(parseSuggestionsFormat);\n}\nfunction parseSuggestionsResponseItem(item) {\n return {\n text: item.suggestion,\n content: item.answer,\n formats: parseSuggestionsFormats(item.format),\n type: item.type,\n };\n}\nfunction getHeading(type) {\n switch (type) {\n case \"FAQ\":\n return \"FAQs\";\n case \"INTENT\":\n return \"Suggestions\";\n case \"HISTORICAL\":\n return \"Suggestions\";\n default:\n return type;\n }\n}\nfunction parseSuggestionsResponse(response, direction) {\n if (direction === void 0) { direction = 1; }\n if (!response) {\n return undefined;\n }\n var items = sortSuggestionItems(response.suggestions, direction);\n return items.reduce(function (result, current) {\n var mappedItem = parseSuggestionsResponseItem(current);\n if (result.length) {\n var prevGroup = result[result.length - 1];\n if (prevGroup.heading === getHeading(current.type)) {\n prevGroup.items.push(mappedItem);\n return result;\n }\n }\n result.push({\n heading: getHeading(current.type),\n items: [mappedItem],\n });\n return result;\n }, []);\n}\n\n/**\n * Append the provided query params to the URL\n *\n * It will overwrite existing params on the URL if there are conflicts\n * @param url\n * @param params\n */\nfunction addQueryParametersToURL(url, params) {\n var existingParams = new URL(url).searchParams;\n params.forEach(function (value, key) {\n existingParams.append(key, value);\n });\n var newUrl = new URL(url);\n newUrl.search = existingParams.toString();\n return newUrl;\n}\n\nvar defaultOptions = {};\nfunction noop() {\n}\nfunction useJsonFetch(url, options) {\n if (options === void 0) { options = defaultOptions; }\n var _a = react.useState({\n state: \"paused\"\n }), value = _a[0], setValue = _a[1];\n var pause = options.pause;\n react.useEffect(function () {\n if (pause) {\n setValue({\n state: \"paused\"\n });\n return noop;\n }\n var controller = new AbortController();\n var signal = controller.signal;\n var mounted = true;\n (function () {\n return __awaiter(this, void 0, void 0, function () {\n var response, json, e_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 4, , 5]);\n setValue({\n state: \"fetching\"\n });\n return [4 /*yield*/, fetch(url, { signal: signal })];\n case 1:\n response = _a.sent();\n if (!mounted) return [3 /*break*/, 3];\n return [4 /*yield*/, response.json()];\n case 2:\n json = _a.sent();\n if (response.ok) {\n setValue({\n state: \"success\",\n data: json\n });\n }\n else {\n setValue({\n state: \"error\",\n error: json\n });\n }\n _a.label = 3;\n case 3: return [3 /*break*/, 5];\n case 4:\n e_1 = _a.sent();\n if (e_1.name === \"AbortError\") {\n setValue({\n state: \"paused\"\n });\n return [2 /*return*/];\n }\n throw e_1;\n case 5: return [2 /*return*/];\n }\n });\n });\n })();\n return function () {\n mounted = false;\n controller.abort();\n };\n }, [url, pause]);\n return value;\n}\n\nfunction useSuggestionsFetch(options) {\n var baseUrl = options.url, context = options.context, query = options.query;\n var url = react.useMemo(function () {\n if (!baseUrl) {\n return undefined;\n }\n var params = new URLSearchParams();\n params.append(\"size\", \"5\");\n params.append(\"queryText\", query);\n if (context === null || context === void 0 ? void 0 : context.length) {\n params.append(\"activeContexts\", context.join(\",\"));\n }\n return addQueryParametersToURL(baseUrl, params);\n }, [query, context, baseUrl]);\n var response = useJsonFetch(url ? \"\".concat(url.toString()) : \"\", {\n pause: !query || !baseUrl\n });\n return response;\n}\n\n/**\n * Marketing attribution capture, shared by every widget surface.\n *\n * The chat widget historically sent only `currentUrl`, which meant attribution\n * survived only when the visitor opened the chat on the very page the ad landed\n * them on. Anyone who browsed first arrived unattributed. These helpers capture\n * the parameters on first sight and persist them, so a conversation started three\n * pages later still carries the click that paid for it.\n *\n * Only the parameters below are ever read or stored. The query string as a whole\n * is not, because it routinely carries session tokens and PII.\n */\n/** Standard UTM parameters. */\nvar UTM_PARAMETERS = [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\"\n];\n/**\n * Platform click ids.\n *\n * `gbraid` and `wbraid` are what Google substitutes for `gclid` when the click\n * cannot be tied to a cookie — iOS and consent-mode traffic. For home services,\n * where most paid traffic is mobile, omitting them loses attribution on the\n * majority of the spend.\n */\nvar CLICK_ID_PARAMETERS = [\n \"gclid\",\n \"gbraid\",\n \"wbraid\",\n \"msclkid\",\n \"fbclid\"\n];\nvar ATTRIBUTION_PARAMETERS = __spreadArray(__spreadArray([], UTM_PARAMETERS, true), CLICK_ID_PARAMETERS, true);\n/**\n * Params AI surfaces put on the links they send people to: Google AI Overviews\n * (`st_source=ai_overview`), Google's `srsltid` click id, and the generic `ref` / `source`\n * that ChatGPT, Perplexity and others use. Read only by the widget `load` event, never stored and\n * never sent with chat messages.\n */\nvar AI_REFERRAL_PARAMETERS = [\"st_source\", \"srsltid\", \"ref\", \"source\"];\nvar STORAGE_KEY_PREFIX = \"xa_tracking_\";\n/** Matches the 30 day window the form widget already uses. */\nvar DEFAULT_PERSISTENCE_DAYS = 30;\nvar MAX_VALUE_LENGTH$1 = 255;\n/**\n * Values land in a request body and, downstream, in a CRM. Cap the length and\n * reject anything carrying markup or control characters.\n */\nfunction isValidValue$1(value) {\n // eslint-disable-next-line no-control-regex\n return value.length <= MAX_VALUE_LENGTH$1 && !/[<>\"'\\x00-\\x1f]/.test(value);\n}\n/**\n * Reads the attribution parameters present on a URL. Never throws — a URL we\n * cannot parse simply contributes nothing.\n */\nfunction extractAttributionFromUrl(url) {\n var parsed;\n try {\n parsed = new URL(url);\n }\n catch (_a) {\n return {};\n }\n var attribution = {};\n ATTRIBUTION_PARAMETERS.forEach(function (parameter) {\n var value = parsed.searchParams.get(parameter);\n if (value && isValidValue$1(value)) {\n attribution[parameter] = value;\n }\n });\n return attribution;\n}\n/**\n * Persists attribution for later conversations. Existing values are overwritten,\n * so the most recent click wins, matching how the ad platforms attribute.\n */\nfunction storeAttribution(attribution, persistenceDays) {\n if (persistenceDays === void 0) { persistenceDays = DEFAULT_PERSISTENCE_DAYS; }\n var expires = Date.now() + persistenceDays * 24 * 60 * 60 * 1000;\n Object.entries(attribution).forEach(function (_a) {\n var key = _a[0], value = _a[1];\n if (!value) {\n return;\n }\n try {\n localStorage.setItem(\"\".concat(STORAGE_KEY_PREFIX).concat(key), JSON.stringify({ value: value, expires: expires }));\n }\n catch (_b) {\n // Storage can be full or blocked by the browser. Attribution is best\n // effort — never let it break the conversation.\n }\n });\n}\n/** Reads back unexpired stored attribution, cleaning up anything unreadable. */\nfunction getStoredAttribution() {\n var attribution = {};\n ATTRIBUTION_PARAMETERS.forEach(function (parameter) {\n var key = \"\".concat(STORAGE_KEY_PREFIX).concat(parameter);\n var stored;\n try {\n stored = localStorage.getItem(key);\n }\n catch (_a) {\n return;\n }\n if (!stored) {\n return;\n }\n try {\n var parsed = JSON.parse(stored);\n if (parsed && parsed.expires > Date.now() && typeof parsed.value === \"string\") {\n attribution[parameter] = parsed.value;\n }\n else {\n localStorage.removeItem(key);\n }\n }\n catch (_b) {\n localStorage.removeItem(key);\n }\n });\n return attribution;\n}\n/**\n * The attribution to send with a request: whatever is stored, with anything on\n * the current URL layered on top, and the current URL's values persisted for\n * subsequent pages.\n */\nfunction getAttribution(url) {\n if (url === void 0) { url = window.location.href; }\n var fromUrl = extractAttributionFromUrl(url);\n if (Object.keys(fromUrl).length > 0) {\n storeAttribution(fromUrl);\n }\n return __assign(__assign({}, getStoredAttribution()), fromUrl);\n}\n/**\n * Strips the query string from a URL, leaving origin + pathname.\n *\n * Referrers and page URLs routinely carry session tokens, email addresses and other\n * PII in their query strings, and a referrer captured at session start is sent with\n * every subsequent message — so the raw value must never be stored. Attribution is\n * read separately, by allowlist, before this is applied.\n *\n * Returns undefined for an empty or unparseable URL rather than passing it through.\n */\nfunction stripQueryString(url) {\n if (!url) {\n return undefined;\n }\n try {\n var parsed = new URL(url);\n return parsed.origin + parsed.pathname;\n }\n catch (_a) {\n return undefined;\n }\n}\n\n/**\n * Client-side detection of AI browsing agents (Meta Muse, OpenClaw, ChatGPT agent, Gemini,\n * Claude, Perplexity, ...) visiting a customer's site.\n *\n * Pure: it reads only what it is handed, so it can be tested without a browser. The verdict\n * is a hint, not an identity - it decides whether to show agents a pointer to the MCP server\n * and is reported with the widget `load` event so the server side can do the real classification.\n */\n/** User-agent tokens of agents that browse on a person's behalf. Matched case-insensitively. */\nvar AGENT_UA_TOKENS = [\n \"ChatGPT-User\",\n \"Claude-User\",\n \"Perplexity-User\",\n \"GoogleAgent\",\n \"Google-Agent\",\n \"MistralAI-User\",\n \"meta-externalagent\",\n \"HeadlessChrome\",\n];\n/** User-agent tokens of search-indexing crawlers, classic and AI search alike. */\nvar SEARCH_CRAWLER_UA_TOKENS = [\n \"Googlebot\",\n \"Google-InspectionTool\",\n \"Storebot-Google\",\n \"AdsBot-Google\",\n \"Mediapartners-Google\",\n \"bingbot\",\n \"BingPreview\",\n \"Applebot\",\n \"DuckDuckBot\",\n \"YandexBot\",\n \"Baiduspider\",\n \"OAI-SearchBot\",\n \"PerplexityBot\",\n];\n/**\n * Brands a real, branded Chromium browser adds next to \"Chromium\". An agent's headless or\n * stock Chromium carries \"Chromium\" alone - the observed Meta Muse fingerprint.\n */\nvar BRANDED_CHROMIUM = [\"Google Chrome\", \"Microsoft Edge\", \"Opera\", \"Brave\"];\nfunction includesToken(userAgent, token) {\n return userAgent.toLowerCase().indexOf(token.toLowerCase()) >= 0;\n}\nfunction isLinuxDesktop(nav, userAgent) {\n var data = nav.userAgentData;\n if (data === null || data === void 0 ? void 0 : data.mobile) {\n return false;\n }\n if (data === null || data === void 0 ? void 0 : data.platform) {\n return data.platform === \"Linux\";\n }\n return /\\bLinux\\b/.test(userAgent) && !/\\bAndroid\\b/.test(userAgent);\n}\nfunction isChromiumOnly(nav) {\n var _a;\n var names = (((_a = nav.userAgentData) === null || _a === void 0 ? void 0 : _a.brands) || []).map(function (b) { return b.brand; });\n return (names.indexOf(\"Chromium\") >= 0 && !names.some(function (name) { return BRANDED_CHROMIUM.indexOf(name) >= 0; }));\n}\nfunction detectBrowsingAgent(nav) {\n var userAgent = (nav === null || nav === void 0 ? void 0 : nav.userAgent) || \"\";\n var signals = [];\n if (!nav) {\n return { isAgent: false, isSearchCrawler: false, signals: signals };\n }\n if (nav.webdriver === true) {\n signals.push(\"webdriver\");\n }\n AGENT_UA_TOKENS.forEach(function (token) {\n if (includesToken(userAgent, token)) {\n signals.push(\"ua:\".concat(token));\n }\n });\n if (isChromiumOnly(nav) && isLinuxDesktop(nav, userAgent)) {\n signals.push(\"chromium-only-linux\");\n }\n var isSearchCrawler = SEARCH_CRAWLER_UA_TOKENS.some(function (token) {\n return includesToken(userAgent, token);\n });\n return { isAgent: !isSearchCrawler && signals.length > 0, isSearchCrawler: isSearchCrawler, signals: signals };\n}\n\n/**\n * Pointing AI browsing agents at the tenant's public MCP server.\n *\n * agent-server serves a public, unauthenticated, per-tenant homeowner MCP server at\n * `https://agentic.xapp.ai/{appId}/mcp` with a manifest at\n * `/{appId}/.well-known/mcp/manifest.json` and a server card at `/{appId}/mcp/server-card`. An agent that finds it can ask the business\n * questions and request a callback directly instead of scraping and form-filling.\n */\nvar DEFAULT_AGENT_MCP_HOST = \"https://agentic.xapp.ai\";\nvar APP_ID = /^[A-Za-z0-9_-]{1,128}$/;\nvar HOMEOWNER_PATHS = [\"/chat/stream\", \"/chat/close\"];\nfunction endpointsFor(origin, appId) {\n if (!APP_ID.test(appId)) {\n return undefined;\n }\n var base = \"\".concat(origin.replace(/\\/+$/, \"\"), \"/\").concat(appId);\n return {\n appId: appId,\n mcpUrl: \"\".concat(base, \"/mcp\"),\n manifestUrl: \"\".concat(base, \"/.well-known/mcp/manifest.json\"),\n serverCardUrl: \"\".concat(base, \"/mcp/server-card\"),\n };\n}\nfunction httpUrl(value) {\n try {\n var url = new URL(value);\n return url.protocol === \"https:\" || url.protocol === \"http:\" ? url : undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\n/** The first path segment of an http(s) URL, after removing a known endpoint suffix. */\nfunction firstSegment(url, suffixes) {\n var path = url.pathname.replace(/\\/+$/, \"\");\n suffixes.forEach(function (suffix) {\n if (path.endsWith(suffix)) {\n path = path.slice(0, -suffix.length);\n }\n });\n var segments = path.split(\"/\").filter(Boolean);\n return segments.length === 1 ? segments[0] : undefined;\n}\n/**\n * Resolves the tenant's public MCP endpoints. Order: explicit `agentMcpUrl`, then explicit\n * `appId` on the agent host, then the appId inside a homeowner MCP connection's serverUrl.\n * Undefined when none identifies the tenant.\n */\nfunction resolveAgentMcpEndpoints(source) {\n var _a;\n if (!source) {\n return undefined;\n }\n if (source.agentMcpUrl) {\n var url = httpUrl(source.agentMcpUrl);\n var appId = url && firstSegment(url, [\"/mcp\"]);\n return url && appId ? endpointsFor(url.origin, appId) : undefined;\n }\n if (source.appId) {\n var host = source.agentMcpHost && httpUrl(source.agentMcpHost);\n return endpointsFor(host ? host.origin : DEFAULT_AGENT_MCP_HOST, source.appId);\n }\n var connection = source.connection;\n if ((connection === null || connection === void 0 ? void 0 : connection.type) === \"mcp\" &&\n connection.serverUrl &&\n (((_a = connection.mcp) === null || _a === void 0 ? void 0 : _a.mode) || \"homeowner\") === \"homeowner\") {\n var url = httpUrl(connection.serverUrl);\n var appId = url && firstSegment(url, HOMEOWNER_PATHS);\n return url && appId ? endpointsFor(url.origin, appId) : undefined;\n }\n return undefined;\n}\nvar OWN_TAG = \"data-xapp-mcp\";\nfunction upsert(doc, tag, selector, attributes) {\n var existing = doc.head.querySelector(selector);\n if (existing && !existing.hasAttribute(OWN_TAG)) {\n // The site owner advertises their own - theirs wins.\n return;\n }\n var element = existing || doc.createElement(tag);\n element.setAttribute(OWN_TAG, \"\");\n Object.keys(attributes).forEach(function (name) { return element.setAttribute(name, attributes[name]); });\n if (!existing) {\n doc.head.appendChild(element);\n }\n}\n/** Adds (or refreshes) the MCP discovery tags in <head>. Idempotent. */\nfunction injectMcpDiscoveryTags(endpoints, doc) {\n if (doc === void 0) { doc = document; }\n if (!(doc === null || doc === void 0 ? void 0 : doc.head)) {\n return;\n }\n upsert(doc, \"link\", 'link[rel=\"mcp-server\"]', { rel: \"mcp-server\", href: endpoints.mcpUrl });\n upsert(doc, \"link\", 'link[rel=\"mcp-manifest\"]', {\n rel: \"mcp-manifest\",\n href: endpoints.manifestUrl,\n });\n upsert(doc, \"link\", 'link[rel=\"mcp-server-card\"]', {\n rel: \"mcp-server-card\",\n href: endpoints.serverCardUrl,\n });\n upsert(doc, \"meta\", 'meta[name=\"mcp-server\"]', {\n name: \"mcp-server\",\n content: endpoints.mcpUrl,\n });\n}\n/**\n * The note shown to AI assistants. Deliberately informational rather than imperative:\n * agents treat instruction-shaped page text as prompt injection and discard it.\n */\nfunction buildAgentNoticeText(mcpUrl, businessName) {\n var name = (businessName === null || businessName === void 0 ? void 0 : businessName.trim()) || \"this business\";\n return (\"AI assistant? You can talk to \".concat(name, \" directly over MCP: \").concat(mcpUrl, \" \") +\n \"\\u2014 ask questions, check services, and request a callback or quote for your user.\");\n}\nvar AGENT_NOTICE_ID = \"xapp-agent-notice\";\nvar AGENT_NOTICE_HIDDEN_ID = \"xapp-agent-notice-sr\";\n/** Text with the MCP URL as a link, built with DOM APIs so no value is parsed as markup. */\nfunction fillNotice(doc, container, options) {\n var text = buildAgentNoticeText(options.mcpUrl, options.businessName);\n var at = text.indexOf(options.mcpUrl);\n var link = doc.createElement(\"a\");\n link.href = options.mcpUrl;\n link.rel = \"nofollow\";\n link.textContent = options.mcpUrl;\n link.style.color = \"inherit\";\n container.appendChild(doc.createTextNode(text.slice(0, at)));\n container.appendChild(link);\n container.appendChild(doc.createTextNode(text.slice(at + options.mcpUrl.length)));\n}\n/**\n * Renders the agent notice: a small, dismissible note a person can ignore, plus a\n * visually-hidden copy for agents that read the DOM or accessibility tree rather than pixels.\n * Only call this for a detected agent. Renders once.\n */\nfunction renderAgentNotice(options, doc) {\n if (doc === void 0) { doc = document; }\n if (!(doc === null || doc === void 0 ? void 0 : doc.body)) {\n return;\n }\n if (!doc.getElementById(AGENT_NOTICE_HIDDEN_ID)) {\n var hidden = doc.createElement(\"div\");\n hidden.id = AGENT_NOTICE_HIDDEN_ID;\n hidden.style.cssText =\n \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;\" +\n \"clip:rect(0,0,0,0);white-space:nowrap;border:0;\";\n fillNotice(doc, hidden, options);\n doc.body.appendChild(hidden);\n }\n if (doc.getElementById(AGENT_NOTICE_ID)) {\n return;\n }\n var notice = doc.createElement(\"div\");\n notice.id = AGENT_NOTICE_ID;\n notice.setAttribute(\"role\", \"note\");\n notice.style.cssText =\n \"position:fixed;left:8px;bottom:8px;max-width:320px;z-index:2147483000;\" +\n \"padding:6px 24px 6px 8px;border-radius:4px;background:rgba(255,255,255,0.92);\" +\n \"color:#555;font:11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;\" +\n \"box-shadow:0 1px 3px rgba(0,0,0,0.15);word-break:break-word;\";\n fillNotice(doc, notice, options);\n var close = doc.createElement(\"button\");\n close.type = \"button\";\n close.setAttribute(\"aria-label\", \"Dismiss\");\n close.textContent = \"×\";\n close.style.cssText =\n \"position:absolute;top:2px;right:4px;border:0;background:none;color:#888;\" +\n \"font-size:14px;line-height:1;cursor:pointer;padding:2px;\";\n close.addEventListener(\"click\", function () { return notice.remove(); });\n notice.appendChild(close);\n doc.body.appendChild(notice);\n}\n\nfunction isModelContext(value) {\n return !!value && typeof value.registerTool === \"function\";\n}\n/** The page's model context, if this browser has WebMCP. */\nfunction findModelContext(doc, nav) {\n if (doc === void 0) { doc = typeof document !== \"undefined\"\n ? document\n : undefined; }\n if (nav === void 0) { nav = typeof navigator !== \"undefined\"\n ? navigator\n : undefined; }\n if (isModelContext(doc === null || doc === void 0 ? void 0 : doc.modelContext)) {\n return doc.modelContext;\n }\n if (isModelContext(nav === null || nav === void 0 ? void 0 : nav.modelContext)) {\n return nav.modelContext;\n }\n return undefined;\n}\n/**\n * A minimal client for the tenant's homeowner MCP endpoint: one `tools/call` per request, no\n * session. The endpoint is public and the server keeps no state we need, so the MCP\n * initialize handshake would only add a round trip (and a session the next App Runner\n * instance has never heard of).\n */\nvar HomeownerMcpClient = /** @class */ (function () {\n function HomeownerMcpClient(mcpUrl, fetchImpl) {\n this.mcpUrl = mcpUrl;\n this.nextId = 1;\n this.fetchImpl = fetchImpl || (typeof fetch === \"function\" ? fetch : undefined);\n }\n HomeownerMcpClient.prototype.callTool = function (name, args) {\n return __awaiter(this, void 0, void 0, function () {\n var response, body;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (typeof this.fetchImpl !== \"function\") {\n throw new Error(\"fetch is not available\");\n }\n return [4 /*yield*/, this.fetchImpl(this.mcpUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: this.nextId++,\n method: \"tools/call\",\n params: { name: name, arguments: args },\n }),\n })];\n case 1:\n response = _a.sent();\n if (!response.ok) {\n throw new Error(\"MCP endpoint answered \".concat(response.status));\n }\n return [4 /*yield*/, response.json()];\n case 2:\n body = (_a.sent());\n if (body.error) {\n throw new Error(body.error.message || \"MCP error \".concat(body.error.code));\n }\n return [2 /*return*/, toolResultToValue(body.result)];\n }\n });\n });\n };\n return HomeownerMcpClient;\n}());\n/**\n * MCP tool results are text parts; agents want a value. JSON text becomes the object it\n * encodes, prose stays `{ text }`, and a tool-level error becomes `{ ok: false, message }` so\n * the agent can read the validation message and try again rather than seeing a thrown call.\n */\nfunction toolResultToValue(result) {\n var text = ((result === null || result === void 0 ? void 0 : result.content) || [])\n .filter(function (part) { return part.type === \"text\" && typeof part.text === \"string\"; })\n .map(function (part) { return part.text; })\n .join(\"\\n\");\n if (result === null || result === void 0 ? void 0 : result.isError) {\n return { ok: false, message: text };\n }\n try {\n return JSON.parse(text);\n }\n catch (_a) {\n return { text: text };\n }\n}\nvar CALLBACK_FIELDS = [\n \"name\",\n \"phone\",\n \"email\",\n \"address\",\n \"zip\",\n \"serviceType\",\n \"message\",\n \"preferredContactTime\",\n \"urgency\",\n];\nfunction pick(input, keys) {\n var out = {};\n keys.forEach(function (key) {\n if (input && input[key] !== undefined && input[key] !== null && input[key] !== \"\") {\n out[key] = input[key];\n }\n });\n return out;\n}\n/**\n * The tools a visitor's agent gets. Names and descriptions are written for that agent, which\n * is helping a person on the business's site; the server's own tool descriptions address the\n * business owner and would mislead it.\n */\nfunction buildSiteTools(endpoints, caller, options) {\n var _a;\n if (options === void 0) { options = {}; }\n var business = ((_a = options.businessName) === null || _a === void 0 ? void 0 : _a.trim()) || \"this business\";\n var readOnly = {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n };\n return [\n {\n name: \"get_business_info\",\n description: \"What \".concat(business, \" offers: services, service area, hours, and how to reach them. \") +\n \"Call this first when the user asks what the business does or whether it can help.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: false,\n },\n annotations: readOnly,\n execute: function () { return caller.callTool(\"get_business_context\", {}); },\n },\n {\n name: \"search_business_knowledge\",\n description: \"Search \".concat(business, \"'s FAQs and website content to answer a question: services, \") +\n \"pricing, policies, scheduling, warranties, service area.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"The user's question, in their words.\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n annotations: readOnly,\n execute: function (input) { return caller.callTool(\"search_knowledge_base\", pick(input, [\"query\"])); },\n },\n {\n name: \"request_callback\",\n description: \"Ask \".concat(business, \" to contact the user about work they need. Sends the user's name, \") +\n \"phone or email, address and request to the business as a lead. Only call this after \" +\n \"the user has agreed to be contacted. Returns validation errors to fix, or confirmation.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"The user's full name.\" },\n phone: {\n type: \"string\",\n description: \"Phone number, at least 10 digits. Required if no email.\",\n },\n email: { type: \"string\", description: \"Email address. Required if no phone.\" },\n address: {\n type: \"string\",\n description: \"Street address where the work is needed.\",\n },\n zip: {\n type: \"string\",\n description: \"ZIP or postal code where the work is needed.\",\n },\n serviceType: {\n type: \"string\",\n description: \"The kind of work or service needed.\",\n },\n message: {\n type: \"string\",\n description: \"What the user needs, in their words.\",\n },\n preferredContactTime: {\n type: \"string\",\n description: \"When the user would like to be contacted.\",\n },\n urgency: {\n type: \"string\",\n description: 'How urgent: \"urgent\", \"this week\" or \"flexible\".',\n },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n execute: function (input) {\n return caller.callTool(\"collect_contact_info\", __assign(__assign({ appId: endpoints.appId, source: \"webmcp\", channel: \"mcp\" }, (options.channelId ? { channelId: options.channelId } : {})), pick(input, CALLBACK_FIELDS)));\n },\n },\n ];\n}\nvar registered = new WeakSet();\n/**\n * Registers the site tools on the page's model context. Resolves with how many were\n * registered: 0 in a browser without WebMCP, on a second call for the same context, or when\n * registration fails. Never rejects: this runs at widget start and must not take it down.\n */\nfunction registerSiteTools(options) {\n return __awaiter(this, void 0, void 0, function () {\n var context, client, tools, count, _i, tools_1, tool;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 5, , 6]);\n context = findModelContext(options.doc, options.nav);\n if (!context || registered.has(context)) {\n return [2 /*return*/, 0];\n }\n registered.add(context);\n client = new HomeownerMcpClient(options.endpoints.mcpUrl, options.fetchImpl);\n tools = buildSiteTools(options.endpoints, client, options);\n count = 0;\n _i = 0, tools_1 = tools;\n _b.label = 1;\n case 1:\n if (!(_i < tools_1.length)) return [3 /*break*/, 4];\n tool = tools_1[_i];\n return [4 /*yield*/, context.registerTool(tool)];\n case 2:\n _b.sent();\n count++;\n _b.label = 3;\n case 3:\n _i++;\n return [3 /*break*/, 1];\n case 4: return [2 /*return*/, count];\n case 5:\n _b.sent();\n return [2 /*return*/, 0];\n case 6: return [2 /*return*/];\n }\n });\n });\n}\n\nvar NO_VERDICT = { isAgent: false, isSearchCrawler: false, signals: [] };\n/**\n * What a widget does on load for AI browsing agents: detect one, advertise the tenant's MCP\n * server in <head>, and - when the tenant opted in - show a detected agent a short note\n * pointing at it, and register the server's tools as WebMCP site tools for the agent in the\n * visitor's own browser. Never throws.\n */\nfunction startAgentDiscovery(options, nav, doc) {\n if (nav === void 0) { nav = typeof navigator !== \"undefined\"\n ? navigator\n : undefined; }\n if (doc === void 0) { doc = typeof document !== \"undefined\" ? document : undefined; }\n var verdict = NO_VERDICT;\n var endpoints;\n var siteTools;\n try {\n verdict = detectBrowsingAgent(nav);\n }\n catch (_a) {\n // A navigator that throws tells us nothing; carry on as a person.\n }\n try {\n endpoints = resolveAgentMcpEndpoints(options.mcp);\n if (endpoints) {\n injectMcpDiscoveryTags(endpoints);\n if (verdict.isAgent && options.notice === true) {\n renderAgentNotice({\n mcpUrl: endpoints.mcpUrl,\n businessName: options.businessName,\n });\n }\n if (options.siteTools === true) {\n siteTools = registerSiteTools({\n endpoints: endpoints,\n doc: doc,\n nav: nav,\n businessName: options.businessName,\n channelId: options.channelId,\n });\n }\n }\n }\n catch (_b) {\n // Discovery is best effort.\n }\n return { verdict: verdict, endpoints: endpoints, siteTools: siteTools };\n}\n\n/** Distinct errors one page load may report; the server drops anything past its own cap too. */\nvar MAX_CLIENT_ERRORS_PER_PAGE = 5;\nvar MAX_MESSAGE_LENGTH = 1000;\nvar MAX_STACK_LENGTH = 8000;\nfunction clip(value, max) {\n if (typeof value !== \"string\") {\n return undefined;\n }\n var trimmed = value.trim();\n return trimmed ? trimmed.slice(0, max) : undefined;\n}\nfunction describeReason(reason) {\n if (reason === undefined || reason === null) {\n return undefined;\n }\n if (typeof reason === \"string\") {\n return reason;\n }\n try {\n var json = JSON.stringify(reason);\n return json && json !== \"{}\" ? json : String(reason);\n }\n catch (_a) {\n return String(reason);\n }\n}\n/**\n * The report for whatever was thrown: an Error's class, message and stack, a string as the\n * message, anything else described as best it can be. Undefined when there is nothing to say.\n */\nfunction describeClientError(input) {\n var error = input.error;\n var isErrorLike = !!error && typeof error === \"object\" && typeof error.message === \"string\";\n var message = clip(isErrorLike ? error.message : describeReason(input.error), MAX_MESSAGE_LENGTH) || clip(input.message, MAX_MESSAGE_LENGTH);\n if (!message) {\n return undefined;\n }\n var report = {\n message: message,\n name: isErrorLike ? clip(error.name, 120) : undefined,\n stack: isErrorLike ? clip(error.stack, MAX_STACK_LENGTH) : undefined,\n kind: input.kind,\n source: input.source,\n version: clip(input.version, 120),\n url: clip(input.url, 2048),\n line: typeof input.line === \"number\" && input.line > 0 ? input.line : undefined,\n column: typeof input.column === \"number\" && input.column > 0 ? input.column : undefined,\n };\n Object.keys(report).forEach(function (key) {\n if (report[key] === undefined) {\n delete report[key];\n }\n });\n return report;\n}\n/**\n * Whether an error came from one of our bundles: its own file, or any frame of its stack,\n * names one of the given script URLs (query strings ignored on both sides). Nothing matches\n * when the bundle URL is unknown, which is deliberate: the npm build inside someone else's\n * React app must not report that app's errors.\n */\nfunction isFromBundle(location, bundles) {\n var urls = bundles.map(function (b) { return stripQueryString(b); }).filter(function (b) { return !!b; });\n if (!urls.length) {\n return false;\n }\n var file = stripQueryString(location.file);\n if (file && urls.indexOf(file) >= 0) {\n return true;\n }\n var stack = location.stack || \"\";\n return !!stack && urls.some(function (url) { return stack.indexOf(url) >= 0; });\n}\n/**\n * POSTs one `error` event, fire-and-forget with keepalive, in the shape the server's\n * WidgetEvents endpoint reads (`data` is the report). Never throws.\n *\n * @returns true when the request was queued.\n */\nfunction sendWidgetErrorEvent(input) {\n if (!input.key || typeof fetch !== \"function\") {\n return false;\n }\n try {\n var body = {\n key: input.key,\n widgetType: input.widgetType,\n events: [\n {\n eventType: \"error\",\n metadata: __assign({ timestamp: new Date().toISOString() }, input.metadata),\n data: input.report,\n },\n ],\n };\n fetch(input.eventsUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n keepalive: true,\n }).catch(function () { return undefined; });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nvar NOOP_REPORTER = {\n report: function () { return false; },\n uninstall: function () { return undefined; },\n};\nfunction dedupeKey(report) {\n return \"\".concat(report.name || \"\", \"|\").concat(report.message.slice(0, 200));\n}\n/**\n * Installs the page's error reporter for a widget: window `error` and `unhandledrejection`\n * listeners filtered to our bundle, one report per distinct error, at most `maxPerPage` per\n * page load. Idempotent per `source` across every copy of the bundle on the page. Never throws.\n */\nfunction installClientErrorReporter(options) {\n var _a;\n try {\n if (!options.key || typeof window === \"undefined\") {\n return NOOP_REPORTER;\n }\n var w = window;\n var registry_1 = (w.__xappErrorReporters = w.__xappErrorReporters || {});\n var existing = registry_1[options.source];\n if (existing) {\n return existing;\n }\n var bundles_1 = options.bundles || [];\n var maxPerPage_1 = (_a = options.maxPerPage) !== null && _a !== void 0 ? _a : MAX_CLIENT_ERRORS_PER_PAGE;\n var seen_1 = {};\n var sent_1 = 0;\n var metadata_1 = function () {\n try {\n return typeof options.metadata === \"function\" ? options.metadata() : options.metadata || {};\n }\n catch (_a) {\n return {};\n }\n };\n var send_1 = function (report) {\n if (!report || sent_1 >= maxPerPage_1) {\n return false;\n }\n var key = dedupeKey(report);\n if (seen_1[key]) {\n return false;\n }\n seen_1[key] = true;\n var queued = sendWidgetErrorEvent({\n eventsUrl: options.eventsUrl,\n key: options.key,\n widgetType: options.widgetType,\n metadata: metadata_1(),\n report: report,\n });\n if (queued) {\n sent_1++;\n }\n return queued;\n };\n var describe_1 = function (error, kind, location) {\n if (location === void 0) { location = {}; }\n var url;\n try {\n url = window.location.href;\n }\n catch (_a) {\n url = undefined;\n }\n return describeClientError({\n error: error,\n message: location.message,\n kind: kind,\n source: options.source,\n version: options.version,\n url: url,\n line: location.line,\n column: location.column,\n });\n };\n var onError_1 = function (event) {\n var _a;\n try {\n var stack = (_a = event.error) === null || _a === void 0 ? void 0 : _a.stack;\n if (!isFromBundle({ file: event.filename, stack: typeof stack === \"string\" ? stack : undefined }, bundles_1)) {\n return;\n }\n send_1(describe_1(event.error, \"error\", { message: event.message, line: event.lineno, column: event.colno }));\n }\n catch (_b) {\n // Reporting must never break the page.\n }\n };\n var onRejection_1 = function (event) {\n try {\n var reason = event.reason;\n var stack = reason === null || reason === void 0 ? void 0 : reason.stack;\n if (!isFromBundle({ stack: typeof stack === \"string\" ? stack : undefined }, bundles_1)) {\n return;\n }\n send_1(describe_1(reason, \"unhandledrejection\"));\n }\n catch (_a) {\n // Reporting must never break the page.\n }\n };\n window.addEventListener(\"error\", onError_1);\n window.addEventListener(\"unhandledrejection\", onRejection_1);\n var reporter_1 = {\n report: function (error, kind) {\n if (kind === void 0) { kind = \"boundary\"; }\n try {\n return send_1(describe_1(error, kind));\n }\n catch (_a) {\n return false;\n }\n },\n uninstall: function () {\n try {\n window.removeEventListener(\"error\", onError_1);\n window.removeEventListener(\"unhandledrejection\", onRejection_1);\n if (registry_1[options.source] === reporter_1) {\n delete registry_1[options.source];\n }\n }\n catch (_a) {\n // Nothing left to undo.\n }\n },\n };\n registry_1[options.source] = reporter_1;\n return reporter_1;\n }\n catch (_b) {\n return NOOP_REPORTER;\n }\n}\n\n/** Page params whose VALUES the load event may send, each as its own metadata field. */\nvar LOAD_EVENT_PAGE_PARAMETERS = __spreadArray(__spreadArray([], ATTRIBUTION_PARAMETERS, true), AI_REFERRAL_PARAMETERS, true);\nvar DEFAULT_WIDGET_EVENTS_ORIGIN = \"https://api.xapp.ai\";\nvar EVENTS_PATH = \"/cms/widget/events\";\nvar MAX_REFERRER_LENGTH = 500;\nvar MAX_VALUE_LENGTH = 255;\nvar MAX_OTHER_KEYS = 20;\nvar MAX_OTHER_KEYS_LENGTH = 300;\nvar PLAIN_KEY = /^[A-Za-z0-9_.[\\]-]{1,64}$/;\n/**\n * The page global XAPP's own web scraper sets before any page script runs, so the crawler's\n * widget events are reported as `internal` traffic instead of as an AI agent. The crawler cannot\n * mark these events with a request header the way it marks the widget script load: a custom\n * header on the widget's cross-origin fetch would trigger a CORS preflight.\n */\nvar INTERNAL_TRAFFIC_GLOBAL = \"__xappInternal\";\nvar INTERNAL_TRAFFIC_VALUE = /^[a-z][a-z-]{0,31}$/;\n/** The page's internal traffic mark (e.g. `crawler`), or undefined. Never throws. */\nfunction readInternalTrafficMark() {\n try {\n var value = window[INTERNAL_TRAFFIC_GLOBAL];\n return typeof value === \"string\" && INTERNAL_TRAFFIC_VALUE.test(value) ? value : undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\nfunction isValidValue(value) {\n // eslint-disable-next-line no-control-regex\n return value.length <= MAX_VALUE_LENGTH && !/[<>\"'\\x00-\\x1f]/.test(value);\n}\nfunction pageFields(pageUrl) {\n var url;\n try {\n url = new URL(pageUrl);\n }\n catch (_a) {\n return {};\n }\n var fields = { currentUrl: url.origin + url.pathname };\n var otherKeys = [];\n var otherLength = 0;\n url.searchParams.forEach(function (value, name) {\n if (LOAD_EVENT_PAGE_PARAMETERS.indexOf(name) >= 0) {\n if (fields[name] === undefined && value && isValidValue(value)) {\n fields[name] = value;\n }\n return;\n }\n if (!PLAIN_KEY.test(name) || otherKeys.indexOf(name) >= 0) {\n return;\n }\n var added = (otherKeys.length ? 1 : 0) + name.length;\n if (otherKeys.length >= MAX_OTHER_KEYS || otherLength + added > MAX_OTHER_KEYS_LENGTH) {\n return;\n }\n otherKeys.push(name);\n otherLength += added;\n });\n if (otherKeys.length) {\n fields.pageQueryKeys = otherKeys.join(\",\");\n }\n return fields;\n}\n/**\n * The load event's page, browser and agent metadata. Callers add their own identity fields\n * (sessionId, userId, formId). Never throws.\n */\nfunction buildLoadEventMetadata(input) {\n var _a;\n var metadata = pageFields(input.pageUrl);\n var nav = input.nav;\n try {\n if (nav === null || nav === void 0 ? void 0 : nav.userAgent)\n metadata.userAgent = nav.userAgent;\n metadata.webdriver = (nav === null || nav === void 0 ? void 0 : nav.webdriver) === true ? \"1\" : \"0\";\n var brands = (_a = nav === null || nav === void 0 ? void 0 : nav.userAgentData) === null || _a === void 0 ? void 0 : _a.brands;\n if (brands && brands.length) {\n metadata.uaBrands = brands\n .map(function (b) { return \"\".concat(b.brand, \"/\").concat(String(b.version).split(\".\")[0]); })\n .join(\"|\");\n }\n if (nav === null || nav === void 0 ? void 0 : nav.language)\n metadata.language = nav.language;\n }\n catch (_b) {\n // A navigator that throws contributes nothing further.\n }\n var referrer = stripQueryString(input.referrer);\n if (referrer)\n metadata.referrer = referrer.slice(0, MAX_REFERRER_LENGTH);\n metadata.agentVerdict = input.verdict.isAgent ? \"1\" : \"0\";\n if (input.verdict.signals.length) {\n metadata.agentSignals = input.verdict.signals.join(\",\");\n }\n var internal = readInternalTrafficMark();\n if (internal)\n metadata.internal = internal;\n try {\n metadata.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n catch (_c) {\n // Intl unavailable - skip timezone\n }\n if (input.screen) {\n metadata.screenWidth = String(input.screen.width);\n metadata.screenHeight = String(input.screen.height);\n }\n if (input.viewport) {\n metadata.viewportWidth = String(input.viewport.width);\n metadata.viewportHeight = String(input.viewport.height);\n }\n return metadata;\n}\n/**\n * Where the widget events endpoint lives. A stentor-api run URL\n * (`https://api.xapp.ai/apps/{appId}/run`) names it by its origin - the same derivation the\n * form widget's StentorApi uses. Anything else (a chat router websocket, the agent server)\n * is not stentor-api, so the production API is used.\n */\nfunction resolveWidgetEventsUrl(serverUrl) {\n if (serverUrl) {\n try {\n var url = new URL(serverUrl);\n if ((url.protocol === \"https:\" || url.protocol === \"http:\") &&\n /\\/apps\\//.test(url.pathname)) {\n return \"\".concat(url.origin).concat(EVENTS_PATH);\n }\n }\n catch (_a) {\n // fall through\n }\n }\n return \"\".concat(DEFAULT_WIDGET_EVENTS_ORIGIN).concat(EVENTS_PATH);\n}\n/**\n * Claims this page load's `load` event for a widget type. True the first time per page load,\n * across every copy of the bundle on the page; false after that.\n */\nfunction claimPageLoadEvent(widgetType) {\n try {\n var w = window;\n var claimed = (w.__xappLoadEvents = w.__xappLoadEvents || {});\n if (claimed[widgetType]) {\n return false;\n }\n claimed[widgetType] = true;\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n/**\n * POSTs the `load` event, fire-and-forget with keepalive. Never throws.\n *\n * @returns true when the request was queued.\n */\nfunction sendWidgetLoadEvent(input) {\n if (!input.key || typeof fetch !== \"function\") {\n return false;\n }\n try {\n var body = {\n key: input.key,\n widgetType: input.widgetType,\n events: [\n {\n eventType: \"load\",\n metadata: __assign({ timestamp: new Date().toISOString() }, input.metadata),\n data: {},\n },\n ],\n };\n fetch(input.eventsUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n keepalive: true,\n }).catch(function () { return undefined; });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n\n/**\n * Stop the host page scrolling behind an open overlay.\n *\n * `body { overflow: hidden }` is the obvious way to do this, and is what both widgets used\n * to do — but **iOS Safari ignores `overflow: hidden` on the body**, so the customer's page\n * carried on scrolling under the modal. The technique that does work there is to take the\n * body out of flow at a negative offset equal to the current scroll position, then put it\n * back and re-scroll to that exact position on release.\n *\n * Reference counted rather than a plain on/off flag, and the count lives on the `<body>`\n * element rather than in module scope. That is deliberate: the chat widget's `FormModal`\n * loads the **standalone** form widget bundle, which carries its own copy of this module,\n * so the two overlays that can be open at once are not sharing any JS state. With a module\n * counter, the second lock would read the already-pinned scroll position (which the browser\n * reports as 0), the first release would unpin the body while the second overlay was still\n * open, and the second release would then re-apply `position: fixed` and leave the host page\n * stuck. The DOM is the only thing both bundles can agree on.\n */\n/** How many overlays currently hold the lock. Absent means unlocked. */\nvar COUNT_ATTRIBUTE$1 = \"data-xapp-scroll-lock\";\n/** What to put back when the last one lets go, as JSON. */\nvar RESTORE_ATTRIBUTE = \"data-xapp-scroll-lock-restore\";\nvar PINNED_PROPERTIES = [\"position\", \"top\", \"left\", \"right\", \"width\", \"overflow\"];\nfunction readCount$1(body) {\n var count = Number(body.getAttribute(COUNT_ATTRIBUTE$1));\n return Number.isFinite(count) && count > 0 ? count : 0;\n}\nfunction captureRestorePoint(body) {\n var inlineStyles = PINNED_PROPERTIES.reduce(function (styles, property) {\n styles[property] = body.style.getPropertyValue(property);\n return styles;\n }, {});\n return { scrollY: window.scrollY || window.pageYOffset || 0, inlineStyles: inlineStyles };\n}\nfunction takeRestorePoint(body) {\n var serialized = body.getAttribute(RESTORE_ATTRIBUTE);\n body.removeAttribute(RESTORE_ATTRIBUTE);\n try {\n var parsed = JSON.parse(serialized || \"\");\n if (parsed && typeof parsed.scrollY === \"number\" && parsed.inlineStyles) {\n return parsed;\n }\n }\n catch (_a) {\n // Fall through: something else rewrote the attribute. Better to clear our own\n // properties and leave the page usable than to throw and leave it pinned.\n }\n return { scrollY: 0, inlineStyles: {} };\n}\n/**\n * Lock the body and return the release function.\n *\n * The returned function is idempotent — calling it twice is a no-op, which matters because\n * React StrictMode runs an effect's cleanup more than once.\n */\nfunction lockBodyScroll() {\n if (typeof document === \"undefined\" || typeof window === \"undefined\") {\n return function () { return undefined; };\n }\n var body = document.body;\n if (readCount$1(body) === 0) {\n var restorePoint = captureRestorePoint(body);\n body.setAttribute(RESTORE_ATTRIBUTE, JSON.stringify(restorePoint));\n body.style.position = \"fixed\";\n body.style.top = \"-\".concat(restorePoint.scrollY, \"px\");\n body.style.left = \"0\";\n body.style.right = \"0\";\n body.style.width = \"100%\";\n // Redundant next to `position: fixed`, but harmless, and it keeps the behaviour the\n // widgets already had on the browsers that do honour it.\n body.style.overflow = \"hidden\";\n }\n body.setAttribute(COUNT_ATTRIBUTE$1, String(readCount$1(body) + 1));\n var released = false;\n return function releaseBodyScroll() {\n if (released) {\n return;\n }\n released = true;\n var remaining = readCount$1(body) - 1;\n if (remaining > 0) {\n body.setAttribute(COUNT_ATTRIBUTE$1, String(remaining));\n return;\n }\n if (remaining < 0) {\n return;\n }\n body.removeAttribute(COUNT_ATTRIBUTE$1);\n var _a = takeRestorePoint(body), scrollY = _a.scrollY, inlineStyles = _a.inlineStyles;\n PINNED_PROPERTIES.forEach(function (property) {\n if (inlineStyles[property]) {\n body.style.setProperty(property, inlineStyles[property]);\n }\n else {\n body.style.removeProperty(property);\n }\n });\n // An empty `style=\"\"` on the host page's body is untidy and is not what we found.\n if (!body.style.length) {\n body.removeAttribute(\"style\");\n }\n window.scrollTo(0, scrollY);\n };\n}\n/**\n * Lock the body scroll for as long as the calling component is mounted.\n *\n * The cleanup runs on unmount, so a modal that disappears without a clean close — a route\n * change, a parent re-render, an error boundary — still leaves the page scrollable.\n */\nfunction useBodyScrollLock(enabled) {\n if (enabled === void 0) { enabled = true; }\n react.useEffect(function () {\n if (!enabled) {\n return undefined;\n }\n return lockBodyScroll();\n }, [enabled]);\n}\n\n/**\n * Publish the visual viewport's geometry as CSS custom properties, so overlays can size\n * themselves around the soft keyboard.\n *\n * We are an **embedded** widget: the customer owns the host page's `<meta name=\"viewport\">`,\n * so we cannot add `interactive-widget=resizes-content` and let the browser solve this for\n * us. Reading `window.visualViewport` ourselves is the only mechanism we control. (Injecting\n * or mutating the host's viewport meta is not an option — it is not ours, and breaking it\n * breaks the whole page in ways nobody would attribute to us.)\n *\n * Three properties are published on `<html>`:\n *\n * --xapp-viewport-height the visible height, in px\n * --xapp-viewport-offset-top how far the visual viewport has been scrolled down within\n * the layout viewport — nonzero on iOS when the keyboard\n * pushes the page up\n * --xapp-keyboard-inset layout height minus visual height: how much the keyboard\n * (or any other browser UI) is covering\n *\n * `--xapp-keyboard-inset` is the one worth having. It is what a `padding-bottom` wants, and\n * deriving it here means the consuming CSS does not have to do arithmetic across two\n * variables that update at slightly different moments.\n *\n * Reference counted on the DOM, for the same reason `bodyScrollLock` is: chat-widget's\n * `FormModal` loads the **standalone** form-widget bundle, which carries its own copy of\n * this module. Two independent copies can be live at once, and a module-scope counter would\n * not see across them. Without counting, closing the form modal while the chat panel is\n * still open (with the keyboard still up) would clear the properties out from under the\n * panel and snap it back to its fallback height mid-interaction.\n */\nvar HEIGHT_PROPERTY = \"--xapp-viewport-height\";\nvar OFFSET_TOP_PROPERTY = \"--xapp-viewport-offset-top\";\nvar KEYBOARD_INSET_PROPERTY = \"--xapp-keyboard-inset\";\n/** How many subscribers currently want these properties maintained. */\nvar COUNT_ATTRIBUTE = \"data-xapp-viewport-subscribers\";\n/**\n * Below this, a shrunken viewport is treated as browser chrome rather than a keyboard.\n * Address bars collapse and expand by ~60-90px during normal scrolling, and reacting to\n * that would make the layout twitch while the user is only reading.\n */\nvar KEYBOARD_THRESHOLD_PX = 120;\nfunction readCount(root) {\n var count = Number(root.getAttribute(COUNT_ATTRIBUTE));\n return Number.isFinite(count) && count > 0 ? count : 0;\n}\n/**\n * Write the current geometry to `<html>`.\n *\n * Deliberately does nothing when `visualViewport` is unavailable: the consuming CSS falls\n * back to `100dvh`, which is correct-ish and certainly better than a zero height. Publishing\n * `0px` would collapse the widget entirely — a worse failure than the one being fixed.\n */\nfunction publish(root) {\n var viewport = typeof window === \"undefined\" ? undefined : window.visualViewport;\n if (!viewport) {\n return;\n }\n var height = viewport.height, offsetTop = viewport.offsetTop;\n if (!(height > 0)) {\n // Mid-transition, or a browser reporting nonsense. Keep the last good values.\n return;\n }\n // window.innerHeight is the LAYOUT viewport, which the keyboard does not shrink on iOS.\n // The difference between the two is the occluded strip.\n var layoutHeight = window.innerHeight || height;\n var rawInset = Math.max(0, layoutHeight - height);\n var inset = rawInset >= KEYBOARD_THRESHOLD_PX ? rawInset : 0;\n root.style.setProperty(HEIGHT_PROPERTY, \"\".concat(Math.round(height), \"px\"));\n root.style.setProperty(OFFSET_TOP_PROPERTY, \"\".concat(Math.round(offsetTop), \"px\"));\n root.style.setProperty(KEYBOARD_INSET_PROPERTY, \"\".concat(Math.round(inset), \"px\"));\n}\nfunction clear(root) {\n root.style.removeProperty(HEIGHT_PROPERTY);\n root.style.removeProperty(OFFSET_TOP_PROPERTY);\n root.style.removeProperty(KEYBOARD_INSET_PROPERTY);\n}\n/**\n * Start publishing viewport geometry. Returns a release function.\n *\n * Imperative twin of {@link useVisualViewportProperties}, for callers outside React.\n */\nfunction trackVisualViewport() {\n if (typeof document === \"undefined\") {\n return function () { return undefined; };\n }\n var root = document.documentElement;\n root.setAttribute(COUNT_ATTRIBUTE, String(readCount(root) + 1));\n publish(root);\n var viewport = typeof window === \"undefined\" ? undefined : window.visualViewport;\n var frame;\n var onChange = function () {\n // These fire many times per second through the keyboard animation. Coalescing to one\n // write per frame keeps us off the layout-thrash path.\n if (frame !== undefined) {\n return;\n }\n frame = window.requestAnimationFrame(function () {\n frame = undefined;\n publish(root);\n });\n };\n // `scroll` matters as much as `resize`: on iOS the keyboard scrolls the visual viewport\n // within the layout viewport, and offsetTop only changes on that event.\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"resize\", onChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"scroll\", onChange);\n var released = false;\n return function () {\n if (released) {\n return;\n }\n released = true;\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"resize\", onChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"scroll\", onChange);\n if (frame !== undefined) {\n window.cancelAnimationFrame(frame);\n frame = undefined;\n }\n var remaining = readCount(root) - 1;\n if (remaining > 0) {\n root.setAttribute(COUNT_ATTRIBUTE, String(remaining));\n return;\n }\n root.removeAttribute(COUNT_ATTRIBUTE);\n clear(root);\n };\n}\n/**\n * Publish viewport geometry for as long as this component is mounted.\n *\n * @param enabled pass `false` to opt out — e.g. above the mobile breakpoint, where there is\n * no soft keyboard to work around and the desktop sizing should stand.\n */\nfunction useVisualViewportProperties(enabled) {\n if (enabled === void 0) { enabled = true; }\n react.useEffect(function () {\n if (!enabled) {\n return undefined;\n }\n return trackVisualViewport();\n }, [enabled]);\n}\n/** Read the published inset, or 0 if nothing has published one. */\nfunction readInset() {\n var value = getComputedStyle(document.documentElement).getPropertyValue(KEYBOARD_INSET_PROPERTY);\n var inset = parseFloat(value);\n return Number.isFinite(inset) ? inset : 0;\n}\nfunction scrollIntoViewIfPossible(element) {\n if (element && \"scrollIntoView\" in element) {\n // block: \"nearest\" scrolls the minimum needed, so a field already in view does not\n // jump. Anything more aggressive fights the browser's own attempt and overshoots.\n element.scrollIntoView({ block: \"nearest\", behavior: \"smooth\" });\n }\n}\n/**\n * Scroll whatever the user has focused back into view when the keyboard covers it.\n *\n * Browsers mostly do this themselves, but not reliably inside a `position: fixed` overlay —\n * which is exactly what both widgets are. The failure looks like tapping the last field on a\n * step and having it disappear behind the keyboard.\n *\n * **The ordering is the whole problem.** On a device the sequence is: focus lands, *then*\n * the keyboard opens, *then* the viewport events fire. So reading the inset inside the\n * `focusin` handler sees `0` and does nothing — on precisely the case this exists for, the\n * first tap into a field near the bottom of a step. It has to react to the inset becoming\n * nonzero and scroll whatever is focused at that moment.\n *\n * Both directions are covered: focusing while the keyboard is already up (tabbing between\n * fields) scrolls immediately, and a keyboard that opens after focus scrolls on the\n * transition. Nothing happens when the keyboard closes, or for a mouse user on desktop where\n * the inset never leaves `0`.\n */\nfunction useScrollFocusedIntoView(enabled) {\n if (enabled === void 0) { enabled = true; }\n react.useEffect(function () {\n if (!enabled || typeof document === \"undefined\") {\n return undefined;\n }\n // Seeded from the current value so a hook mounted while the keyboard is already up\n // does not read that as a fresh transition and scroll unbidden.\n var lastInset = readInset();\n var onFocusIn = function (event) {\n if (readInset() > 0) {\n scrollIntoViewIfPossible(event.target);\n }\n };\n var onViewportChange = function () {\n // One frame late: the property is published from a rAF callback, so reading it\n // synchronously here would see the previous value. This assumes the publishing\n // hook mounted first, which it does at both call sites - and even if it did not,\n // a browser fires resize AND scroll for a keyboard, so the second event catches\n // what the first missed.\n window.requestAnimationFrame(function () {\n var inset = readInset();\n var opened = lastInset <= 0 && inset > 0;\n lastInset = inset;\n if (opened) {\n scrollIntoViewIfPossible(document.activeElement);\n }\n });\n };\n var viewport = typeof window === \"undefined\" ? undefined : window.visualViewport;\n document.addEventListener(\"focusin\", onFocusIn);\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"resize\", onViewportChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.addEventListener(\"scroll\", onViewportChange);\n return function () {\n document.removeEventListener(\"focusin\", onFocusIn);\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"resize\", onViewportChange);\n viewport === null || viewport === void 0 ? void 0 : viewport.removeEventListener(\"scroll\", onViewportChange);\n };\n }, [enabled]);\n}\n\n/**\n * A fake soft keyboard, for testing keyboard handling on a machine that has none.\n *\n * **This is a development harness, not a verifier.** It substitutes a stand-in for\n * `window.visualViewport` and fires the events a real browser would, so our own code cannot\n * tell the difference. What it proves is that the hook subscribes, does the arithmetic, and\n * that the consuming CSS responds. What it cannot prove is that a real iOS or Android\n * keyboard produces these events at all — iOS scrolls the visual viewport within the layout\n * viewport, Android may resize the layout viewport itself depending on the host page's\n * viewport meta, and as an embedded widget we do not control that meta. A mock we wrote can\n * only ever confirm our own assumptions.\n *\n * So: use this to iterate on a desktop, and verify on a real device with it switched off,\n * where the same instrumentation reads the numbers the device actually reports.\n *\n * Exported from the package because the Storybook stories that use it live in two different\n * packages, and duplicating a fake this fiddly is how the two copies drift apart.\n */\n/**\n * Roughly what the common keyboards occupy.\n *\n * The landscape entry is not optional garnish: a portrait keyboard is ~336px, and a\n * landscape phone viewport is only ~340px tall, so simulating a portrait keyboard sideways\n * leaves 4px of usable space and every layout assertion fails for a reason that has nothing\n * to do with the layout. Landscape keyboards are genuinely shorter.\n */\nvar KEYBOARD_PRESETS = {\n \"iOS (iPhone 14)\": 336,\n \"Android (Pixel 7)\": 312,\n \"iOS with autocomplete bar\": 380,\n \"Compact / numeric\": 260,\n \"Landscape phone\": 200,\n};\n/**\n * Stands in for VisualViewport. Only the members our code reads are real; the rest satisfy\n * the structural type so this can be assigned over `window.visualViewport`.\n */\nvar SimulatedViewport = /** @class */ (function () {\n function SimulatedViewport(height, width) {\n this.offsetTop = 0;\n this.offsetLeft = 0;\n this.pageTop = 0;\n this.pageLeft = 0;\n this.scale = 1;\n this.onresize = null;\n this.onscroll = null;\n this.listeners = {};\n this.height = height;\n this.width = width;\n }\n SimulatedViewport.prototype.addEventListener = function (type, listener) {\n var _a;\n ((_a = this.listeners)[type] || (_a[type] = new Set())).add(listener);\n };\n SimulatedViewport.prototype.removeEventListener = function (type, listener) {\n var _a;\n (_a = this.listeners[type]) === null || _a === void 0 ? void 0 : _a.delete(listener);\n };\n SimulatedViewport.prototype.dispatchEvent = function (event) {\n var _a;\n (_a = this.listeners[event.type]) === null || _a === void 0 ? void 0 : _a.forEach(function (listener) { return listener(event); });\n return true;\n };\n SimulatedViewport.prototype.fire = function () {\n // A real browser fires both, and offsetTop only lands on the scroll one.\n this.dispatchEvent(new Event(\"resize\"));\n this.dispatchEvent(new Event(\"scroll\"));\n };\n return SimulatedViewport;\n}());\n/**\n * Install the simulator, replacing `window.visualViewport` until `destroy()`.\n *\n * The real property is a readonly accessor on `window`, so this redefines it and puts the\n * original descriptor back on teardown. Confined to Storybook — nothing ships with this.\n */\nfunction installKeyboardSimulator() {\n var original = Object.getOwnPropertyDescriptor(window, \"visualViewport\");\n var layoutHeight = window.innerHeight;\n var simulated = new SimulatedViewport(layoutHeight, window.innerWidth);\n Object.defineProperty(window, \"visualViewport\", {\n value: simulated,\n writable: true,\n configurable: true,\n });\n return {\n open: function (height) {\n simulated.height = Math.max(0, layoutHeight - height);\n // iOS pushes the visual viewport down within the layout viewport as well as\n // shrinking it. Mirroring that is what makes offsetTop worth reading.\n simulated.offsetTop = height / 2;\n simulated.fire();\n },\n close: function () {\n simulated.height = layoutHeight;\n simulated.offsetTop = 0;\n simulated.fire();\n },\n destroy: function () {\n if (original) {\n Object.defineProperty(window, \"visualViewport\", original);\n }\n else {\n delete window.visualViewport;\n }\n },\n };\n}\n\n/**\n * Wraps a widget story with soft-keyboard instrumentation.\n *\n * Two modes, and the second is the one that matters:\n *\n * 1. **Simulate on** (desktop): substitutes a fake `visualViewport`, so you can raise and\n * lower a keyboard of a chosen height and watch the layout respond. Good for iterating.\n * It proves our code reacts correctly to the events; it cannot prove a real keyboard\n * produces them.\n *\n * 2. **Simulate off** (a real phone): leaves the browser alone. Tap a field, get the real\n * keyboard, and the readout shows what the device actually reports — which is the number\n * we have never had. If the fix misbehaves, this is what says why.\n *\n * Defaults to off so that opening the story on a phone does the right thing without anyone\n * having to remember to switch it.\n */\nvar READOUT_KEYS = [\n [\"--xapp-viewport-height\", \"viewport height\"],\n [\"--xapp-keyboard-inset\", \"keyboard inset\"],\n [\"--xapp-viewport-offset-top\", \"offset top\"],\n];\nfunction readMetrics() {\n var viewport = window.visualViewport;\n var style = getComputedStyle(document.documentElement);\n var published = {};\n READOUT_KEYS.forEach(function (_a) {\n var property = _a[0];\n published[property] = style.getPropertyValue(property).trim() || \"(unset)\";\n });\n return {\n visualHeight: viewport ? Math.round(viewport.height) : undefined,\n layoutHeight: window.innerHeight,\n offsetTop: viewport ? Math.round(viewport.offsetTop) : undefined,\n scale: viewport === null || viewport === void 0 ? void 0 : viewport.scale,\n published: published,\n };\n}\nvar KeyboardTestRig = function (_a) {\n var _b;\n var children = _a.children;\n var _c = react.useState(false), simulate = _c[0], setSimulate = _c[1];\n var _d = react.useState(KEYBOARD_PRESETS[\"iOS (iPhone 14)\"]), height = _d[0], setHeight = _d[1];\n var _e = react.useState(false), open = _e[0], setOpen = _e[1];\n var _f = react.useState(function () { return readMetrics(); }), metrics = _f[0], setMetrics = _f[1];\n var _g = react.useState(), simulator = _g[0], setSimulator = _g[1];\n /**\n * Whether the simulator is actually installed, as opposed to merely requested.\n *\n * The widget subscribes to whatever `window.visualViewport` was when it mounted, so\n * swapping the property under a mounted widget changes nothing — it is still listening\n * to the old object. The children are therefore unmounted while the swap happens and\n * remounted afterwards, against whichever viewport is now current. Found the hard way:\n * without this the toolbar worked, the readout updated, and the layout never moved.\n */\n var _h = react.useState(false), installed = _h[0], setInstalled = _h[1];\n // Poll rather than subscribe: the point is to observe what the page is doing, including\n // any update path we forgot to wire, so this deliberately does not depend on our own\n // event handling being correct.\n react.useEffect(function () {\n var id = window.setInterval(function () { return setMetrics(readMetrics()); }, 100);\n return function () { return window.clearInterval(id); };\n }, []);\n react.useEffect(function () {\n if (!simulate) {\n return undefined;\n }\n var active = installKeyboardSimulator();\n setSimulator(active);\n setInstalled(true);\n return function () {\n active.close();\n active.destroy();\n setSimulator(undefined);\n setInstalled(false);\n setOpen(false);\n };\n }, [simulate]);\n react.useEffect(function () {\n if (!simulator) {\n return;\n }\n if (open) {\n simulator.open(height);\n }\n else {\n simulator.close();\n }\n }, [simulator, open, height]);\n var hasRealViewport = typeof window !== \"undefined\" && !!window.visualViewport;\n return (jsxRuntime.jsxs(\"div\", { style: { font: \"13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace\" }, children: [jsxRuntime.jsxs(\"div\", { style: {\n position: \"fixed\",\n top: 0,\n left: 0,\n right: 0,\n zIndex: 2147483647,\n background: \"#14181a\",\n color: \"#edf1f1\",\n padding: \"8px 10px\",\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: \"10px\",\n alignItems: \"center\",\n }, children: [jsxRuntime.jsxs(\"label\", { style: { display: \"flex\", gap: 6, alignItems: \"center\" }, children: [jsxRuntime.jsx(\"input\", { type: \"checkbox\", checked: simulate, onChange: function (event) { return setSimulate(event.target.checked); } }), \"simulate keyboard\"] }), jsxRuntime.jsxs(\"button\", { type: \"button\", disabled: !simulate, onClick: function () { return setOpen(function (value) { return !value; }); }, \n // Do not take focus. On a device the keyboard opens *because* a field was\n // focused, and the field keeps focus throughout. A toolbar button that\n // steals it makes the interesting case - does the focused field survive\n // the keyboard arriving? - impossible to reproduce here.\n onMouseDown: function (event) { return event.preventDefault(); }, style: { padding: \"4px 10px\" }, children: [open ? \"hide\" : \"show\", \" keyboard\"] }), jsxRuntime.jsx(\"select\", { disabled: !simulate, value: height, onChange: function (event) { return setHeight(Number(event.target.value)); }, children: Object.entries(KEYBOARD_PRESETS).map(function (_a) {\n var label = _a[0], value = _a[1];\n return (jsxRuntime.jsxs(\"option\", { value: value, children: [label, \" \\u2014 \", value, \"px\"] }, label));\n }) }), jsxRuntime.jsxs(\"span\", { style: { opacity: 0.75 }, children: [\"visual \", (_b = metrics.visualHeight) !== null && _b !== void 0 ? _b : \"n/a\", \" / layout \", metrics.layoutHeight, metrics.offsetTop !== undefined && \" / offsetTop \".concat(metrics.offsetTop), metrics.scale !== undefined && \" / scale \".concat(metrics.scale.toFixed(2))] }), READOUT_KEYS.map(function (_a) {\n var property = _a[0], label = _a[1];\n return (jsxRuntime.jsxs(\"span\", { style: { opacity: 0.75 }, children: [label, \": \", jsxRuntime.jsx(\"strong\", { children: metrics.published[property] })] }, property));\n }), !hasRealViewport && !simulate && (jsxRuntime.jsx(\"span\", { style: { color: \"#d9a45f\" }, children: \"this browser has no visualViewport \\u2014 widgets fall back to 100dvh\" }))] }), installed === simulate && (jsxRuntime.jsx(\"div\", { children: children }, simulate ? \"simulated\" : \"real\")), simulate && open && (jsxRuntime.jsxs(\"div\", { style: {\n position: \"fixed\",\n bottom: 0,\n left: 0,\n right: 0,\n height: height,\n zIndex: 2147483646,\n background: \"repeating-linear-gradient(45deg, #2b3336 0 12px, #222a2b 12px 24px)\",\n color: \"#7f8c8e\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n borderTop: \"2px solid #58c4ac\",\n }, children: [\"simulated keyboard \\u2014 \", height, \"px\"] }))] }));\n};\n\n/**\n * Test-lead flag, shared by every widget surface.\n *\n * Studio opens a business's booking page with `?xa_test=1` so the owner can send\n * themselves a test lead. The booking page records that in sessionStorage — never\n * localStorage, so a later real visit is never tagged — and every submission from\n * that page view carries `xaTest: true`. stentor-api keeps such leads out of stats,\n * billing counts, CRM pushes and Google conversions.\n */\n/** The booking-page query parameter Studio sets. */\nvar TEST_LEAD_PARAMETER = \"xa_test\";\n/** The sessionStorage key the booking page writes the flag to. */\nvar TEST_LEAD_STORAGE_KEY = \"xa_test\";\n/** The attribute sent with a lead submission. */\nvar TEST_LEAD_ATTRIBUTE = \"xaTest\";\n/** True when the current browser session is a test-lead page view. */\nfunction isTestLeadSession() {\n try {\n return sessionStorage.getItem(TEST_LEAD_STORAGE_KEY) === \"1\";\n }\n catch (_a) {\n // Storage can be blocked by the browser; treat that as a real visit.\n return false;\n }\n}\n/**\n * Tags the attributes as a test lead when the session flag is set. A test must\n * never be counted as Google traffic, so any `rwg_token` is dropped as well.\n */\nfunction addTestLeadAttribute(attributes) {\n if (isTestLeadSession()) {\n attributes[TEST_LEAD_ATTRIBUTE] = true;\n delete attributes[\"rwg_token\"];\n }\n return attributes;\n}\n\n/**\n * Quicker configurable uuid\n *\n * @export\n * @returns {string}\n */\nfunction uuid() {\n var d = new Date().getTime();\n var newUuid = \"xxxxxxxx-xxxx-65xx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, function (c) {\n /* tslint:disable:no-magic-numbers */\n /* tslint:disable:no-bitwise */\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n /* tslint:enable:no-magic-numbers */\n /* tslint:disable:no-bitwise */\n });\n return newUuid;\n}\n\n/**\n * Who is on the page, shared by every XAPP widget on it.\n *\n * - `visitorId`: one per browser and site, kept in localStorage. The form widget's existing user\n * id is adopted when there is one, so a returning visitor keeps the id their leads carry.\n * - `visitId`: one per visit. A visit ends after VISIT_IDLE_MS without a widget event, the same\n * rule as a Google Analytics session, so the chat and form widgets on one page - and the pages a\n * visitor clicks through - share it.\n *\n * Both are kept in the host page's localStorage, which every widget bundle on the page reads, so\n * a chat and a form loaded as separate scripts agree. When storage throws (private mode, a\n * sandboxed frame, a storage policy) a page global stands in, so the page at least agrees with\n * itself. Never throws.\n */\nvar VISITOR_ID_STORAGE_KEY = \"__xapp_visitor_id\";\nvar VISIT_STORAGE_KEY = \"__xapp_visit\";\n/** The form widget's user id key before the shared visitor id existed. */\nvar LEGACY_FORM_USER_ID_KEY = \"__xapp_form_user_id\";\n/** A visit ends after this long without a widget event. */\nvar VISIT_IDLE_MS = 30 * 60 * 1000;\nvar ID = /^[A-Za-z0-9_-]{8,64}$/;\nfunction fallback() {\n try {\n var w = window;\n return (w.__xappVisitIdentity = w.__xappVisitIdentity || {});\n }\n catch (_a) {\n return {};\n }\n}\nfunction read(key) {\n try {\n return localStorage.getItem(key) || undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\n/** True when it was stored. */\nfunction write(key, value) {\n try {\n localStorage.setItem(key, value);\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction asId(value) {\n return value && ID.test(value) ? value : undefined;\n}\n/** This browser's visitor id on this site, minted on first use. */\nfunction visitorId() {\n var stored = asId(read(VISITOR_ID_STORAGE_KEY));\n if (stored) {\n return stored;\n }\n var page = fallback();\n var id = page.visitorId || asId(read(LEGACY_FORM_USER_ID_KEY)) || uuid();\n if (!write(VISITOR_ID_STORAGE_KEY, id)) {\n page.visitorId = id;\n }\n return id;\n}\nfunction parseVisit(raw) {\n if (!raw) {\n return undefined;\n }\n try {\n var visit = JSON.parse(raw);\n return visit && asId(visit.id) && typeof visit.at === \"number\"\n ? visit\n : undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\n/**\n * The visitor and their current visit, extending the visit to `now`. Call it for each event the\n * widget sends: the call is what keeps the visit alive.\n */\nfunction visitIdentity(now) {\n if (now === void 0) { now = Date.now(); }\n var page = fallback();\n var current = parseVisit(read(VISIT_STORAGE_KEY)) || page.visit;\n var active = current && current.at <= now && now - current.at <= VISIT_IDLE_MS;\n var visit = { id: active && current ? current.id : uuid(), at: now };\n if (!write(VISIT_STORAGE_KEY, JSON.stringify(visit))) {\n page.visit = visit;\n }\n return { visitorId: visitorId(), visitId: visit.id };\n}\n\nexports.AGENT_NOTICE_HIDDEN_ID = AGENT_NOTICE_HIDDEN_ID;\nexports.AGENT_NOTICE_ID = AGENT_NOTICE_ID;\nexports.AGENT_UA_TOKENS = AGENT_UA_TOKENS;\nexports.AI_REFERRAL_PARAMETERS = AI_REFERRAL_PARAMETERS;\nexports.ATTRIBUTION_PARAMETERS = ATTRIBUTION_PARAMETERS;\nexports.CLICK_ID_PARAMETERS = CLICK_ID_PARAMETERS;\nexports.DEFAULT_AGENT_MCP_HOST = DEFAULT_AGENT_MCP_HOST;\nexports.DEFAULT_WIDGET_EVENTS_ORIGIN = DEFAULT_WIDGET_EVENTS_ORIGIN;\nexports.HomeownerMcpClient = HomeownerMcpClient;\nexports.INTERNAL_TRAFFIC_GLOBAL = INTERNAL_TRAFFIC_GLOBAL;\nexports.IconButton = IconButton;\nexports.KEYBOARD_PRESETS = KEYBOARD_PRESETS;\nexports.KeyboardTestRig = KeyboardTestRig;\nexports.LEGACY_FORM_USER_ID_KEY = LEGACY_FORM_USER_ID_KEY;\nexports.LOAD_EVENT_PAGE_PARAMETERS = LOAD_EVENT_PAGE_PARAMETERS;\nexports.MAX_CLIENT_ERRORS_PER_PAGE = MAX_CLIENT_ERRORS_PER_PAGE;\nexports.MessageBubble = MessageBubble;\nexports.RichInput = RichInput;\nexports.RichText = RichText;\nexports.SEARCH_CRAWLER_UA_TOKENS = SEARCH_CRAWLER_UA_TOKENS;\nexports.SuggestionsGroup = SuggestionsGroup;\nexports.SuggestionsGroupHeading = SuggestionsGroupHeading;\nexports.SuggestionsItem = SuggestionsItem;\nexports.SuggestionsList = SuggestionsList;\nexports.TEST_LEAD_ATTRIBUTE = TEST_LEAD_ATTRIBUTE;\nexports.TEST_LEAD_PARAMETER = TEST_LEAD_PARAMETER;\nexports.TEST_LEAD_STORAGE_KEY = TEST_LEAD_STORAGE_KEY;\nexports.UTM_PARAMETERS = UTM_PARAMETERS;\nexports.VISITOR_ID_STORAGE_KEY = VISITOR_ID_STORAGE_KEY;\nexports.VISIT_IDLE_MS = VISIT_IDLE_MS;\nexports.VISIT_STORAGE_KEY = VISIT_STORAGE_KEY;\nexports.addQueryParametersToURL = addQueryParametersToURL;\nexports.addTestLeadAttribute = addTestLeadAttribute;\nexports.buildAgentNoticeText = buildAgentNoticeText;\nexports.buildLoadEventMetadata = buildLoadEventMetadata;\nexports.buildSiteTools = buildSiteTools;\nexports.claimPageLoadEvent = claimPageLoadEvent;\nexports.describeClientError = describeClientError;\nexports.detectBrowsingAgent = detectBrowsingAgent;\nexports.extendFormat = extendFormat;\nexports.extractAttributionFromUrl = extractAttributionFromUrl;\nexports.findItemByIndex = findItemByIndex;\nexports.findModelContext = findModelContext;\nexports.getAttribution = getAttribution;\nexports.getItemsLength = getItemsLength;\nexports.getStoredAttribution = getStoredAttribution;\nexports.injectMcpDiscoveryTags = injectMcpDiscoveryTags;\nexports.installClientErrorReporter = installClientErrorReporter;\nexports.installKeyboardSimulator = installKeyboardSimulator;\nexports.isFromBundle = isFromBundle;\nexports.isTestLeadSession = isTestLeadSession;\nexports.lockBodyScroll = lockBodyScroll;\nexports.parseSuggestionsResponse = parseSuggestionsResponse;\nexports.readInternalTrafficMark = readInternalTrafficMark;\nexports.registerSiteTools = registerSiteTools;\nexports.renderAgentNotice = renderAgentNotice;\nexports.resolveAgentMcpEndpoints = resolveAgentMcpEndpoints;\nexports.resolveWidgetEventsUrl = resolveWidgetEventsUrl;\nexports.sendWidgetErrorEvent = sendWidgetErrorEvent;\nexports.sendWidgetLoadEvent = sendWidgetLoadEvent;\nexports.sortSuggestionItems = sortSuggestionItems;\nexports.startAgentDiscovery = startAgentDiscovery;\nexports.storeAttribution = storeAttribution;\nexports.stripQueryString = stripQueryString;\nexports.trackVisualViewport = trackVisualViewport;\nexports.useBodyScrollLock = useBodyScrollLock;\nexports.useJsonFetch = useJsonFetch;\nexports.useScrollFocusedIntoView = useScrollFocusedIntoView;\nexports.useSuggestionsFetch = useSuggestionsFetch;\nexports.useVisualViewportProperties = useVisualViewportProperties;\nexports.uuid = uuid;\nexports.visitIdentity = visitIdentity;\nexports.visitorId = visitorId;\n//# sourceMappingURL=index.js.map\n","import {\n CLICK_ID_PARAMETERS as CORE_CLICK_ID_PARAMETERS,\n UTM_PARAMETERS as CORE_UTM_PARAMETERS\n} from \"@xapp/chat-widget-core\";\n\n/**\n * Utility functions for handling UTM parameters and tracking data\n * Following industry standards for marketing attribution tracking\n */\n\nexport interface TrackingParameters {\n // Standard UTM parameters (Google Analytics standard)\n utm_source?: string; // Traffic source (e.g., \"google\", \"facebook\", \"newsletter\")\n utm_medium?: string; // Marketing medium (e.g., \"cpc\", \"email\", \"social\")\n utm_campaign?: string; // Campaign name (e.g., \"spring_sale\", \"product_launch\")\n utm_term?: string; // Paid keywords (for paid search)\n utm_content?: string; // Ad content (for A/B testing different ads)\n\n // Platform-specific click IDs\n gclid?: string; // Google Click ID (Google Ads auto-tagging)\n gbraid?: string; // Google Click ID for web-to-app, iOS (no gclid available)\n wbraid?: string; // Google Click ID for app-to-web, iOS (no gclid available)\n fbclid?: string; // Facebook Click ID\n msclkid?: string; // Microsoft Click ID (Bing Ads)\n\n // Custom tracking parameters with configurable prefix\n [key: `track_${string}`]: string;\n}\n\n/**\n * Configuration for tracking parameter extraction\n */\nexport interface TrackingConfig {\n /**\n * Whether to extract UTM parameters from the URL\n * @default true\n */\n extractUtmParameters?: boolean;\n\n /**\n * Whether to extract platform-specific click IDs\n * @default true\n */\n extractClickIds?: boolean;\n\n /**\n * Custom parameter prefix to look for (in addition to utm_)\n * @default \"track_\"\n */\n customParameterPrefix?: string;\n\n /**\n * Whether to persist parameters to localStorage\n * @default true\n */\n persistToLocalStorage?: boolean;\n\n /**\n * How long to persist parameters in localStorage (in days)\n * @default 30\n */\n persistenceDays?: number;\n\n /**\n * Whether to prefer URL parameters over stored ones when both exist\n * @default true\n */\n preferUrlParameters?: boolean;\n\n /**\n * Which form the parameters belong to, from {@link trackingScope}. Scoped values are\n * stored and read back only for that form; omit it for the legacy page-wide keys.\n */\n scope?: string;\n}\n\nconst DEFAULT_CONFIG: Required<Omit<TrackingConfig, \"scope\">> = {\n extractUtmParameters: true,\n extractClickIds: true,\n customParameterPrefix: \"track_\",\n persistToLocalStorage: true,\n persistenceDays: 30,\n preferUrlParameters: true,\n};\n\n/**\n * UTM and click ID parameter names.\n *\n * Sourced from chat-widget-core so this widget, the submit path in api/stentor-api.ts\n * and the event path in services/EventTrackingService.ts cannot disagree about which\n * parameters exist. The three previously kept separate lists, and adding a parameter\n * here alone meant it was persisted to localStorage but never sent to the server.\n */\nconst UTM_PARAMETERS = CORE_UTM_PARAMETERS;\n\nconst CLICK_ID_PARAMETERS = CORE_CLICK_ID_PARAMETERS;\n\n\n/**\n * Storage key prefix for localStorage\n */\nconst STORAGE_KEY_PREFIX = 'xa_tracking_';\n\n/**\n * Prefix shared by every key this module writes, scoped or not.\n */\nconst STORAGE_KEY_ROOT = 'xa_tracking';\n\n/**\n * Identifies one form for stored attribution: the app key plus the form's intentId,\n * the same pair StentorApi keys its instances by.\n *\n * Unscoped, a utm_source picked up on one form's landing URL was sent with every form\n * the browser opened for the next 30 days - on form.xapp.ai that is every tenant's form.\n */\nexport function trackingScope(key: string | undefined, intentId?: string): string {\n return `${key ?? ''}|${intentId ?? ''}`;\n}\n\n/**\n * The localStorage key prefix for a scope; the legacy page-wide prefix when there is none.\n * The scope is URI-encoded so it can never read as a param name, or as another scope.\n */\nfunction storageKeyPrefix(scope?: string): string {\n return scope === undefined ? STORAGE_KEY_PREFIX : `${STORAGE_KEY_ROOT}@${encodeURIComponent(scope)}:`;\n}\n\n/**\n * Snapshot of every localStorage key, via length/key() rather than Object.keys, which\n * not every Storage implementation enumerates. A snapshot, so callers can remove keys.\n */\nfunction storageKeys(): string[] {\n const keys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key) {\n keys.push(key);\n }\n }\n return keys;\n}\n\n/**\n * Validates if a parameter value is safe to store and use\n */\nfunction isValidParameterValue(value: string): boolean {\n // Check length limit and basic XSS prevention\n return value.length <= 255 && !/[<>\"'\\x00-\\x1f]/.test(value);\n}\n\n/**\n * Extracts tracking parameters from a URL\n */\nexport function extractTrackingParametersFromUrl(\n url: string = window.location.href,\n config: TrackingConfig = {}\n): TrackingParameters {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (error) {\n console.warn('Invalid URL provided to tracking parameter extraction:', url);\n return {};\n }\n\n const searchParams = urlObj.searchParams;\n const parameters: TrackingParameters = {};\n\n // Extract UTM parameters\n if (finalConfig.extractUtmParameters) {\n UTM_PARAMETERS.forEach(param => {\n const value = searchParams.get(param);\n if (value && isValidParameterValue(value)) {\n parameters[param] = value;\n }\n });\n }\n\n // Extract platform-specific click IDs\n if (finalConfig.extractClickIds) {\n CLICK_ID_PARAMETERS.forEach(param => {\n const value = searchParams.get(param);\n if (value && isValidParameterValue(value)) {\n parameters[param] = value;\n }\n });\n }\n\n // Extract custom tracking parameters\n if (finalConfig.customParameterPrefix) {\n searchParams.forEach((value, key) => {\n if (key.startsWith(finalConfig.customParameterPrefix) && isValidParameterValue(value)) {\n // Type-safe assignment for custom parameters\n (parameters as Record<string, string>)[key] = value;\n }\n });\n }\n\n return parameters;\n}\n\n/**\n * Gets tracking parameters from localStorage\n */\nexport function getStoredTrackingParameters(scope?: string): TrackingParameters {\n const parameters: TrackingParameters = {};\n const prefix = storageKeyPrefix(scope);\n\n // Check each potential parameter in localStorage\n [...UTM_PARAMETERS, ...CLICK_ID_PARAMETERS].forEach(param => {\n const stored = localStorage.getItem(`${prefix}${param}`);\n if (stored) {\n try {\n const data = JSON.parse(stored);\n // Check if data hasn't expired\n if (data.expires > Date.now()) {\n parameters[param] = data.value;\n }\n } catch (e) {\n // Clean up invalid data\n localStorage.removeItem(`${prefix}${param}`);\n }\n }\n });\n\n // Check for custom tracking parameters\n storageKeys().forEach(key => {\n if (key.startsWith(`${prefix}track_`)) {\n try {\n const data = JSON.parse(localStorage.getItem(key) || '{}');\n if (data.expires > Date.now()) {\n const paramName = key.slice(prefix.length) as keyof TrackingParameters;\n parameters[paramName] = data.value;\n }\n } catch (e) {\n localStorage.removeItem(key);\n }\n }\n });\n\n return parameters;\n}\n\n/**\n * Stores tracking parameters in localStorage with expiration\n */\nexport function storeTrackingParameters(\n parameters: TrackingParameters,\n config: TrackingConfig = {}\n): void {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n\n if (!finalConfig.persistToLocalStorage) {\n return;\n }\n\n const expirationTime = Date.now() + (finalConfig.persistenceDays * 24 * 60 * 60 * 1000);\n const prefix = storageKeyPrefix(config.scope);\n\n Object.entries(parameters).forEach(([key, value]) => {\n if (value) {\n const data = {\n value,\n expires: expirationTime,\n stored: Date.now()\n };\n localStorage.setItem(`${prefix}${key}`, JSON.stringify(data));\n }\n });\n}\n\n/**\n * Main function to get all tracking parameters, combining URL and stored parameters\n */\nexport function getAllTrackingParameters(\n url: string = window.location.href,\n config: TrackingConfig = {}\n): TrackingParameters {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n\n const urlParameters = extractTrackingParametersFromUrl(url, config);\n const storedParameters = getStoredTrackingParameters(config.scope);\n\n // Combine parameters, with URL parameters taking precedence if configured\n const parameters: TrackingParameters = finalConfig.preferUrlParameters\n ? { ...storedParameters, ...urlParameters }\n : { ...urlParameters, ...storedParameters };\n\n // Store any new URL parameters\n if (Object.keys(urlParameters).length > 0) {\n storeTrackingParameters(urlParameters, config);\n }\n\n return parameters;\n}\n\n/**\n * Clears all stored tracking parameters, for every form\n */\nexport function clearStoredTrackingParameters(): void {\n storageKeys().forEach(key => {\n if (key.startsWith(STORAGE_KEY_ROOT)) {\n localStorage.removeItem(key);\n }\n });\n}\n\n/**\n * Gets tracking parameters formatted for form widget attributes\n */\nexport function getTrackingParametersForWidget(\n url: string = window.location.href,\n config: TrackingConfig = {}\n): Record<string, string> {\n const parameters = getAllTrackingParameters(url, config);\n const attributes: Record<string, string> = {};\n\n // Convert to string attributes for widget consumption\n Object.entries(parameters).forEach(([key, value]) => {\n if (value) {\n attributes[key] = String(value);\n }\n });\n\n return attributes;\n}\n","\nexport const EMAIL_REGEX = \"^\\\\w+([\\\\.-]?\\\\w+)*@\\\\w+([\\\\.-]?\\\\w+)*(\\\\.\\\\w{2,3})+$\";\n\n// Returns current timestamp\nfunction getCurrentDateString() {\n return (new Date()).toISOString() + \" ::\";\n}\n\ntype LogParam = unknown;\n\nexport function log(...args: readonly LogParam[]): void {\n if (window.xaLogLevel === \"debug\") {\n console.log(getCurrentDateString(), ...args);\n }\n}\n\nexport function err(...args: readonly LogParam[]): void {\n console.error(getCurrentDateString(), ...args);\n}\n\nexport const logOnce = (key: string, ...args: readonly LogParam[]): void => {\n const map = {};\n if (!map[key]) {\n map[key] = true;\n log(...args);\n }\n}\n\nexport * from \"./useIsMounted\";\nexport * from \"./tracking\";","import { Display, List } from \"stentor-models\";\n\nexport function isCarousel(display: Display): display is List {\n return !!display && ((display as List).type === \"CAROUSEL\");\n}","import { Display, List } from \"stentor-models\";\n\nexport function isList(display: Display): display is List {\n return !!display && ((display as List).type === \"LIST\");\n}","import { Display, MultistepForm } from \"stentor-models\";\n\nexport function isForm(display: Display): display is MultistepForm {\n return !!display && display[\"type\"] === \"FORM\";\n}\n","import { throwBadKind } from \"../../utils/guards\";\nimport { SearchAction } from \"../actions\";\nimport { SearchState } from \"../SearchState\";\n\nexport function RootReducer(state: SearchState, action: SearchAction): SearchState {\n const { type } = action;\n switch (type) {\n case \"set-query\":\n return {\n ...state,\n query: action.query || \"\"\n };\n case \"set-response\":\n return {\n ...state,\n responseQuery: action.query,\n responseIntentId: action.intentId\n };\n case \"set-context\":\n return {\n ...state,\n context: action.context\n };\n case \"new-search\":\n return {\n ...state,\n query: \"\",\n };\n case \"set-modal-state\":\n return {\n ...state,\n active: action.active,\n minimized: action.minimized,\n sendRequest: action.sendRequest\n };\n case \"open-modal-state\":\n if (state.active) {\n return state;\n }\n return {\n ...state,\n active: true,\n minimized: false,\n sendRequest: true\n };\n default:\n throwBadKind(type);\n }\n}","// compile time full switch-case verification\nexport function throwBadKind(x: never): never {\n throw new Error(\"Unknown kind \" + x);\n}\n","import React from \"react\";\nimport { SearchDispatch } from \"./SearchDispatch\";\nimport { SearchState } from \"./SearchState\";\nimport { SearchStore } from \"./SearchStore\";\n\nexport const DEFAULT_SEARCH_STATE: SearchState = {\n query: \"\",\n active: false,\n minimized: false,\n sendRequest: true\n};\n\nconst DEFAULT_SEARCH_DISPATCH: SearchDispatch = () => { };\n\nconst DEFAULT_SEARCH_STORE: SearchStore = [DEFAULT_SEARCH_STATE, DEFAULT_SEARCH_DISPATCH];\n\nexport const SearchStoreContext = React.createContext<SearchStore>(DEFAULT_SEARCH_STORE);","import React, { FC, useReducer, PropsWithChildren } from \"react\";\nimport { RootReducer } from \"./reducers\";\nimport { SearchState } from \"./SearchState\";\nimport { SearchStore } from \"./SearchStore\";\nimport { DEFAULT_SEARCH_STATE, SearchStoreContext } from \"./SearchStoreContext\";\n\nexport interface SearchStoreProviderProps {\n readonly initialState?: SearchState;\n}\n\nexport const SearchStoreProvider: FC<PropsWithChildren<SearchStoreProviderProps>> = props => {\n\n const reducer: SearchStore = useReducer(RootReducer, props.initialState || DEFAULT_SEARCH_STATE);\n\n return (\n <SearchStoreContext.Provider value={reducer}>\n {props.children}\n </SearchStoreContext.Provider>\n );\n};","import { useContext } from \"react\";\nimport { SearchStore } from \"./SearchStore\";\nimport { SearchStoreContext } from \"./SearchStoreContext\";\n\nexport function useSearchStore(): SearchStore {\n return useContext(SearchStoreContext);\n}\n","import { SearchState } from \"./SearchState\";\nimport { useSearchStore } from \"./useSearchStore\";\n\nexport function useSearchState(): SearchState {\n return useSearchStore()[0];\n}\n","function styleInject(css, ref) {\n if ( ref === void 0 ) ref = {};\n var insertAt = ref.insertAt;\n\n if (!css || typeof document === 'undefined') { return; }\n\n var head = document.head || document.getElementsByTagName('head')[0];\n var style = document.createElement('style');\n style.type = 'text/css';\n\n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild);\n } else {\n head.appendChild(style);\n }\n } else {\n head.appendChild(style);\n }\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(document.createTextNode(css));\n }\n}\n\nexport default styleInject;\n","import {\n useBodyScrollLock,\n useScrollFocusedIntoView,\n useVisualViewportProperties,\n} from \"@xapp/chat-widget-core\";\nimport React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./ModalDialog.module.scss\";\n\nexport interface ModalDialogProps {\n /**\n * Removes the backdrop overlay\n *\n * Setting this to true will then disable the click backdrop to close functionality\n */\n readonly disableBackdrop?: boolean;\n /**\n * Callback when the user requests to close the modal by clicking the backdrop.\n */\n onClose(): void;\n /**\n * Rendering inside a container the host page provided and sized (see `isEmbedded`).\n *\n * The customer's div is then the frame, so everything this component does for the\n * floating case -- a fixed full-viewport overlay, a backdrop over the host page, and\n * locking the host page's scroll -- is dropped.\n */\n readonly embedded?: boolean;\n}\n\nexport const ModalDialog: FC<PropsWithChildren<ModalDialogProps>> = (props) => {\n const { embedded } = props;\n\n // This used to add a class that set `body { overflow: hidden }`, which iOS Safari\n // ignores — the host page scrolled on underneath the open modal. Embedded there is no\n // overlay to scroll underneath: the form sits in the page flow, and pinning the body\n // around it would freeze the customer's whole page.\n useBodyScrollLock(!embedded);\n\n // Keeps the step's action row clear of the soft keyboard — see the calc() on\n // .xapp_search_modal's mobile padding. Reference counted, so the chat widget's own\n // subscription survives this modal closing while its keyboard is still up. Embedded,\n // nothing consumes --xapp-keyboard-inset, so there is nothing to publish it for.\n useVisualViewportProperties(!embedded);\n\n // Browsers do this themselves, but not reliably inside a position: fixed overlay -\n // tapping the last field on a step could leave it behind the keyboard. Kept on when\n // embedded: the customer's container is commonly a scroll box with the same problem.\n useScrollFocusedIntoView();\n\n if (embedded) {\n return <div className={styles.xapp_search_modal_embedded}>{props.children}</div>;\n }\n\n return (\n <div className={styles.xapp_search_modal}>\n {!props.disableBackdrop && (\n <div\n data-testid=\"xapp-modal-backdrop\"\n className={styles[\"xapp_search_modal__backdrop\"]}\n onClick={props.onClose}\n />\n )}\n <div className={styles[\"xapp_search_modal__body\"]}>{props.children}</div>\n </div>\n );\n};\n","import { stripQueryString, uuid, visitorId } from \"@xapp/chat-widget-core\";\nimport {\n ChannelActionRequest,\n IntentRequest,\n LaunchRequest,\n OptionSelectRequest,\n PermissionRequest,\n Response,\n} from \"stentor-models\";\nimport { StentorApiConfig } from \"../config\";\nimport { WidgetEvent, WidgetEventsRequest, WidgetEventsResponse } from \"../types/events\";\nimport { err, log } from \"../utils\";\nimport { addTestLeadAttribute } from \"@xapp/chat-widget-core\";\nimport { getStoredTrackingParameters, trackingScope } from \"../utils/tracking\";\n\nexport type StentorRequest =\n | IntentRequest\n | LaunchRequest\n | OptionSelectRequest\n | PermissionRequest\n | ChannelActionRequest;\n\nconst delay = (waitTimeInMs: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, waitTimeInMs);\n });\n\n/**\n * Marks a response for a channel action that was suppressed because a final submit had\n * already gone out on this session, rather than one that was actually sent.\n */\nconst DROPPED_AFTER_FINAL = \"__xappDroppedAfterFinal\";\n\n/**\n * True when the response came from the post-final suppression path rather than the\n * server. Callers use it to tell \"we deliberately did not send this\" apart from \"the\n * server returned nothing\" -- the two were indistinguishable before issue #1373.\n */\nexport function wasDroppedAfterFinal(response: unknown): boolean {\n return !!response && (response as Record<string, unknown>)[DROPPED_AFTER_FINAL] === true;\n}\n\n// One cached StentorApi per distinct widget config. A page can host multiple form widgets, each\n// bound to a different handler via its own intentId (see issue #1482), and each is an independent\n// conversation with its own session — so a single process-wide instance would make the second\n// widget send the first's intentId as overrideKey. Keyed by the fields that define a widget's\n// identity; the Form/FormWidget pair within one tree passes matching config and so shares one entry.\nconst API_INSTANCES = new Map<string, StentorApi>();\n\nconst apiCacheKey = (config: StentorApiConfig): string =>\n // demoMode is part of the identity, not just behaviour: a page can host a\n // live widget and a preview of the same handler, and sharing one instance\n // between them would let the preview submit through the live instance.\n `${config.url} ${config.key} ${config.intentId ?? \"\"} ${config.demoMode ? \"demo\" : \"live\"}`;\n\n/**\n * The only request types demo mode lets through.\n *\n * An **allowlist**, deliberately. A denylist of write types would let any\n * request type added later — OPTION_SELECT and PERMISSION_REQUEST already\n * exist unused in the StentorRequest union — through by default, and the\n * guarantee would quietly weaken as the request surface grows. Failing closed\n * means a new type is blocked until someone decides it is a read.\n *\n * These two only fetch the form definition; without them there is no form to\n * preview at all. Everything else, CHANNEL_ACTION_REQUEST above all, can\n * create a lead, notify the business, or land in reporting.\n *\n * So the guarantee is precisely \"a preview cannot create a lead or a tracked\n * event\", not \"a preview makes no requests\".\n */\nconst DEMO_READ_REQUEST_TYPES = new Set<string>([\"LAUNCH_REQUEST\", \"INTENT_REQUEST\"]);\n\nconst RESPONSE_TTL_MS = 900 * 1000; // 15 minutes\n\nconst TRACKING_CACHE_DURATION = 5 * 60 * 1000; // 5 minutes\n\nexport class StentorApi {\n private responseCache: {\n [key: string]: {\n ts: number;\n value: Response;\n };\n };\n\n private readonly config: StentorApiConfig;\n private session: StentorApiSession | undefined;\n /** Whether a request has gone out on the current session (visitSession can start one earlier). */\n private sessionSent = false;\n\n private prefetchSemaphore = Promise.resolve();\n\n // Cached tracking parameters to avoid repeated localStorage access. Per instance, since\n // each instance is one form and reads only that form's stored attribution.\n private cachedTrackingParams: { ts: number; value: Record<string, string> } | undefined;\n\n private constructor(config: StentorApiConfig) {\n this.config = config;\n this.responseCache = {};\n }\n\n /**\n * Which form this instance's stored attribution belongs to. See {@link trackingScope}.\n */\n public get trackingScope(): string {\n return trackingScope(this.config.key, this.config.intentId);\n }\n\n /**\n * Gets this form's tracking parameters with memory caching to reduce localStorage access\n */\n private getCachedTrackingParameters(): Record<string, string> {\n const now = Date.now();\n if (\n this.cachedTrackingParams &&\n now - this.cachedTrackingParams.ts < TRACKING_CACHE_DURATION\n ) {\n return this.cachedTrackingParams.value;\n }\n\n const value = getStoredTrackingParameters(this.trackingScope) as Record<string, string>;\n this.cachedTrackingParams = { ts: now, value };\n return value;\n }\n\n /**\n * Returns the cached API instance for this widget config, creating it on first use.\n *\n * Instances are keyed by url + key + intentId, so two widgets on one page with different\n * intentIds each get their own instance (and their own session) instead of colliding on a\n * single process-wide one. The Form/FormWidget pair within a single widget tree passes matching\n * config and so shares one entry.\n */\n public static getApi(config: StentorApiConfig): StentorApi {\n const cacheKey = apiCacheKey(config);\n const existing = API_INSTANCES.get(cacheKey);\n if (existing) {\n return existing;\n }\n\n const api = new StentorApi(config);\n API_INSTANCES.set(cacheKey, api);\n\n if (config.prefetchQuery) {\n api.prefetch(config.prefetchQuery);\n }\n\n return api;\n }\n\n public launchRequest(query: string): Promise<Response> {\n return this.send({\n type: \"LAUNCH_REQUEST\",\n rawQuery: query,\n intentId: \"LaunchRequest\",\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n } as StentorRequest);\n }\n\n public intentRequest(request: { query?: string; intentId?: string }): Promise<Response> {\n // if we have the intentId, use that and set rawQuery to be undefined\n // so that stentor doesn't try to resolve it again\n // otherwise, use the query and set intentId to be \"NLU_RESULT_PLACEHOLDER\"\n const rawQuery: string | undefined = request?.intentId ? undefined : request.query;\n const intentId: string = request?.intentId ? request.intentId : \"NLU_RESULT_PLACEHOLDER\";\n\n return this.send({\n type: \"INTENT_REQUEST\",\n rawQuery,\n intentId,\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n } as StentorRequest);\n }\n\n public channelActionRequest(data: unknown, action: string): Promise<Response> {\n const isFinal = !!(data as any).final;\n\n if (this.session) {\n if (this.session.hadFinal) {\n log(`Had final submit. Not sending action request: ${action}`);\n // Flagged rather than a bare {}: suppressing a duplicate after the final\n // submit is correct, but an indistinguishable empty response meant a\n // caller could not tell a dropped submit from a delivered one -- so a\n // wrongly-latched session looked exactly like success (issue #1373).\n // A plain string key, not a Symbol: the module is re-required per test\n // and Symbol identity would not survive that.\n return Promise.resolve({ [DROPPED_AFTER_FINAL]: true } as unknown as Response);\n }\n\n this.session.hadFinal = isFinal;\n }\n\n return this.send({\n type: \"CHANNEL_ACTION_REQUEST\",\n action,\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n ...(this.config.intentId ? { overrideKey: this.config.intentId } : {}),\n attributes: {\n data,\n },\n // The double cast is required: ChannelActionRequest requires userId, which send() fills\n // in below. It is NOT about overrideKey — that is a declared optional field on the\n // request type. A single `as StentorRequest` does not compile here.\n } as unknown as StentorRequest).catch((error) => {\n // The latch goes up synchronously above so a double-click cannot put two\n // finals in flight. But a final that never reached the server must not keep\n // it up: leaving it latched turns every retry into an instant\n // DROPPED_AFTER_FINAL \"success\", which is precisely how a lead goes missing\n // (issue #1373). Unlatch and let the caller retry for real.\n if (this.session && isFinal) {\n this.session.hadFinal = false;\n }\n throw error;\n });\n }\n\n /**\n * Track form widget interaction events\n * Sends events to POST /cms/widget/events\n *\n * Authentication uses the widget key in the request body (not headers).\n *\n * @param eventType - Type of event (next_step, submit, partial_data)\n * @param event - The widget event to track\n * @returns The response with processed count, or undefined on error\n */\n public async trackEvent(\n eventType: string,\n event: WidgetEvent\n ): Promise<WidgetEventsResponse | undefined> {\n try {\n const { key } = this.config;\n if (this.config.demoMode) {\n // A preview interaction must not show up in funnel analytics as\n // a real form open/submit.\n log(\"[demoMode] suppressed tracking event\", eventType);\n return undefined;\n }\n if (!key) {\n err(\"[EventTracking] No widget key configured, skipping event tracking\");\n return undefined;\n }\n const trackingUrl = this.getTrackingUrl();\n\n // Request body includes key for authentication (no Authorization header needed)\n const requestBody: WidgetEventsRequest = {\n key,\n events: [event],\n };\n\n const params: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(requestBody),\n mode: \"cors\",\n };\n\n const response = await fetch(trackingUrl, params);\n\n if (!response.ok) {\n err(`Event tracking failed: ${response.status} ${response.statusText}`);\n // Don't throw - we don't want to block user flow\n return undefined;\n }\n\n const result: WidgetEventsResponse = await response.json();\n log(`Event tracking succeeded: ${eventType}, processed: ${result.processed}`);\n return result;\n } catch (error) {\n // Log error but don't throw - events should never block user flow\n err(`Event tracking error: ${error}`);\n return undefined;\n }\n }\n\n /**\n * Track form widget interaction events for page unload scenarios.\n *\n * Uses fetch with keepalive instead of sendBeacon because:\n * - sendBeacon with Content-Type: application/json triggers CORS preflight\n * - sendBeacon doesn't properly wait for preflight response before firing\n * - fetch with keepalive handles the preflight handshake correctly\n *\n * @param event - The widget event to track\n * @param widgetType - Names the sending widget, for event types the server shares between\n * widgets (e.g. \"load\"). Omitted from the body when not given.\n * @returns true if the request was queued (not necessarily delivered), false if queuing failed\n */\n public trackEventBeacon(\n event: WidgetEvent,\n widgetType?: WidgetEventsRequest[\"widgetType\"]\n ): boolean {\n const { key } = this.config;\n if (this.config.demoMode) {\n // The beacon fires on beforeunload and on the midnight timeout, and\n // its payload is `partialData` — the values the visitor actually\n // typed. A preview that gets abandoned would otherwise post real\n // form data to the events endpoint, which is exactly what demo mode\n // exists to prevent.\n log(\"[demoMode] suppressed tracking beacon\", event.eventType);\n return false;\n }\n if (!key) {\n err(\"[EventTracking] No widget key configured, skipping event beacon\");\n return false;\n }\n\n try {\n const trackingUrl = this.getTrackingUrl();\n const requestBody: WidgetEventsRequest = {\n key,\n ...(widgetType ? { widgetType } : {}),\n events: [event],\n };\n\n // Use fetch with keepalive for proper CORS handling during page unload.\n // keepalive allows the request to outlive the page.\n // Note: This is fire-and-forget - we return true once queued, regardless of\n // eventual success/failure, since the page may be gone by the time it completes.\n fetch(trackingUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(requestBody),\n keepalive: true,\n }).catch(() => {\n // Silently ignore errors - page may already be unloaded\n });\n\n return true;\n } catch (error) {\n err(`Event beacon error: ${error}`);\n return false;\n }\n }\n\n /**\n * Build the tracking endpoint URL: /cms/widget/events\n */\n private getTrackingUrl(): string {\n const { url } = this.config;\n\n try {\n const parsedUrl = new URL(url);\n // Extract origin (protocol + host) and build the tracking endpoint\n return `${parsedUrl.origin}/cms/widget/events`;\n } catch (e) {\n // Fallback for invalid URLs - try to extract origin manually\n err(`[EventTracking] Failed to parse URL: ${url}`);\n const match = url.match(/^(https?:\\/\\/[^/]+)/);\n if (match) {\n return `${match[1]}/cms/widget/events`;\n }\n // Last resort: append to the URL\n return `${url.replace(/\\/$/, \"\")}/cms/widget/events`;\n }\n }\n\n public resetSession(): void {\n this.session = undefined;\n this.sessionSent = false;\n }\n\n /**\n * This visit's session and the visitor's user id (the shared visitor id), starting the session if no request has\n * yet. The load event calls it before the form has sent anything, so the load carries the\n * same ids as the visit's open and submit events. The first request on it still goes out\n * as the new session.\n */\n public visitSession(): { readonly sessionId: string; readonly userId: string } {\n if (!this.session) {\n this.session = {\n sessionId: `stentor-form-session-${uuid()}`,\n // The visitor id every XAPP widget on the site shares, so a lead's user id is\n // the one the chat widget's events report too.\n userId: visitorId(),\n hadFinal: false,\n };\n }\n const { sessionId, userId } = this.session;\n return { sessionId, userId };\n }\n\n private getCachedResponse(query: string | undefined): Response | undefined {\n if (!query) {\n return;\n }\n\n const now = new Date().getTime();\n const hit = this.responseCache[query];\n\n if (hit) {\n if (now - hit.ts < RESPONSE_TTL_MS) {\n log(`Returning cached response for \"${query}\"`);\n return hit.value;\n }\n\n log(`Deleting expired cached response for \"${query}\"`);\n delete this.responseCache[query];\n }\n\n return;\n }\n\n private async send(\n data: Omit<StentorRequest, \"sessionId\" | \"userId\" | \"isNewSession\">\n ): Promise<Response> {\n await this.prefetchSemaphore;\n\n if (this.config.demoMode && !DEMO_READ_REQUEST_TYPES.has(data.type)) {\n // Only reads are allowed through: the form's entire step structure\n // arrives on the INTENT_REQUEST response and is stashed in\n // formDisplayRef, and that handler applies the response\n // unconditionally. Blocking reads too would clobber state with an\n // empty response and render a form with no steps — the opposite of\n // \"behaves exactly like production\".\n log(\"[demoMode] suppressed request\", data.type);\n // Deliberately partial. Every field on Response that callers read\n // — outputSpeech, displays, context — is optional, and they all\n // guard before use, so absent means \"nothing to apply\" rather than\n // a missing value. The cast is what makes that intent explicit; if\n // a caller ever starts requiring a field, this is where to add it.\n return {} as Response;\n }\n\n const hit = this.getCachedResponse(data.rawQuery);\n if (hit) {\n return Promise.resolve(hit);\n }\n\n const { url, key } = this.config;\n\n const newSession = !this.sessionSent;\n const { sessionId, userId } = this.visitSession();\n this.sessionSent = true;\n\n const attributes: Record<string, unknown> = {};\n\n // Add current URL for analytics (exclude localhost for privacy)\n try {\n const href = new URL(window.location.href);\n if (href?.host.toLowerCase().startsWith(\"localhost\")) {\n // Indicate localhost without exposing the full URL\n attributes[\"isLocal\"] = true;\n } else {\n // Not localhost, include the full URL\n attributes[\"currentUrl\"] = window.location.href;\n }\n } catch (e) {\n // If URL parsing fails, skip currentUrl\n }\n\n // The page the visitor came from, query string dropped (it can carry PII). Lands on the\n // lead as extras.referrer, so a lead can be attributed without joining the events.\n const referrer = stripQueryString(document.referrer);\n if (referrer) {\n attributes[\"referrer\"] = referrer;\n }\n\n // look for certain attributes on the browser and add them.\n // get xa_rwg_token from local storage\n const rwgToken = localStorage.getItem(\"xa_rwg_token\");\n if (rwgToken) {\n attributes[\"rwg_token\"] = rwgToken;\n }\n const merchantId = localStorage.getItem(\"xa_merchant_id\");\n if (merchantId) {\n attributes[\"merchant_id\"] = merchantId;\n }\n const environment = localStorage.getItem(\"xa_environment\");\n if (environment) {\n attributes[\"environment\"] = environment;\n }\n const enablePreferredTime = localStorage.getItem(\"xa_enablePreferredTime\");\n if (enablePreferredTime) {\n attributes[\"enablePreferredTime\"] = enablePreferredTime;\n }\n const service = localStorage.getItem(\"xa_service\");\n if (service) {\n attributes[\"service\"] = service;\n }\n const origin = localStorage.getItem(\"xa_origin\");\n if (origin) {\n attributes[\"origin\"] = origin;\n }\n\n // Read placeId from URL parameters on every request (not cached like UTM params).\n // This is intentional: in multi-location / SPA scenarios (e.g. Reserve with Google),\n // the URL may change between requests within a session and the routing must always\n // reflect the current placeId. The value is forwarded to the backend as-is; the\n // backend is responsible for validating and using the value safely.\n try {\n const urlParams = new URLSearchParams(window.location.search);\n const placeId = urlParams.get(\"placeId\");\n if (placeId) {\n attributes[\"placeId\"] = placeId;\n }\n } catch (e) {\n // If URL parsing fails, skip placeId\n }\n\n // Extract tracking parameters using cached approach for better performance\n const trackingParams = this.getCachedTrackingParameters();\n Object.assign(attributes, trackingParams);\n\n // A test lead from Studio's \"send yourself a test lead\" booking page\n addTestLeadAttribute(attributes);\n\n // Add current time for accurate date/time responses\n attributes[\"currentTime\"] = new Date().toISOString();\n\n const request = {\n ...data,\n sessionId,\n userId,\n isNewSession: newSession,\n attributes: {\n ...data.attributes,\n ...attributes,\n },\n } as StentorRequest;\n const body = JSON.stringify(request);\n\n const params: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${key}`,\n },\n body,\n mode: \"cors\",\n };\n\n let response = await fetch(url, params);\n\n if (!response.ok) {\n err(`Stentor call failed: ${response.statusText}`);\n\n await delay(1000);\n response = await fetch(url, params); // once more\n if (!response.ok) {\n err(`Stentor call failed again: ${response.statusText}`);\n throw new Error(`Status ${response.status}, Text: ${response.statusText}`);\n }\n }\n\n return response.json();\n }\n\n private async prefetch(query: string): Promise<void> {\n if (this.config.demoMode) {\n return;\n }\n\n const hit = this.getCachedResponse(query);\n if (hit) {\n return;\n }\n\n let resolver: (value: void | PromiseLike<void>) => void;\n\n this.prefetchSemaphore = new Promise((resolve) => {\n resolver = resolve;\n });\n\n const { url, key } = this.config;\n\n const newSession = !this.sessionSent;\n const { sessionId, userId } = this.visitSession();\n this.sessionSent = true;\n\n const data = {\n type: \"INTENT_REQUEST\",\n rawQuery: query,\n intentId: \"NLU_RESULT_PLACEHOLDER\",\n platform: \"stentor-platform\",\n channel: \"form-widget\",\n };\n\n const attributes: Record<string, unknown> = {\n currentTime: new Date().toISOString(),\n };\n\n const request = {\n ...data,\n sessionId,\n userId,\n isNewSession: newSession,\n attributes,\n } as StentorRequest;\n\n const body = JSON.stringify(request);\n\n const params: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${key}`,\n },\n body,\n mode: \"cors\",\n };\n\n const start = new Date().getTime();\n\n fetch(url, params)\n .then(async (fetchResponse) => {\n if (!fetchResponse.ok) {\n err(`Stentor prefetch failed: ${fetchResponse.statusText}`);\n return;\n }\n\n const now = new Date().getTime();\n\n this.responseCache[query] = {\n ts: now,\n value: await fetchResponse.json(),\n };\n\n log(`Stentor prefetch took: ${now - start} ms`);\n })\n .finally(() => {\n resolver();\n });\n\n return;\n }\n}\n\nexport interface StentorApiSession {\n readonly sessionId: string;\n readonly userId: string;\n hadFinal: boolean;\n}\n","import { SuggestionTypes } from \"stentor-models\";\n\nexport function getActionLabel(action: SuggestionTypes): string {\n if (typeof action === \"string\") {\n return action;\n }\n return action.title;\n}\n","import React from \"react\";\nimport { FormWidgetConfig } from \"../config\";\n\nconst defaultValue: FormWidgetConfig = {\n api: {\n key: \"\",\n url: \"\"\n },\n suggestionsUrl: \"\",\n isVoiceEnabled: false,\n autoGreeting: \"schedule\" // default utterance to trigger the form if not set in config\n};\n\nexport const SearchWidgetConfigContext = React.createContext<FormWidgetConfig>(defaultValue);","import { useCallback, useMemo, useState } from \"react\";\nimport { useIsMounted } from \"./useIsMounted\";\n\nexport type LoadingAction<TResult> = () => Promise<TResult>;\n\nexport type LoadingRunAction<TResult> = (action: LoadingAction<TResult>) => Promise<TResult>;\n\nexport interface LoadingState {\n readonly loading: boolean;\n run<TResult>(action: LoadingAction<TResult>): Promise<TResult>;\n}\n\nfunction runCounter<TResult>(action: LoadingAction<TResult>, shift: (delta: number) => void): Promise<TResult> {\n shift(1);\n return action().finally(() => {\n shift(-1);\n });\n}\n\nexport function useLoading(): LoadingState {\n\n const [state, setState] = useState<number>(0);\n\n const mounted = useIsMounted();\n\n const run = useCallback(<TResult>(action: LoadingAction<TResult>) => {\n return runCounter(action, delta => {\n if (mounted()) {\n setState(prev => prev + delta);\n }\n });\n }, [mounted]);\n\n return useMemo(() => ({\n loading: !!state,\n run\n }), [state, run]);\n\n}","import { useCallback, useEffect, useRef } from \"react\";\n\nexport function useIsMounted(): () => boolean {\n const ref = useRef(false);\n useEffect(() => {\n ref.current = true;\n return () => {\n ref.current = false;\n };\n }, []);\n\n return useCallback(() => ref.current, []);\n};\n","import { useEffect, useCallback } from \"react\";\nimport { err } from \".\";\n\nconst TRUSTED_FORM_CERT_FIELD = \"xxTrustedFormCertUrl\";\nconst TRUSTED_FORM_PING_FIELD = \"xxTrustedFormPingUrl\";\nconst TRUSTED_FORM_ORIGIN = \"https://api.trustedform.com\";\n\nfunction isValidTrustedFormUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n return parsed.origin === TRUSTED_FORM_ORIGIN;\n } catch {\n return false;\n }\n}\n\nexport function useTrustedForm(scriptUrl: string | undefined): () => Record<string, string> | undefined {\n useEffect(() => {\n if (!scriptUrl) {\n return;\n }\n\n if (!isValidTrustedFormUrl(scriptUrl)) {\n err(\"[TrustedForm] Rejected script URL from unexpected origin\");\n return;\n }\n\n const existingScript = document.querySelector(`script[src=\"${scriptUrl}\"]`);\n if (existingScript) {\n return;\n }\n\n const script = document.createElement(\"script\");\n script.async = true;\n script.src = scriptUrl;\n\n script.onerror = () => {\n err(\"[TrustedForm] Failed to load script\");\n };\n\n // Intentionally no cleanup on unmount — TrustedForm must remain active for the page session\n document.head.appendChild(script);\n }, [scriptUrl]);\n\n const getTrustedFormData = useCallback((): Record<string, string> | undefined => {\n if (!scriptUrl) {\n return undefined;\n }\n\n const data: Record<string, string> = {};\n\n const certInput = document.querySelector<HTMLInputElement>(\n `input[name=\"${TRUSTED_FORM_CERT_FIELD}\"], input[id=\"${TRUSTED_FORM_CERT_FIELD}\"]`\n );\n const pingInput = document.querySelector<HTMLInputElement>(\n `input[name=\"${TRUSTED_FORM_PING_FIELD}\"], input[id=\"${TRUSTED_FORM_PING_FIELD}\"]`\n );\n\n if (certInput?.value) {\n data[TRUSTED_FORM_CERT_FIELD] = certInput.value;\n }\n if (pingInput?.value) {\n data[TRUSTED_FORM_PING_FIELD] = pingInput.value;\n }\n\n if (Object.keys(data).length === 0) {\n err(\"[TrustedForm] No certificate data found in DOM\");\n return undefined;\n }\n\n return data;\n }, [scriptUrl]);\n\n return getTrustedFormData;\n}\n","/**\n * Reads a single cookie value by name, or undefined when unavailable\n * (no document, empty cookie jar, or the cookie is not set).\n */\nexport function getCookie(name: string): string | undefined {\n if (typeof document === \"undefined\" || !document.cookie) {\n return undefined;\n }\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = document.cookie.match(new RegExp(\"(?:^|; )\" + escaped + \"=([^;]*)\"));\n if (!match) {\n return undefined;\n }\n try {\n return decodeURIComponent(match[1]);\n } catch {\n // decodeURIComponent throws a URIError on malformed percent-encoding\n // (e.g. a stray \"%\" written by another script). getMetaCookies runs\n // during FORM_SUBMIT, so never let a bad tracking cookie break the lead:\n // fall back to the raw value (fbp/fbc are normally not percent-encoded).\n return match[1];\n }\n}\n\n/**\n * Meta's browser cookies used for Conversions API match quality and dedup:\n * `_fbp` (browser id) and `_fbc` (click id). Forwarded to the backend with the\n * lead so the server-side CAPI event carries the same signals as the browser\n * pixel. Only keys that are actually present are returned.\n */\nexport function getMetaCookies(): { fbp?: string; fbc?: string } {\n const fbp = getCookie(\"_fbp\");\n const fbc = getCookie(\"_fbc\");\n return {\n ...(fbp ? { fbp } : {}),\n ...(fbc ? { fbc } : {}),\n };\n}\n","import { getCookie } from \"./metaCookies\";\n\n/**\n * Google Analytics 4 lead conversion tracking.\n *\n * GA4 cannot deduplicate a browser `generate_lead` against a server-side\n * Measurement Protocol one (Meta and OpenAI dedupe on a shared event id; GA4\n * does not). So each lead is sent by exactly ONE path: the browser sends it\n * when the customer's GA4 tag is actually loaded, and flags the lead\n * `ga4ClientFired`; the backend sends it via Measurement Protocol only when\n * that flag is absent (tag blocked or missing, chat leads).\n *\n * Nothing here ever sends PII — GA4's terms forbid it. The event carries only\n * the shared event id and the lead source.\n */\n\nexport const GA4_LEAD_EVENT_NAME = \"generate_lead\";\n\ntype Gtag = (...args: unknown[]) => void;\n\ntype GaWindow = Window & {\n gtag?: Gtag;\n dataLayer?: unknown[];\n google_tag_manager?: Record<string, unknown>;\n};\n\n/**\n * Non-PII lead extras forwarded to the backend for the GA4 integration.\n */\nexport interface Ga4LeadExtras {\n /** `<random>.<timestamp>` from the `_ga` cookie. */\n gaClientId?: string;\n /** Session start (unix seconds) from the `_ga_<id>` cookie. */\n gaSessionId?: string;\n /** The browser already sent `generate_lead`; the server must not. */\n ga4ClientFired?: true;\n /** The visitor opted out (GPC); the server must not send either. */\n ga4OptOut?: true;\n}\n\n/**\n * Validates a GA4 measurement id (\"G-\" followed by alphanumerics). Universal\n * Analytics (\"UA-\") and GTM container (\"GTM-\") ids are rejected.\n */\nexport function isValidGa4MeasurementId(id: unknown): id is string {\n return typeof id === \"string\" && /^G-[A-Z0-9]{4,}$/i.test(id.trim());\n}\n\n/**\n * Honors Global Privacy Control (CCPA/CPRA). GA4 data feeds Google Ads, so an\n * opted-out visitor gets neither the browser event nor the server one.\n */\nexport function hasGlobalPrivacyControlOptOut(): boolean {\n if (typeof navigator === \"undefined\") {\n return false;\n }\n return (\n (navigator as Navigator & { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n );\n}\n\n/**\n * Extracts the GA4 client id from a `_ga` cookie value: `GA1.1.<rand>.<ts>`\n * -> `<rand>.<ts>`.\n */\nexport function parseGaClientId(cookie: string | undefined): string | undefined {\n const parts = cookie?.split(\".\") || [];\n if (parts.length < 4) {\n return undefined;\n }\n const clientId = parts.slice(-2).join(\".\");\n return /^\\d+\\.\\d+$/.test(clientId) ? clientId : undefined;\n}\n\n/**\n * Extracts the session id from a `_ga_<container>` cookie value. Handles both\n * the legacy `GS1.1.<sid>.<n>...` format and the 2025 `GS2.1.s<sid>$o3$...`\n * format.\n */\nexport function parseGaSessionId(cookie: string | undefined): string | undefined {\n const parts = cookie?.split(\".\") || [];\n if (parts.length < 3) {\n return undefined;\n }\n let sessionId: string | undefined;\n if (parts[0] === \"GS2\") {\n const token = parts[2].split(\"$\").find((t) => t.startsWith(\"s\"));\n sessionId = token?.slice(1);\n } else {\n sessionId = parts[2];\n }\n return sessionId && /^\\d+$/.test(sessionId) ? sessionId : undefined;\n}\n\n/**\n * True only when the Google tag for THIS measurement id has actually loaded.\n * A bare `window.gtag` is not enough: host pages define the gtag stub inline,\n * so it exists even when an ad blocker stopped gtag.js — events pushed then go\n * nowhere, and flagging them as sent would lose the lead from GA4 entirely.\n */\nexport function isGa4TagLoaded(measurementId: string): boolean {\n const gtm = (window as GaWindow).google_tag_manager;\n return !!gtm && Object.prototype.hasOwnProperty.call(gtm, measurementId);\n}\n\n/**\n * Sends `generate_lead` to the given GA4 property from the browser. Returns\n * true only when the event was handed to a loaded Google tag; the caller uses\n * that to set `ga4ClientFired`.\n *\n * GTM-only sites have no `gtag` global, so fall back to the gtag-style\n * `arguments` push onto `dataLayer`, which the loaded Google tag processes.\n */\nexport function sendGa4LeadEvent(\n measurementId: string | undefined,\n eventId: string,\n leadSource: string\n): boolean {\n if (!isValidGa4MeasurementId(measurementId) || hasGlobalPrivacyControlOptOut()) {\n return false;\n }\n const id = measurementId.trim();\n if (!isGa4TagLoaded(id)) {\n return false;\n }\n\n const w = window as GaWindow;\n const params = { send_to: id, event_id: eventId, lead_source: leadSource };\n\n try {\n if (typeof w.gtag === \"function\") {\n w.gtag(\"event\", GA4_LEAD_EVENT_NAME, params);\n return true;\n }\n if (Array.isArray(w.dataLayer)) {\n // Must be an `arguments` object, not an array: the Google tag only\n // treats arguments-shaped dataLayer entries as gtag commands.\n (function pushGtag(..._args: unknown[]) {\n // eslint-disable-next-line prefer-rest-params\n w.dataLayer?.push(arguments);\n })(\"event\", GA4_LEAD_EVENT_NAME, params);\n return true;\n }\n } catch {\n // A broken host tag must never break the lead submission; the server\n // path covers this lead since ga4ClientFired stays unset.\n }\n return false;\n}\n\n/**\n * Builds the GA4 lead extras sent to the backend with the submission.\n *\n * @param measurementId the app's GA4 id, needed to find the session cookie\n * @param clientFired whether {@link sendGa4LeadEvent} sent the browser event\n */\nexport function getGa4LeadExtras(\n measurementId: string | undefined,\n clientFired: boolean\n): Ga4LeadExtras {\n if (hasGlobalPrivacyControlOptOut()) {\n return { ga4OptOut: true };\n }\n\n const extras: Ga4LeadExtras = {};\n\n const gaClientId = parseGaClientId(getCookie(\"_ga\"));\n if (gaClientId) {\n extras.gaClientId = gaClientId;\n }\n\n if (isValidGa4MeasurementId(measurementId)) {\n const container = measurementId.trim().replace(/^G-/i, \"\");\n const gaSessionId = parseGaSessionId(getCookie(`_ga_${container}`));\n if (gaSessionId) {\n extras.gaSessionId = gaSessionId;\n }\n }\n\n if (clientFired) {\n extras.ga4ClientFired = true;\n }\n\n return extras;\n}\n","import React, { FC } from \"react\";\n\nexport const LeftAngleIcon: FC = () => {\n return (\n <svg viewBox=\"0 0 15 15\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M10 14L3 7.5L10 1\" stroke=\"currentColor\" fill=\"none\" strokeLinecap=\"square\" />\n </svg>\n );\n}","import React, { FC } from \"react\";\n\nexport const RightAngleIcon: FC = () => {\n return (\n <svg viewBox=\"0 0 15 15\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M5 14L12 7.5L5 1\" stroke=\"currentColor\" fill=\"none\" strokeLinecap=\"square\" />\n </svg>\n );\n}","import React, { FC } from \"react\";\n\nexport const SearchIcon: FC = () => {\n return (\n <svg\n fill=\"#000000\"\n height=\"300px\"\n width=\"30px\"\n version=\"1.1\"\n id=\"Capa_1\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 382.163 382.163\">\n <g>\n <path\n d=\"M344.89,215.855c0-50.602-24.567-95.57-62.396-123.618l2.982-5.326l46.258,25.92c1.16,0.65,2.418,0.958,3.659,0.958\n\t\tc2.626,0,5.175-1.381,6.55-3.835c8.883-15.853,11.061-34.216,6.132-51.706c-4.243-15.059-13.327-27.91-25.887-36.864l5.722-10.22\n\t\tc2.023-3.614,0.733-8.185-2.881-10.208c-3.614-2.023-8.184-0.734-10.208,2.88l-5.72,10.216\n\t\tc-31.487-13.349-68.758-1.123-85.857,29.391c-0.972,1.735-1.215,3.786-0.676,5.7s1.817,3.536,3.553,4.509l46.268,25.925\n\t\tl-2.406,4.297c-23.084-13.853-50.078-21.83-78.903-21.83c-28.825,0-55.818,7.977-78.902,21.829l-2.408-4.296l46.269-25.926\n\t\tc3.614-2.025,4.902-6.595,2.877-10.209c-8.883-15.853-23.407-27.297-40.897-32.226c-15.061-4.244-30.765-3.205-44.96,2.833\n\t\tL67.342,3.838c-2.023-3.615-6.593-4.904-10.208-2.881c-3.614,2.023-4.904,6.594-2.881,10.208l5.721,10.22\n\t\tc-12.559,8.954-21.643,21.804-25.886,36.864c-4.929,17.49-2.751,35.854,6.132,51.706c1.375,2.454,3.924,3.835,6.55,3.835\n\t\tc1.241,0,2.5-0.309,3.659-0.958l46.257-25.919l2.984,5.324c-37.83,28.047-62.397,73.016-62.397,123.619\n\t\tc0,45.21,19.61,85.924,50.767,114.091l-9.427,43.114c-0.885,4.047,1.678,8.044,5.725,8.929c0.54,0.118,1.078,0.175,1.609,0.175\n\t\tc3.448,0,6.553-2.393,7.32-5.899l7.818-35.757c25.321,18.332,56.416,29.157,89.996,29.157c33.58,0,64.676-10.825,89.997-29.158\n\t\tl7.818,35.758c0.767,3.507,3.871,5.899,7.319,5.899c0.531,0,1.07-0.057,1.609-0.175c4.046-0.885,6.61-4.882,5.725-8.929\n\t\tl-9.427-43.115C325.281,301.778,344.89,261.065,344.89,215.855z M308.517,30.436c12.357,6.924,21.279,18.246,25.121,31.88\n\t\tc3.155,11.198,2.574,22.853-1.57,33.507l-91.609-51.331C256.211,23.856,285.228,17.387,308.517,30.436z M50.096,95.824\n\t\tc-4.145-10.654-4.726-22.31-1.57-33.507c3.842-13.634,12.763-24.956,25.121-31.88c8.179-4.583,17.064-6.758,25.833-6.758\n\t\tc16.201,0,32.005,7.425,42.225,20.814L50.096,95.824z M52.273,215.855c0-76.54,62.269-138.809,138.809-138.809\n\t\tS329.89,139.315,329.89,215.855s-62.27,138.809-138.809,138.809S52.273,292.394,52.273,215.855z\"\n />\n <path\n d=\"M191.081,107.685c-59.645,0-108.17,48.525-108.17,108.17c0,59.645,48.525,108.17,108.17,108.17\n\t\tc59.646,0,108.17-48.525,108.17-108.17C299.252,156.21,250.727,107.685,191.081,107.685z M191.081,309.025\n\t\tc-51.374,0-93.17-41.796-93.17-93.17c0-51.374,41.796-93.17,93.17-93.17c51.375,0,93.17,41.796,93.17,93.17\n\t\tC284.252,267.229,242.456,309.025,191.081,309.025z\"\n />\n <path\n d=\"M198.585,190.081v-36.262c0-4.142-3.358-7.5-7.5-7.5s-7.5,3.358-7.5,7.5v36.26c-8.784,2.559-15.718,9.492-18.279,18.276\n\t\th-16.941c-4.142,0-7.5,3.358-7.5,7.5s3.358,7.5,7.5,7.5h16.941c3.254,11.165,13.574,19.349,25.775,19.349\n\t\tc14.805,0,26.849-12.044,26.849-26.849C217.93,203.655,209.748,193.337,198.585,190.081z M191.081,227.704\n\t\tc-6.533,0-11.849-5.315-11.849-11.849s5.315-11.849,11.849-11.849c6.534,0,11.849,5.315,11.849,11.849\n\t\tS197.615,227.704,191.081,227.704z\"\n />\n </g>\n </svg>\n );\n};\n","import React, { FC } from \"react\";\n\nconst strokeWidth = 16;\nconst strokeWidthHalf = strokeWidth / 2;\nconst strokeWidthQuarter = strokeWidth / 4;\n\nexport const SpinnerIcon:FC = () => {\n return (\n <svg\n viewBox=\"0 0 200 200\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <defs>\n <linearGradient id=\"spinner-secondHalf\">\n <stop offset=\"0%\" stopOpacity=\"0\" stopColor=\"currentColor\" />\n <stop offset=\"100%\" stopOpacity=\"0.5\" stopColor=\"currentColor\" />\n </linearGradient>\n <linearGradient id=\"spinner-firstHalf\">\n <stop offset=\"0%\" stopOpacity=\"1\" stopColor=\"currentColor\" />\n <stop offset=\"100%\" stopOpacity=\"0.5\" stopColor=\"currentColor\" />\n </linearGradient>\n </defs>\n \n <g strokeWidth={strokeWidth}>\n <path stroke=\"url(#spinner-secondHalf)\" d={`M${strokeWidthHalf} 100 A${100 - strokeWidthHalf} ${100 - strokeWidthHalf} 0 0 1 ${200 - strokeWidthHalf} 100`} />\n <path stroke=\"url(#spinner-firstHalf)\" d={`M${200 - strokeWidthHalf} 100 A${100 - strokeWidthHalf} ${100 - strokeWidthHalf} 0 0 1 ${strokeWidthHalf} 100`} />\n \n <path\n stroke=\"currentColor\"\n strokeLinecap=\"round\"\n d={`M${strokeWidthHalf} 100 A${100 - strokeWidthHalf} ${100 - strokeWidthHalf} 0 0 1 ${strokeWidthHalf} ${100 - strokeWidthQuarter}`}\n />\n </g>\n \n <animateTransform\n from=\"0 0 0\"\n to=\"360 0 0\"\n attributeName=\"transform\"\n type=\"rotate\"\n repeatCount=\"indefinite\"\n dur=\"1300ms\"\n />\n </svg>\n );\n};","import React, { FC } from \"react\";\n\n/**\n * The handful of Material glyphs the form fields draw, inlined so the fields do not pull in\n * @mui/icons-material (and SvgIcon, and emotion) for six paths. Same 24x24 artwork as the\n * Material icons they replace, and decorative: the control they sit in carries the name.\n */\ninterface FieldIconProps {\n readonly className?: string;\n}\n\nconst icon = (path: string): FC<FieldIconProps> => {\n const FieldIcon: FC<FieldIconProps> = ({ className }) => (\n <svg\n className={className}\n viewBox=\"0 0 24 24\"\n width=\"1em\"\n height=\"1em\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n focusable=\"false\">\n <path d={path} />\n </svg>\n );\n return FieldIcon;\n};\n\nexport const CheckIcon = icon(\"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z\");\n\nexport const CheckBoxIcon = icon(\n \"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z\"\n);\n\nexport const CheckBoxOutlineIcon = icon(\n \"M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z\"\n);\n\nexport const RadioCheckedIcon = icon(\n \"M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z\"\n);\n\nexport const RadioUncheckedIcon = icon(\n \"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z\"\n);\n\nexport const ArrowDropDownIcon = icon(\"M7 10l5 5 5-5z\");\n\nexport const ChevronLeftIcon = icon(\"M15.41 16.59 10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z\");\n\nexport const ChevronRightIcon = icon(\"M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z\");\n","import { MessageBubble } from \"@xapp/chat-widget-core\";\nimport React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./SearchResponseBubble.module.scss\";\n\nexport interface SearchResponseBubbleProps { }\n\nexport const SearchResponseBubble: FC<PropsWithChildren<SearchResponseBubbleProps>> = props => {\n return (\n <div className={styles.xapp_search_response_bubble}>\n <MessageBubble>\n {props.children}\n </MessageBubble>\n </div>\n );\n};","// Note: This is great code that we should move to stentor-utils to help reduce URLs\n// Right now I just copy and pasted this from the widget channel\n\ndeclare type Parser = (rest: string, all: string) => number;\n\nfunction firstIndex(val: string, patterns: readonly string[]) {\n let res = -1;\n for (const pattern of patterns) {\n const index = val.indexOf(pattern);\n if (index >= 0) {\n if (res < 0 || ((res >= 0) && (index < res))) {\n res = index;\n }\n }\n }\n return res;\n}\n\nconst schemeParser: Parser = rest => {\n const next = rest.indexOf(\"://\");\n if (next < 0) return next;\n return next + 3;\n};\n\nconst domainEnds: readonly string[] = [\":\", \"/\"];\nconst portEnds: readonly string[] = [\"/\"];\nconst pathEnds: readonly string[] = [\"?\", \"#\"];\nconst queryEnds: readonly string[] = [\"#\"];\n\nconst domainParser: Parser = rest => {\n return firstIndex(rest, domainEnds);\n};\n\nconst portParser: Parser = rest => {\n if (rest.charAt(0) !== \":\") {\n return -1;\n }\n return firstIndex(rest, portEnds);\n};\n\nconst pathParser: Parser = rest => {\n const res = firstIndex(rest, pathEnds);\n if (res >= 0) {\n return res;\n }\n return rest.length;\n};\n\nconst queryParser: Parser = rest => {\n return firstIndex(rest, queryEnds);\n};\n\nconst parsers: Parser[] = [\n schemeParser,\n domainParser,\n portParser,\n pathParser,\n queryParser\n];\n\nfunction parse(val: string): string[] {\n const parts: string[] = [];\n let rest = val;\n for (const parser of parsers) {\n const newIndex = Math.max(0, parser(rest, val));\n const part = rest.substring(0, newIndex);\n parts.push(part);\n rest = rest.substring(newIndex);\n }\n if (rest) {\n parts.push(rest);\n }\n return parts;\n}\n\nconst ellipsis = \"/...\";\n\nexport function reduceLink(url: string, maxLength: number): string {\n if (!url) return url;\n\n if (url.length < maxLength) return url;\n\n const parts = parse(url); // [scheme, domain, port, path, query, hash]\n\n function getText() {\n return parts.join(\"\");\n }\n\n function overflows() {\n return getText().length > maxLength;\n }\n\n function tryReduce(index: number) {\n if (overflows()) {\n parts[index] = \"\";\n }\n }\n\n if (parts[2] === \":80\" && parts[0] === \"http://\") {\n tryReduce(2);\n }\n if (parts[2] === \":443\" && parts[0] === \"https://\") {\n tryReduce(2);\n }\n\n tryReduce(5);\n tryReduce(4);\n tryReduce(2);\n tryReduce(0);\n\n if (overflows()) {\n const path = parts[3];\n const allButPathLength = getText().length - path.length;\n const available = maxLength - allButPathLength;\n if (available < 0) {\n parts[3] = \"\";\n } else if (available < path.length) {\n const newPathStart = path.length - available + ellipsis.length;\n parts[3] = ellipsis + path.substring(newPathStart)\n }\n }\n\n return getText();\n}\n","import React, { FC } from \"react\";\nimport { ListItem } from \"stentor-models\";\nimport { reduceLink } from \"./utils\";\nimport styles from \"./Card.module.scss\";\n\nexport interface CardProps {\n readonly item: ListItem;\n readonly className?: string;\n}\n\nexport const Card: FC<CardProps> = props => {\n const { item } = props;\n\n const imageUrl = item.image?.url;\n\n return (\n <div className={`${styles.xapp_search_card} ${props.className || \"\"}`}>\n {!!imageUrl &&\n <div className={styles['xapp_search_card__featured']}>\n <div className={styles['xapp_search_card__featured_box']}>\n <img\n src={item.image?.url}\n className={styles['xapp_search_card__img']}\n alt={item.image?.accessibilityText}\n />\n </div>\n </div>\n }\n <div className={styles['xapp_search_card__content']}>\n {!!item.url && <a href={item.url} className={styles['xapp_search_card__title']}>\n {item.title}\n </a>}\n {!!item.url && <div className={styles['xapp_search_card__link']}>{reduceLink(item.url, 40)}</div>}\n <div className={styles['xapp_search_card__description']}>\n {item.description}\n </div>\n </div>\n </div>\n );\n};","import React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./CarouselItem.module.scss\";\n\nexport interface CarouselItemProps {\n readonly className?: string;\n}\n\nexport const CarouselItem: FC<PropsWithChildren<CarouselItemProps>> = props => {\n return (\n <div className={`${styles.xapp_search_carousel_item} ${props.className || \"\"}`}>\n {props.children}\n </div>\n );\n};\n\n","import { IconButton } from \"@xapp/chat-widget-core\";\nimport React, { FC, useCallback, useRef } from \"react\";\nimport { List } from \"stentor-models\";\nimport { Card } from \"../Card\";\nimport { LeftAngleIcon, RightAngleIcon } from \"../icons\";\nimport styles from \"./Carousel.module.scss\";\nimport { CarouselItem } from \"./CarouselItem\";\n\nexport interface CarouselProps {\n readonly list: List;\n}\n\nexport const Carousel: FC<CarouselProps> = props => {\n const { list } = props;\n\n const listRef = useRef<HTMLDivElement>(null);\n\n const scrollIterate = useCallback((func: (item: { position: number, size: number }) => number | undefined) => {\n const container = listRef.current;\n\n if (container) {\n const items = container.getElementsByClassName(\"xapp_search_carousel-item\");\n\n const containerRect = container.getBoundingClientRect();\n\n const length = items.length;\n\n for (let index = 0; index < length; index++) {\n const item = items.item(index);\n if (item) {\n const itemRect = item.getBoundingClientRect();\n const pos = itemRect.left - containerRect.left;\n const res = func({ position: pos, size: itemRect.width });\n if (res !== undefined) {\n container.scrollLeft += res;\n return;\n }\n }\n }\n }\n }, []);\n\n const handlePrev = useCallback(() => {\n let prevPos: undefined | number;\n scrollIterate(item => {\n const threshold = 10;\n if (item.position > -threshold) {\n return prevPos;\n }\n prevPos = item.position;\n return undefined;\n });\n }, [scrollIterate]);\n\n const handleNext = useCallback(() => {\n scrollIterate(item => {\n const threshold = 10;\n if (item.position > threshold) {\n return item.position;\n }\n return undefined;\n });\n }, [scrollIterate]);\n\n return (\n <div className={styles.xapp_search_carousel}>\n <IconButton icon={LeftAngleIcon} className={styles['xapp_search_carousel__prev']} onClick={handlePrev} />\n <div ref={listRef} className={styles['xapp_search_carousel__items']}>\n {list.items.map((item, index) => (\n <CarouselItem key={index} >\n <Card item={item} className={styles['xapp_search_carousel__content']} />\n </CarouselItem>\n ))}\n </div>\n <IconButton icon={RightAngleIcon} className={styles['xapp_search_carousel__next']} onClick={handleNext} />\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { List } from \"stentor-models\";\nimport { Carousel } from \"../Carousel\";\n\nexport interface SearchResponseCarouselDisplayProps {\n readonly carousel: List;\n}\n\nexport const SearchResponseCarouselDisplay: FC<SearchResponseCarouselDisplayProps> = props => {\n const { carousel } = props;\n return (\n <div>\n <Carousel list={carousel} />\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { List } from \"stentor-models\";\nimport { Card } from \"../Card\";\nimport styles from \"./Cards.module.scss\";\n\nexport interface CardsProps {\n readonly list: List;\n}\n\nexport const Cards: FC<CardsProps> = props => {\n const { list } = props;\n\n return (\n <div className={styles.xapp_search_cards}>\n {list.items.map((item, index) => (\n <Card key={index} item={item} />\n ))}\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { SuggestionsGroupHeading } from \"@xapp/chat-widget-core\";\nimport { List } from \"stentor-models\";\nimport { Cards } from \"../Cards\";\n\nexport interface SearchResponseListDisplayProps {\n readonly list: List;\n}\n\nexport const SearchResponseListDisplay: FC<SearchResponseListDisplayProps> = props => {\n const { list } = props;\n\n const title = list?.title;\n\n return (\n <div>\n {title ? <SuggestionsGroupHeading label={title} /> : <></>}\n\n <Cards list={list} />\n </div>\n );\n};\n","type BooleanMap = { [x: string]: boolean };\n\nexport const shallowEqualBooleanMap = (objA: BooleanMap, objB: BooleanMap): boolean => {\n // Get keys\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n\n // Check if number of keys is different\n if (keysA.length !== keysB.length) return false;\n\n // Check if keys or values are different\n for (const key of keysA) {\n if (objA[key] !== objB[key]) return false;\n }\n\n // If passed all checks, objects are considered shallowly equal\n return true;\n};\n\n/**\n *\n * @param input Prefix javascript variables in simple logical expression with \".this\"\n * @returns\n */\nexport const addContextPrefix = (input: string, prefix = \"this\", ignore: string[] = []): string => {\n const functionNames = ignore.map((fn) => fn.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")).join(\"|\");\n const pattern = new RegExp(\n `\\\\b(?<!')(?!(?:if|else|length|for|while|includes|function|var|let|const|return|switch|case|do|true|false|null|undefined|typeof|new|this|void|delete|in|instanceof|export|import${\n functionNames ? `|${functionNames}` : \"\"\n })\\\\b)([a-zA-Z_$][a-zA-Z0-9_$]*)\\\\b`,\n \"g\"\n );\n return input.replace(pattern, `${prefix}.$1`);\n};\n","// Matches the custom `#{key}` delimiter previously configured via lodash.template's\n// `interpolate` option. Only bare key lookups are supported (no expression evaluation)\n// since that is the only form used by templates in this codebase.\nconst TEMPLATE_REGEX = /#{([\\s\\S]+?)}/g;\n\nexport function replaceValues<T>(o: T, data: object): T {\n const values = data as Record<string, unknown>;\n try {\n const json = JSON.stringify(o).replace(TEMPLATE_REGEX, (_match, key) => {\n const trimmedKey = key.trim();\n if (!(trimmedKey in values)) {\n // Matches lodash.template's behavior of throwing when a key is\n // missing from the data object, which the outer catch turns into\n // \"leave the whole object unchanged\".\n throw new Error(`Missing template key \"${trimmedKey}\"`);\n }\n const value = values[trimmedKey];\n return value === null || value === undefined ? \"\" : String(value);\n });\n const escaped = json.replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\\\\r\").replace(/\\t/g, \"\\\\t\");\n return JSON.parse(escaped);\n } catch (error) {\n // Let it go\n // console.error(`Template replace failed: ${error}`);\n }\n\n return o;\n}\n\nfunction getOrdinalSuffix(number: number) {\n if (number >= 11 && number <= 13) {\n return 'th';\n }\n const lastDigit = number % 10;\n switch (lastDigit) {\n case 1:\n return 'st';\n case 2:\n return 'nd';\n case 3:\n return 'rd';\n default:\n return 'th';\n }\n }\n \n export function reformatDate(inputDate: string | number | Date) {\n const date = new Date(inputDate);\n const day = date.getDate();\n const month = date.toLocaleString('default', { month: 'long' });\n const year = date.getFullYear();\n const ordinalSuffix = getOrdinalSuffix(day);\n \n return `${month} ${day}${ordinalSuffix}, ${year}`;\n }\n \n export function joinWithAnd(arr: string[]) {\n if (arr.length === 0) {\n return '';\n } else if (arr.length === 1) {\n return arr[0];\n } else if (arr.length === 2) {\n return arr.join(' and ');\n } else {\n const lastElement = arr.pop(); // Remove the last element\n const joinedString = arr.join(', ') + ', and ' + lastElement;\n return joinedString;\n }\n }\n\n// Tests\n\n// const data = {\n// foo: 3,\n// d: new Date().toDateString(),\n// name: \"Joe Bloe\",\n// a: [\"x\", \"y\", \"z\"]\n// };\n\n// const T = {\n// // eslint-disable-next-line no-template-curly-in-string\n// x: \"${foo} ${a}\"\n// }\n\n// console.log(JSON.stringify(replaceValues(T, data)));","import { ActionableItem, NextBusinessDayBlock, SelectableItem } from \"stentor-models\";\n\nconst CALENDAR_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst CLOCK_TIME = /^(\\d{1,2}):(\\d{2})/;\n\n/**\n * \"HH:MM\" for a clock time such as \"9:00\" or \"09:00:00\", or undefined if it is not one.\n */\nfunction toClock(value?: string): string | undefined {\n const match = typeof value === \"string\" ? CLOCK_TIME.exec(value.trim()) : null;\n\n return match ? `${match[1].padStart(2, \"0\")}:${match[2]}` : undefined;\n}\n\n/**\n * Narrow the untyped `nextBusinessDayBlock` context parameter - the next business day's morning,\n * held back from a lead that arrived after hours - into a block the widget can trust.\n *\n * Both values are already the business's wall clock, so they are compared as they are and\n * never converted through the browser's zone.\n *\n * Context parameters are typed as strings but carry whatever the handler set, so the object\n * and its JSON form are both accepted.\n *\n * @param raw The parameter exactly as it came off the context.\n */\nexport function parseNextBusinessDayBlock(raw: unknown): NextBusinessDayBlock | undefined {\n let value = raw;\n\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch (err) {\n return undefined;\n }\n }\n\n if (!value || typeof value !== \"object\") {\n return undefined;\n }\n\n const { date, blockedUntil } = value as { date?: unknown; blockedUntil?: unknown };\n const clock = toClock(blockedUntil as string);\n\n if (typeof date !== \"string\" || !CALENDAR_DATE.test(date) || !clock) {\n return undefined;\n }\n\n return { date, blockedUntil: clock };\n}\n\n/**\n * Whether a time on a date falls inside the block.\n *\n * @param calendarDate The date being offered, \"YYYY-MM-DD\".\n * @param start When the offering or chip starts.\n * @param block The block off the context, if any.\n */\nexport function isBlockedTime(\n calendarDate: string | undefined,\n start: string | undefined,\n block: NextBusinessDayBlock | undefined\n): boolean {\n const clock = toClock(start);\n\n return !!block && !!clock && calendarDate === block.date && clock < block.blockedUntil;\n}\n\nfunction windowedChips(items: readonly (SelectableItem | ActionableItem)[]): SelectableItem[] {\n return items.filter(\n (item): item is SelectableItem => !!toClock((item as SelectableItem).startTime)\n );\n}\n\n/**\n * The chips that cannot be picked on a date: those whose window starts inside the block.\n * A chip without a start time (\"First Available Time\") is never blocked.\n */\nexport function blockedChipIds(\n items: readonly (SelectableItem | ActionableItem)[],\n calendarDate: string | undefined,\n block: NextBusinessDayBlock | undefined\n): string[] {\n return windowedChips(items)\n .filter((item) => isBlockedTime(calendarDate, item.startTime, block))\n .map((item) => item.id);\n}\n\n/**\n * Whether the block leaves none of the windowed chips on a date, so the date itself should\n * not be offered.\n */\nexport function isDateFullyBlocked(\n items: readonly (SelectableItem | ActionableItem)[],\n calendarDate: string | undefined,\n block: NextBusinessDayBlock | undefined\n): boolean {\n const windowed = windowedChips(items);\n\n return (\n windowed.length > 0 &&\n windowed.every((item) => isBlockedTime(calendarDate, item.startTime, block))\n );\n}\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||\"\").toLowerCase().replace(/s$/,\"\")},u:function(t){return void 0===t}},g=\"en\",D={};D[g]=M;var p=\"$isDayjsObject\",S=function(t){return t instanceof _||!(!t||!t[p])},w=function t(e,n,r){var i;if(!e)return g;if(\"string\"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split(\"-\");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<O(t)},m.$g=function(t,e,n){return b.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!b.u(e)||e,f=b.p(t),l=function(t,e){var i=b.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return b.w(n.toDate()[t].apply(n.toDate(\"s\"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v=\"set\"+(this.$u?\"UTC\":\"\");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+\"Hours\",0);case u:return $(v+\"Minutes\",1);case s:return $(v+\"Seconds\",2);case i:return $(v+\"Milliseconds\",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=b.p(t),f=\"set\"+(this.$u?\"UTC\":\"\"),l=(n={},n[a]=f+\"Date\",n[d]=f+\"Date\",n[c]=f+\"Month\",n[h]=f+\"FullYear\",n[u]=f+\"Hours\",n[s]=f+\"Minutes\",n[i]=f+\"Seconds\",n[r]=f+\"Milliseconds\",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[b.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=b.p(f),y=function(t){var e=O(l);return b.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return b.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||\"YYYY-MM-DDTHH:mm:ssZ\",i=b.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},d=function(t){return b.s(s%12||12,t,\"0\")},$=f||function(t,e,n){var r=t<12?\"AM\":\"PM\";return n?r.toLowerCase():r};return r.replace(y,(function(t,r){return r||function(t){switch(t){case\"YY\":return String(e.$y).slice(-2);case\"YYYY\":return b.s(e.$y,4,\"0\");case\"M\":return a+1;case\"MM\":return b.s(a+1,2,\"0\");case\"MMM\":return h(n.monthsShort,a,c,3);case\"MMMM\":return h(c,a);case\"D\":return e.$D;case\"DD\":return b.s(e.$D,2,\"0\");case\"d\":return String(e.$W);case\"dd\":return h(n.weekdaysMin,e.$W,o,2);case\"ddd\":return h(n.weekdaysShort,e.$W,o,3);case\"dddd\":return o[e.$W];case\"H\":return String(s);case\"HH\":return b.s(s,2,\"0\");case\"h\":return d(1);case\"hh\":return d(2);case\"a\":return $(s,u,!0);case\"A\":return $(s,u,!1);case\"m\":return String(u);case\"mm\":return b.s(u,2,\"0\");case\"s\":return String(e.$s);case\"ss\":return b.s(e.$s,2,\"0\");case\"SSS\":return b.s(e.$ms,3,\"0\");case\"Z\":return i}return null}(t)||i.replace(\":\",\"\")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=this,M=b.p(d),m=O(r),v=(m.utcOffset()-this.utcOffset())*e,g=this-m,D=function(){return b.m(y,m)};switch(M){case h:$=D()/12;break;case c:$=D();break;case f:$=D()/3;break;case o:$=(g-v)/6048e5;break;case a:$=(g-v)/864e5;break;case u:$=g/n;break;case s:$=g/e;break;case i:$=g/t;break;default:$=g}return l?$:b.a($)},m.daysInMonth=function(){return this.endOf(c).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=w(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return b.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),Y=_.prototype;return O.prototype=Y,[[\"$ms\",r],[\"$s\",i],[\"$m\",s],[\"$H\",u],[\"$W\",a],[\"$M\",c],[\"$y\",h],[\"$D\",d]].forEach((function(t){Y[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),O.extend=function(t,e){return t.$i||(t(e,_,O),t.$i=!0),O},O.locale=w,O.isDayjs=S,O.unix=function(t){return O(1e3*t)},O.en=D[g],O.Ls=D,O.p={},O}));","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_timezone=e()}(this,(function(){\"use strict\";var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,r){var o,a=function(t,n,i){void 0===i&&(i={});var r=new Date(t),o=function(t,n){void 0===n&&(n={});var i=n.timeZoneName||\"short\",r=t+\"|\"+i,o=e[r];return o||(o=new Intl.DateTimeFormat(\"en-US\",{hour12:!1,timeZone:t,year:\"numeric\",month:\"2-digit\",day:\"2-digit\",hour:\"2-digit\",minute:\"2-digit\",second:\"2-digit\",timeZoneName:i}),e[r]=o),o}(n,i);return o.formatToParts(r)},u=function(e,n){for(var i=a(e,n),o=[],u=0;u<i.length;u+=1){var f=i[u],s=f.type,m=f.value,c=t[s];c>=0&&(o[c]=parseInt(m,10))}var l=o[3],d=24===l?0:l,h=o[0]+\"-\"+o[1]+\"-\"+o[2]+\" \"+d+\":\"+o[4]+\":\"+o[5]+\":000\",v=+e;return(r.utc(h).valueOf()-(v-=v%1e3))/6e4},f=i.prototype;f.tz=function(t,e){if(void 0===t&&(t=o),!this.isValid())return this;var n,i=this.utcOffset(),a=this.toDate(),f=a.toLocaleString(\"en-US\",{timeZone:t}),s=u(+a,t);if(!Number(s))n=this.utcOffset(0,e);else if(n=r(f,{locale:this.$L}).$set(\"millisecond\",this.$ms).utcOffset(s,!0),e){var m=n.utcOffset();n=n.add(i-m,\"minute\")}return n.$x.$timezone=t,n},f.offsetName=function(t){var e=this.$x.$timezone||r.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find((function(t){return\"timezonename\"===t.type.toLowerCase()}));return n&&n.value};var s=f.startOf;f.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return s.call(this,t,e);var n=r(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\"),{locale:this.$L});return s.call(n,t,e).tz(this.$x.$timezone,!0)},r.tz=function(t,e,n){var i=n&&e,a=n||e||o,f=u(+r(),a);if(\"string\"!=typeof t)return r(t).tz(a);var s=r.utc(t,i).valueOf();if(Number.isNaN(s)){var m=r(NaN);return m.$x.$timezone=a,m}var c=function(t,e,n){var i=t-60*e*1e3,r=u(i,n);if(e===r)return[i,e];var o=u(i-=60*(r-e)*1e3,n);return r===o?[i,r]:[t-60*Math.min(r,o)*1e3,Math.max(r,o)]}(s,f,a),l=c[0],d=c[1],h=r(l).utcOffset(d);return h.$x.$timezone=a,h},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(t){o=t}}}));","!function(t,i){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=i():\"function\"==typeof define&&define.amd?define(i):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_utc=i()}(this,(function(){\"use strict\";var t=\"minute\",i=/[+-]\\d\\d(?::?\\d\\d)?/g,e=/([+-]|\\d\\d)/g;return function(s,f,n){var u=f.prototype;n.utc=function(t){var i={date:t,utc:!0,args:arguments};return new f(i)},u.utc=function(i){var e=n(this.toDate(),{locale:this.$L,utc:!0});return i?e.add(this.utcOffset(),t):e},u.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var r=u.parse;u.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),r.call(this,t)};var o=u.init;u.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else o.call(this)};var a=u.utcOffset;u.utcOffset=function(s,f){var n=this.$utils().u;if(n(s))return this.$u?0:n(this.$offset)?a.call(this):this.$offset;if(\"string\"==typeof s&&(s=function(t){void 0===t&&(t=\"\");var s=t.match(i);if(!s)return null;var f=(\"\"+s[0]).match(e)||[\"-\",0,0],n=f[0],u=60*+f[1]+ +f[2];return 0===u?0:\"+\"===n?u:-u}(s),null===s))return this;var u=Math.abs(s)<=16?60*s:s;if(0===u)return this.utc(f);var r=this.clone();if(f)return r.$offset=u,r.$u=!1,r;var o=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();return(r=this.local().add(u+o,t)).$offset=u,r.$x.$localOffset=o,r};var h=u.format;u.format=function(t){var i=t||(this.$u?\"YYYY-MM-DDTHH:mm:ss[Z]\":\"\");return h.call(this,i)},u.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},u.isUTC=function(){return!!this.$u},u.toISOString=function(){return this.toDate().toISOString()},u.toString=function(){return this.toDate().toUTCString()};var l=u.toDate;u.toDate=function(t){return\"s\"===t&&this.$offset?n(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\")).toDate():l.call(this)};var c=u.diff;u.diff=function(t,i,e){if(t&&this.$u===t.$u)return c.call(this,t,i,e);var s=this.local(),f=n(t).local();return c.call(s,f,i,e)}}}));","import dayjs from \"dayjs\";\nimport timezonePlugin from \"dayjs/plugin/timezone\";\nimport utcPlugin from \"dayjs/plugin/utc\";\n\nimport {\n ClockTime,\n DayOfWeek,\n FormDateTimeInput,\n NextBusinessDayBlock,\n ScheduleException,\n TimeOffering,\n TimeSlotSchedule,\n} from \"stentor-models\";\n\nimport { isBlockedTime } from \"./nextBusinessDayBlock\";\n\ndayjs.extend(utcPlugin);\ndayjs.extend(timezonePlugin);\n\n/**\n * Minutes between generated starts when the schedule does not say.\n */\nexport const DEFAULT_SLOT_MINUTES = 30;\n\n/**\n * How far ahead the calendar reaches when the schedule does not say.\n */\nexport const DEFAULT_HORIZON_DAYS = 60;\n\n/**\n * Field name the chosen date is submitted under when the field does not say.\n *\n * Deliberately fixed rather than derived from the field's own name: every existing lead\n * consumer already reads `preferred_date`, and namespacing it per field would break all of\n * them to solve a problem only a two-DATETIME step has. A step carrying two of these must\n * set `dateFieldName` on at least one, or the second silently overwrites the first.\n */\nexport const DEFAULT_DATE_FIELD_NAME = \"preferred_date\";\n\n/**\n * Field name the combined ISO timestamp is submitted under when the field does not say.\n *\n * Fixed for the same reason as {@link DEFAULT_DATE_FIELD_NAME}, and additionally because\n * `datetime` is the name the lead analyzer already recognises and ISO-validates. See\n * `dateTimeFieldName` to move it.\n */\nexport const DEFAULT_DATE_TIME_FIELD_NAME = \"datetime\";\n\n/**\n * Field name the schedule's timezone is submitted under when the field does not say.\n *\n * Fixed for the same reason as {@link DEFAULT_DATE_FIELD_NAME}. It exists so a consumer\n * can tell a picker-produced `datetime` from a scraped one: an abandoned form contributes\n * fields literally named `date` or `appointment_time` straight into the lead with no\n * validation, and \"carries an offset\" cannot say who produced the value. This can.\n */\nexport const DEFAULT_TIME_ZONE_FIELD_NAME = \"preferred_time_zone\";\n\n/**\n * `FormDateTimeInput` with the name its timezone field is submitted under.\n *\n * Declared here rather than read off the model because `timeZoneFieldName` is newer than\n * the `stentor-models` pinned by this package; it collapses back into `FormDateTimeInput`\n * once that version lands.\n */\nexport interface FormDateTimeInputWithTimeZone extends FormDateTimeInput {\n /**\n * Field name the schedule's IANA timezone is submitted under. Defaults to\n * \"preferred_time_zone\".\n */\n timeZoneFieldName?: string;\n}\n\nconst MS_PER_DAY = 86400000;\n\n/**\n * A fixed offset rather than a zone, e.g. \"-04:00\". Also catches a bare offset like \"-4\".\n */\nconst FIXED_OFFSET = /^[+-]?\\d/;\n\n/**\n * An arbitrary instant, only ever used to ask whether a zone identifier resolves at all.\n */\nconst ZONE_PROBE = \"2026-01-01T00:00\";\n\n// Indexed to match Date#getUTCDay().\nconst WEEKDAYS: DayOfWeek[] = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n];\n\nconst CLOCK_TIME = /^(\\d{1,2}):(\\d{2})/;\n\n/**\n * Minutes past midnight for a \"HH:MM\" clock time, or -1 for anything unparseable.\n *\n * A schedule is authored by hand in Studio, so a malformed time is a real possibility\n * and has to drop the span rather than generate slots at NaN.\n */\nfunction clockToMinutes(clock: ClockTime): number {\n const match = CLOCK_TIME.exec(clock || \"\");\n\n if (!match) {\n return -1;\n }\n\n const hours = Number(match[1]);\n const minutes = Number(match[2]);\n\n if (hours > 23 || minutes > 59) {\n return -1;\n }\n\n return hours * 60 + minutes;\n}\n\nfunction pad(value: number): string {\n return value < 10 ? `0${value}` : `${value}`;\n}\n\nfunction minutesToClock(minutes: number): ClockTime {\n // Past midnight wraps, so a duration that runs over the end of the day still reads\n // as a time rather than as \"24:30\".\n const wrapped = ((minutes % 1440) + 1440) % 1440;\n\n return `${pad(Math.floor(wrapped / 60))}:${pad(wrapped % 60)}`;\n}\n\n/**\n * The calendar date a `Date` represents, as \"YYYY-MM-DD\".\n *\n * Read off the local fields rather than through `toISOString`, which converts to UTC and\n * so reports the next day for an evening selection anywhere west of Greenwich.\n */\nexport function toCalendarDate(date: Date): string {\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n}\n\n/**\n * The weekday a \"YYYY-MM-DD\" calendar date falls on.\n */\nfunction weekdayOf(calendarDate: string): DayOfWeek | undefined {\n const parsed = new Date(`${calendarDate}T00:00:00Z`);\n\n return isNaN(parsed.getTime()) ? undefined : WEEKDAYS[parsed.getUTCDay()];\n}\n\n/**\n * Whole days from one calendar date to another, ignoring time of day entirely - so a\n * daylight-saving transition in between cannot make the answer come out fractional.\n */\nfunction daysBetween(from: string, to: string): number {\n return Math.round(\n (Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / MS_PER_DAY\n );\n}\n\n/**\n * Whether a zone can actually be used to place a wall-clock time.\n *\n * A schedule's zone is typed in by hand in Studio, so \"Eastern\" or \"America/New York\"\n * reaches the picker as readily as a real IANA identifier does. Matching is case\n * insensitive, so \"America/New_york\" is fine.\n */\nexport function isUsableTimezone(timezone?: string): boolean {\n if (!timezone) {\n return false;\n }\n\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n\n return true;\n } catch (err) {\n return false;\n }\n}\n\n/**\n * The zone the visitor's own browser is in, or \"\" where that cannot be determined.\n */\nexport function hostTimezone(): string {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"\";\n } catch (err) {\n return \"\";\n }\n}\n\n// Generic first, so a zone reads as \"Eastern Time\" rather than as whichever side of a\n// daylight-saving transition today happens to fall on - the times below it span both.\n// \"long\" is the fallback for a platform too old to know the generic form.\nconst TIMEZONE_NAME_STYLES = [\"longGeneric\", \"long\"];\n\n/**\n * A zone named the way a visitor reads it, e.g. \"America/New_York\" to \"Eastern Time\".\n *\n * Falls back to the identifier itself rather than to nothing, because an unnamed zone\n * still tells a visitor more than silence does.\n */\nexport function formatTimezoneLabel(timezone?: string): string {\n if (!timezone) {\n return \"\";\n }\n\n for (const timeZoneName of TIMEZONE_NAME_STYLES) {\n try {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n timeZoneName,\n } as Intl.DateTimeFormatOptions).formatToParts(new Date());\n const named = parts.find((part) => part.type === \"timeZoneName\");\n\n if (named && named.value) {\n return named.value;\n }\n } catch (err) {\n // Either the zone or the naming style is unsupported here. Try the next\n // style, then give up on naming it at all.\n }\n }\n\n return timezone;\n}\n\n/**\n * The instant a wall-clock time on a calendar date happens, in the schedule's zone.\n *\n * An unknown zone falls back to the host's, because a picker that renders slightly wrong\n * times is better than one that throws while the visitor is looking at it.\n */\nfunction zonedInstant(calendarDate: string, clock: ClockTime, timezone: string): number {\n const local = `${calendarDate}T${clock}`;\n\n try {\n return dayjs.tz(local, timezone).valueOf();\n } catch (err) {\n return dayjs(local).valueOf();\n }\n}\n\n/**\n * An offset-bearing ISO 8601 timestamp for a wall-clock time in the given zone, e.g.\n * \"2026-08-24T09:30:00-04:00\". The offset is the one in force on that date, so the value\n * survives a daylight-saving transition.\n */\nexport function toOffsetIso(calendarDate: string, clock: ClockTime, timezone: string): string {\n const minutes = clockToMinutes(clock);\n const normalized = minutes < 0 ? clock : minutesToClock(minutes);\n const local = `${calendarDate}T${normalized}`;\n\n try {\n return dayjs.tz(local, timezone).format();\n } catch (err) {\n return dayjs(local).format();\n }\n}\n\n/**\n * The zone the picker really built its times in, as the IANA identifier the schedule\n * authored - or nothing at all when it did not.\n *\n * {@link zonedInstant} and {@link toOffsetIso} both fall back to the host's zone rather\n * than throwing at a visitor mid-form, so an absent or unrecognised `timezone` still\n * produces a full column of times: they are simply the wrong ones. Naming the business's\n * zone beside those would hand a consumer a marker it cannot trust, and a wrong marker is\n * worse than none - the entire point of the field is that it can be trusted - so nothing\n * is reported instead.\n *\n * A fixed offset is refused for the same reason. `Intl` accepts \"-04:00\", so the times\n * generated from it are self-consistent, but an offset does not survive a daylight-saving\n * transition and so cannot stand in for the zone.\n */\nexport function timeZoneOf(schedule: TimeSlotSchedule): string | undefined {\n const timezone = schedule?.timezone;\n\n if (!timezone || typeof timezone !== \"string\" || FIXED_OFFSET.test(timezone)) {\n return undefined;\n }\n\n try {\n // The same call zonedInstant makes, so the two cannot disagree about which zones\n // are usable and the marker cannot outlive the fallback it is meant to detect.\n if (!dayjs.tz(ZONE_PROBE, timezone).isValid()) {\n return undefined;\n }\n } catch (err) {\n return undefined;\n }\n\n return timezone;\n}\n\n/**\n * A 12-hour rendering of a clock time, e.g. \"09:30\" to \"9:30 AM\".\n */\nfunction formatClock(clock: ClockTime): string {\n const minutes = clockToMinutes(clock);\n\n if (minutes < 0) {\n return clock;\n }\n\n const hours24 = Math.floor(minutes / 60);\n const hours12 = hours24 % 12 === 0 ? 12 : hours24 % 12;\n\n return `${hours12}:${pad(minutes % 60)} ${hours24 < 12 ? \"AM\" : \"PM\"}`;\n}\n\n/**\n * What an offering reads as in the time column - and, because the label is what the field\n * submits, what a CRM or lead consumer receives for it.\n */\nexport function formatOfferingLabel(offering: TimeOffering): string {\n if (!offering) {\n return \"\";\n }\n\n if (offering.label) {\n return offering.label;\n }\n\n const start = formatClock(offering.start);\n\n return offering.end ? `${start} - ${formatClock(offering.end)}` : start;\n}\n\n/**\n * How far ahead the calendar reaches, so the picker's own maxDate and the selectability\n * rules cannot drift apart.\n */\nexport function horizonDaysOf(schedule: TimeSlotSchedule): number {\n const horizon = schedule?.horizonDays;\n\n // 0 is a real answer here - \"today only\" - unlike slotMinutes or durationMinutes where\n // it is meaningless. Testing truthiness handed a same-day-only business the 60 day\n // default instead, which is the opposite of what they asked for.\n return typeof horizon === \"number\" && horizon >= 0 ? horizon : DEFAULT_HORIZON_DAYS;\n}\n\n/**\n * The open booking windows a CRM reported, per calendar date (\"YYYY-MM-DD\"), as wall-clock\n * times in the schedule's zone.\n *\n * Arrives as `offeringsByDate` on the BusyDays context. When present it is the whole truth\n * about which dates are open: a date absent from it, or mapped to an empty list, is closed.\n */\nexport interface OfferingsByDate {\n readonly [date: string]: readonly TimeOffering[];\n}\n\nfunction isOffering(value: unknown): value is TimeOffering {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as TimeOffering).start === \"string\"\n );\n}\n\n/**\n * Narrow the untyped `offeringsByDate` context parameter into a map the picker can trust.\n *\n * Context parameters are typed as strings but carry whatever the handler put there, so an\n * object and its JSON serialisation are both accepted. Entries without a `start` are dropped,\n * and a date whose value is not a list reads as closed rather than as \"use the schedule\".\n *\n * @param raw The parameter exactly as it came off the context.\n */\nexport function parseOfferingsByDate(raw: unknown): OfferingsByDate | undefined {\n let value = raw;\n\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch (err) {\n return undefined;\n }\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const map: { [date: string]: TimeOffering[] } = {};\n\n Object.entries(value as Record<string, unknown>).forEach(([date, offerings]) => {\n map[date] = Array.isArray(offerings) ? offerings.filter(isOffering) : [];\n });\n\n return map;\n}\n\nfunction findException(\n schedule: TimeSlotSchedule,\n calendarDate: string\n): ScheduleException | undefined {\n return (schedule.exceptions || []).find((exception) => exception.date === calendarDate);\n}\n\n/**\n * Drop the offerings that have already passed, measured in the schedule's zone rather than\n * the visitor's.\n *\n * A time earlier today is never bookable, whether or not the schedule sets a lead time —\n * `leadTimeMinutes` pushes the cutoff further out, it does not create it. Treating lead time\n * as the only mechanism let a schedule that omitted it offer 9:00 AM at 3 in the afternoon.\n */\nfunction filterElapsed(\n offerings: TimeOffering[],\n schedule: TimeSlotSchedule,\n calendarDate: string,\n now: Date\n): TimeOffering[] {\n const lead = schedule.leadTimeMinutes;\n const buffer = lead && lead > 0 ? lead : 0;\n const cutoff = now.getTime() + buffer * 60000;\n\n return offerings.filter(\n (offering) => zonedInstant(calendarDate, offering.start, schedule.timezone) >= cutoff\n );\n}\n\n/**\n * The times a schedule offers on one calendar date.\n *\n * Slots come from the schedule alone - there is no availability lookup behind this, so a\n * date change repaints the column without a round trip. The rules, in order:\n *\n * 1. `offerings` present replaces generation. `days`, `slotMinutes` and `durationMinutes`\n * are not consulted. A closing exception still closes the date, because that is the\n * only way a fixed offering list can express a holiday.\n * 2. Otherwise the weekday's spans, or the spans of an `exceptions` entry for this exact\n * date, which *replace* the weekday's rather than adding to them. No spans is closed.\n * 3. Each span is walked in `slotMinutes` steps, up to but not including its end.\n * 4. `durationMinutes` gives every offering an `end`; without it they are discrete starts.\n * A start whose appointment would run past the span's end is not offered at all.\n * 5. Whatever survives is filtered against now, plus `leadTimeMinutes` if the schedule\n * sets one. A time earlier today is never offered.\n *\n * `offeringsByDate`, when given, comes before all of these: the date's entry is offered as\n * is, and a date without one is closed. Only the elapsed filter of rule 5 still applies.\n *\n * @param schedule The schedule to read.\n * @param date The calendar day being offered, read off its local fields.\n * @param now The current moment. Injectable so the lead-time filter is testable.\n * @param offeringsByDate The CRM's own windows per date, replacing the schedule's.\n * @param block The next business day's morning held back from an after-hours lead.\n * Applied last, to whichever offerings the rules above produced.\n */\nexport function generateOfferings(\n schedule: TimeSlotSchedule,\n date: Date,\n now: Date = new Date(),\n offeringsByDate?: OfferingsByDate,\n block?: NextBusinessDayBlock\n): TimeOffering[] {\n if (!schedule || !date || isNaN(date.getTime())) {\n return [];\n }\n\n const calendarDate = toCalendarDate(date);\n\n return generateUnblockedOfferings(schedule, calendarDate, now, offeringsByDate).filter(\n (offering) => !isBlockedTime(calendarDate, offering.start, block)\n );\n}\n\nfunction generateUnblockedOfferings(\n schedule: TimeSlotSchedule,\n calendarDate: string,\n now: Date,\n offeringsByDate?: OfferingsByDate\n): TimeOffering[] {\n\n if (offeringsByDate) {\n return filterElapsed([...(offeringsByDate[calendarDate] || [])], schedule, calendarDate, now);\n }\n const exception = findException(schedule, calendarDate);\n\n if (Array.isArray(schedule.offerings)) {\n // No spans reads as closed here exactly as it does on the generated path below.\n // `spans` is required by the type, but a schedule is authored in Studio and arrives\n // as config, so `{ date: \"2026-12-25\" }` used as a holiday marker has to close the\n // date rather than quietly fall through to the normal offerings.\n if (exception && (!exception.spans || exception.spans.length === 0)) {\n return [];\n }\n\n return filterElapsed(schedule.offerings, schedule, calendarDate, now);\n }\n\n const weekday = weekdayOf(calendarDate);\n const spans = exception\n ? exception.spans || []\n : (weekday && (schedule.days || {})[weekday]) || [];\n\n const step =\n schedule.slotMinutes && schedule.slotMinutes > 0\n ? schedule.slotMinutes\n : DEFAULT_SLOT_MINUTES;\n const duration =\n schedule.durationMinutes && schedule.durationMinutes > 0\n ? schedule.durationMinutes\n : undefined;\n\n const offerings: TimeOffering[] = [];\n\n for (const span of spans) {\n const start = clockToMinutes(span?.start);\n const end = clockToMinutes(span?.end);\n\n if (start < 0 || end < 0) {\n continue;\n }\n\n for (let minutes = start; minutes < end; minutes += step) {\n // The whole appointment has to fit inside the span, which is what Calendly does:\n // 9:00-12:00 at 60 minutes offers 11:00 last, never 11:30. Clipping the end\n // instead would keep the slot but advertise a length the business is not open\n // for, and a span exists precisely to protect what follows it - a lunch break,\n // or closing time.\n if (duration && minutes + duration > end) {\n break;\n }\n\n const offering: TimeOffering = { start: minutesToClock(minutes) };\n\n if (duration) {\n offering.end = minutesToClock(minutes + duration);\n }\n\n offerings.push(offering);\n }\n }\n\n return filterElapsed(offerings, schedule, calendarDate, now);\n}\n\n/**\n * Whether the calendar should let a date be picked.\n *\n * False for anything outside the horizon - in the past, or further ahead than\n * `horizonDays` - and for any date the schedule generates no offerings for, so a closed\n * day greys out rather than opening onto an empty column.\n *\n * @param schedule The schedule to read.\n * @param date The calendar day being tested, read off its local fields.\n * @param now The current moment. Injectable so the horizon is testable.\n * @param offeringsByDate The CRM's own windows per date, see {@link generateOfferings}.\n * @param block The after-hours block, see {@link generateOfferings}.\n */\nexport function isDateSelectable(\n schedule: TimeSlotSchedule,\n date: Date,\n now: Date = new Date(),\n offeringsByDate?: OfferingsByDate,\n block?: NextBusinessDayBlock\n): boolean {\n if (!schedule || !date || isNaN(date.getTime())) {\n return false;\n }\n\n const calendarDate = toCalendarDate(date);\n const horizon = horizonDaysOf(schedule);\n\n // Today is the business's today, not the visitor's - they are frequently different days.\n const today = todayInZone(schedule.timezone, now);\n const offset = daysBetween(today, calendarDate);\n\n if (offset < 0 || offset > horizon) {\n return false;\n }\n\n return generateOfferings(schedule, date, now, offeringsByDate, block).length > 0;\n}\n\n/**\n * The soonest day the calendar would let someone pick, or nothing.\n *\n * Deliberately expressed as a walk over {@link isDateSelectable} rather than by\n * reasoning about the schedule's shape: the answer must be a day the calendar\n * itself would enable, and duplicating that rule is how the two drift into\n * offering a date that then greys out.\n *\n * Bounded by the schedule's own horizon, so an empty schedule -- or one whose\n * every remaining day is full -- terminates and returns undefined rather than\n * searching forever.\n *\n * @param schedule The schedule to read.\n * @param now The current moment. Injectable so the horizon is testable.\n * @param isBusy Days the CRM has declared full, tested one at a time.\n * @param offeringsByDate The CRM's own windows per date, see {@link generateOfferings}.\n * @param block The after-hours block, see {@link generateOfferings}.\n */\nexport function firstSelectableDate(\n schedule: TimeSlotSchedule,\n now: Date = new Date(),\n isBusy: (date: Date) => boolean = () => false,\n offeringsByDate?: OfferingsByDate,\n block?: NextBusinessDayBlock\n): Date | undefined {\n if (!schedule) {\n return undefined;\n }\n\n // From the business's today, not the visitor's -- frequently a different day,\n // and starting from the wrong one can skip a day that is still bookable.\n const today = todayInZone(schedule.timezone, now);\n\n for (let offset = 0; offset <= horizonDaysOf(schedule); offset++) {\n const day = dayjs(`${today}T00:00:00`).add(offset, \"day\").toDate();\n\n if (isDateSelectable(schedule, day, now, offeringsByDate, block) && !isBusy(day)) {\n return day;\n }\n }\n\n return undefined;\n}\n\n/**\n * The calendar date it currently is in the given zone.\n */\nfunction todayInZone(timezone: string, now: Date): string {\n try {\n return dayjs(now).tz(timezone).format(\"YYYY-MM-DD\");\n } catch (err) {\n return toCalendarDate(now);\n }\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport { err } from \".\";\n\n/**\n * Shape of the `externalWidget` block on a booking-handoff form step.\n *\n * This mirrors `FormStepExternalWidget[\"externalWidget\"]` from\n * `stentor-models@1.75.0`. See the local type-extension note in\n * `FormStepDisplay.tsx` for why it is redeclared here instead of imported.\n */\nexport interface ExternalWidgetConfig {\n anchorId: string;\n scriptSrc: string;\n configGlobal: string;\n config: Record<string, string | number | boolean>;\n successCallbackKey?: string;\n cacheBust?: boolean;\n renderTimeoutMs?: number;\n fallbackStep?: string;\n}\n\nexport type ExternalWidgetOutcome = \"pending\" | \"rendered\" | \"no_render\" | \"error\";\n\nexport interface UseExternalWidgetOptions {\n /**\n * Fired once the anchor renders a bookable `#step-*` (any step other than a\n * no-match or loading step, e.g. `step-schedule` or the returning-visitor\n * `step-review`).\n */\n onRendered?: (provider: string) => void;\n /**\n * Fired when the anchor renders a no-match step (no coverage), or stays empty\n * with no `#step-loading` past the backstop `renderTimeoutMs`.\n */\n onNoRender?: (provider: string) => void;\n /**\n * Fired at most once per mounted handoff, the first time the partner script invokes\n * the configured success callback. Later invocations within the same handoff are\n * suppressed, reported to the console and counted (see `suppressedScheduledCount`)\n * -- CostGuide confirmed (2026-08-13) that it fires \"whenever an appointment gets\n * scheduled\", so a single handoff can produce more than one fire and a duplicate\n * dispatch double-counts the booking downstream.\n *\n * Suppression is deliberately NOT its own analytics event: a new eventType needs a\n * matching server-side eventName mapping in stentor-api, which is out of scope here.\n * The console error is the signal that works today in a visitor's browser, and\n * `suppressedScheduledCount` is there for a caller that wants to act on it.\n *\n * `payload` is whatever (if anything) the partner passes to it. CostGuide passes\n * nothing today -- it is a bare trigger with no appointment id, time or contractor --\n * but the parameter is kept tolerant in case that changes.\n */\n onScheduled?: (provider: string, payload?: unknown) => void;\n /**\n * Fired when the script fails to load, or the scriptSrc is rejected.\n */\n onError?: (provider: string) => void;\n /**\n * Fired alongside onNoRender/onError when `externalWidget.fallbackStep` is set,\n * so the caller can navigate there. Not fired when fallbackStep is unset --\n * the caller is expected to render an inline fallback message instead.\n */\n onFallback?: (fallbackStep: string) => void;\n}\n\nconst DEFAULT_RENDER_TIMEOUT_MS = 8000;\n\n// The partner form renders exactly one `#step-*` container at a time with stable\n// ids, so the step id -- not a blind \"anchor has children\" check -- is the render\n// signal. Render timing was measured at 111ms-18.7s against the same endpoint, so\n// a fixed timer can only ever be a backstop for \"the script never arrived\".\nconst LOADING_STEP_ID = \"step-loading\";\nconst NO_MATCH_STEP_IDS = [\n \"step-nomatch\",\n \"step-nomatchaggregator\",\n \"step-no-match-financing\",\n \"step-payPerCallNoneAvailable\",\n];\n// While the anchor still shows `#step-loading` at timeout we extend rather than\n// fail (the 18.7s worst case would otherwise dead-end a homeowner after we already\n// took their details). Bounded so a stuck loader eventually settles as no_render.\nconst MAX_RENDER_TIMEOUT_EXTENSIONS = 3;\n\ntype AnchorState = \"rendered\" | \"no_coverage\" | \"loading\" | \"empty\";\n\n/**\n * Classifies the current state of the anchor from the partner step id it shows.\n *\n * - a no-match step id -> \"no_coverage\" (a real screen, but no bookable coverage)\n * - `step-loading` -> \"loading\" (still working; do not fail yet)\n * - any other `step-*` -> \"rendered\" (e.g. `step-schedule`, or the\n * returning-visitor `step-review` -- do NOT assume one)\n * - no `step-*` present -> \"empty\" (not rendered yet)\n */\nexport function classifyAnchor(anchor: HTMLElement): AnchorState {\n const stepEls = anchor.querySelectorAll('[id^=\"step-\"]');\n if (stepEls.length === 0) {\n return \"empty\";\n }\n let hasLoading = false;\n for (let i = 0; i < stepEls.length; i++) {\n const id = stepEls[i].id;\n if (NO_MATCH_STEP_IDS.indexOf(id) !== -1) {\n return \"no_coverage\";\n }\n if (id === LOADING_STEP_ID) {\n hasLoading = true;\n continue;\n }\n return \"rendered\";\n }\n return hasLoading ? \"loading\" : \"empty\";\n}\n\n/**\n * Derives the analytics `provider` string from the partner script's hostname.\n */\nexport function getExternalWidgetProvider(scriptSrc: string | undefined): string {\n if (!scriptSrc) {\n return \"unknown\";\n }\n try {\n return new URL(scriptSrc).hostname;\n } catch {\n return \"unknown\";\n }\n}\n\nfunction isValidScriptSrc(scriptSrc: string): boolean {\n try {\n const parsed = new URL(scriptSrc);\n return parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n}\n\n// Scripts are appended to document.body and never removed. A module-level guard\n// (mirroring useTrustedForm's existingScript check) ensures the same partner\n// origin is only loaded once per page, even across separate mounted instances.\nconst SCRIPT_ORIGIN_ATTRIBUTE = \"data-xapp-external-widget-origin\";\n\n/**\n * Drives the mount sequence for a third-party booking-widget handoff step:\n * assigns the merged config to `window[configGlobal]` (including the wired-up\n * success callback), appends the partner's embed script, and watches the\n * anchor for a render-timeout outcome.\n *\n * The mount sequence runs at most once per component lifetime (guarded by a\n * ref) the first time `externalWidget` is defined. If the config object is\n * later replaced with a new reference (e.g. a slower FORM_SUBMIT response\n * merging server values in after the step already rendered), the global is\n * re-assigned with the latest values but the script is not re-appended and\n * the timer is not restarted.\n */\nexport function useExternalWidget(\n externalWidget: ExternalWidgetConfig | undefined,\n options: UseExternalWidgetOptions = {}\n): { outcome: ExternalWidgetOutcome; suppressedScheduledCount: number } {\n // onScheduled is read from optionsRef inside the mount effect (so a late\n // callback change is picked up without re-running the effect), not destructured here.\n const { onRendered, onNoRender, onError, onFallback } = options;\n\n const [outcome, setOutcome] = useState<ExternalWidgetOutcome>(\"pending\");\n // Repeats are suppressed, not discarded: if the partner starts firing twice for every\n // booking we want that visible rather than merely harmless.\n const [suppressedScheduledCount, setSuppressedScheduledCount] = useState(0);\n\n const hasMountedRef = useRef(false);\n // Per mounted handoff, so a genuine re-mount (the visitor returns and books again) is a\n // new handoff and may fire again. Survives a refreshed config replacing the global.\n const scheduledFiredRef = useRef(false);\n const suppressedScheduledRef = useRef(0);\n const outcomeSettledRef = useRef(false);\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!externalWidget) {\n return undefined;\n }\n\n const provider = getExternalWidgetProvider(externalWidget.scriptSrc);\n\n // Config may be refreshed (e.g. by a merged FORM_SUBMIT response) on a later\n // render of the same mounted step -- keep the global current either way.\n const globalConfig: Record<string, unknown> = { ...externalWidget.config };\n if (externalWidget.successCallbackKey) {\n const successCallbackKey = externalWidget.successCallbackKey;\n globalConfig[successCallbackKey] = (payload?: unknown) => {\n if (scheduledFiredRef.current) {\n suppressedScheduledRef.current += 1;\n // err, NOT log: `log` is gated on window.xaLogLevel === \"debug\", which no\n // visitor's browser sets, so a repeat in the wild would be invisible -- the\n // opposite of the point. A partner firing its success hook twice for one\n // booking is an anomaly worth a console error, the same treatment this hook\n // already gives a rejected script origin and a failed script load.\n err(\n `[ExternalWidget] Suppressed repeat ${successCallbackKey} fire ` +\n `#${suppressedScheduledRef.current} from ${provider}`,\n payload\n );\n setSuppressedScheduledCount(suppressedScheduledRef.current);\n return;\n }\n scheduledFiredRef.current = true;\n optionsRef.current.onScheduled?.(provider, payload);\n };\n }\n (window as unknown as Record<string, unknown>)[externalWidget.configGlobal] = globalConfig;\n\n if (hasMountedRef.current) {\n return undefined;\n }\n hasMountedRef.current = true;\n\n const settle = (nextOutcome: ExternalWidgetOutcome, notify: (() => void) | undefined) => {\n if (outcomeSettledRef.current) {\n return;\n }\n outcomeSettledRef.current = true;\n setOutcome(nextOutcome);\n notify?.();\n if (nextOutcome !== \"rendered\" && externalWidget.fallbackStep) {\n onFallback?.(externalWidget.fallbackStep);\n }\n };\n\n if (!isValidScriptSrc(externalWidget.scriptSrc)) {\n err(\n `[ExternalWidget] Rejected script URL from unexpected origin: ${externalWidget.scriptSrc}`\n );\n settle(\"error\", () => onError?.(provider));\n return undefined;\n }\n\n const anchor = document.getElementById(externalWidget.anchorId);\n const timeoutMs = externalWidget.renderTimeoutMs ?? DEFAULT_RENDER_TIMEOUT_MS;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let observer: MutationObserver | undefined;\n let extensions = 0;\n\n const handleRendered = () => settle(\"rendered\", () => onRendered?.(provider));\n const handleNoRender = () => settle(\"no_render\", () => onNoRender?.(provider));\n\n // Settle on a decisive step id. Returns true once the outcome is settled.\n const evaluate = (el: HTMLElement | null): boolean => {\n if (!el) {\n return false;\n }\n const state = classifyAnchor(el);\n if (state === \"rendered\") {\n handleRendered();\n return true;\n }\n if (state === \"no_coverage\") {\n handleNoRender();\n return true;\n }\n return false; // \"loading\" | \"empty\" -> keep waiting\n };\n\n const onTimeout = () => {\n if (outcomeSettledRef.current) {\n return;\n }\n const currentAnchor = document.getElementById(externalWidget.anchorId);\n if (evaluate(currentAnchor)) {\n return;\n }\n // Still loading? Extend rather than declare a false no-render.\n if (\n currentAnchor &&\n classifyAnchor(currentAnchor) === \"loading\" &&\n extensions < MAX_RENDER_TIMEOUT_EXTENSIONS\n ) {\n extensions += 1;\n timeoutId = setTimeout(onTimeout, timeoutMs);\n return;\n }\n // Empty past the backstop (or stuck loading) -> hard failure.\n handleNoRender();\n };\n\n const settledOnMount = evaluate(anchor);\n if (!settledOnMount) {\n if (anchor) {\n observer = new MutationObserver(() => {\n evaluate(document.getElementById(externalWidget.anchorId));\n });\n observer.observe(anchor, { childList: true, subtree: true });\n }\n timeoutId = setTimeout(onTimeout, timeoutMs);\n }\n\n let origin: string;\n try {\n origin = new URL(externalWidget.scriptSrc).origin;\n } catch {\n origin = externalWidget.scriptSrc;\n }\n\n const existingScript = document.querySelector(\n `script[${SCRIPT_ORIGIN_ATTRIBUTE}=\"${origin}\"]`\n );\n\n if (!existingScript) {\n const script = document.createElement(\"script\");\n script.src = externalWidget.cacheBust\n ? `${externalWidget.scriptSrc}${\n externalWidget.scriptSrc.includes(\"?\") ? \"&\" : \"?\"\n }v=${Date.now()}`\n : externalWidget.scriptSrc;\n script.setAttribute(SCRIPT_ORIGIN_ATTRIBUTE, origin);\n script.onerror = () => {\n err(`[ExternalWidget] Failed to load script: ${externalWidget.scriptSrc}`);\n settle(\"error\", () => onError?.(provider));\n };\n // Intentionally no cleanup on unmount -- mirrors useTrustedForm.\n document.body.appendChild(script);\n }\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n observer?.disconnect();\n };\n // Only the identity of externalWidget should re-trigger the mount sequence;\n // the notify callbacks are read from optionsRef to avoid re-running on every\n // parent re-render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [externalWidget]);\n\n return { outcome, suppressedScheduledCount };\n}\n","import React, { FC, useEffect, useId, useState } from \"react\";\nimport { FormSelectInput } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\nimport { CheckBoxIcon, CheckBoxOutlineIcon, RadioCheckedIcon, RadioUncheckedIcon } from \"../icons\";\n\nimport styles from \"./FormFieldSelect.module.scss\";\n\nexport interface FormSelectProps extends FormFieldProps {\n readonly field: Styleable<FormSelectInput>;\n}\n\nexport const FormFieldSelect: FC<FormSelectProps> = (props) => {\n const { field, onFieldChange, errorMessage } = props;\n\n const [selectValue, setSelectValue] = useState<string[]>([]); // array for checkboxes\n const [radioValue, setRadioValue] = useState<string>(\"\"); // single value for radio\n\n const onCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const { name, checked } = e.target;\n setSelectValue((prevOptions) => {\n if (checked) {\n return [...prevOptions, name];\n } else {\n return prevOptions.filter((option) => option !== name);\n }\n });\n };\n\n const onRadioChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n setRadioValue(e.target.value);\n };\n\n const id = `xapp-select-${useId()}`;\n const titleId = `${id}-title`;\n const helperId = `${id}-helper-text`;\n const invalid = !!errorMessage;\n\n useEffect(() => {\n if (field.radio) {\n onFieldChange(field.name, radioValue ? [radioValue] : []);\n } else {\n onFieldChange(field.name, selectValue);\n }\n }, [selectValue, radioValue, field.name, field.radio, onFieldChange]);\n\n return (\n <div style={{ ...field.style }}>\n <div\n className={`${styles.xapp_select_title_container}${!field.title ? \"__empty\" : \"\"}`}>\n <p id={titleId}>{field.title}</p>\n </div>\n\n {/* Native radios sharing one name get arrow-key movement and single selection from\n the browser; the group names them by the step's question. */}\n <div\n className={styles.xapp_select_container}\n role={field.radio ? \"radiogroup\" : \"group\"}\n // A radio cannot carry aria-invalid; its group can. Checkboxes carry their own.\n aria-invalid={(field.radio && invalid) || undefined}\n aria-labelledby={field.title ? titleId : undefined}\n aria-describedby={invalid ? helperId : undefined}>\n {field.items.map((item) => {\n const checked = field.radio ? radioValue === item.id : selectValue.includes(item.id);\n const Icon = field.radio\n ? checked\n ? RadioCheckedIcon\n : RadioUncheckedIcon\n : checked\n ? CheckBoxIcon\n : CheckBoxOutlineIcon;\n\n return (\n <label key={item.id} className={styles.xapp_select_option}>\n <span\n className={`${styles.xapp_checkbox_select} ${\n checked ? styles.xapp_checkbox_select_checked : \"\"\n }`}>\n {field.radio ? (\n <input\n type=\"radio\"\n className={styles.xapp_select_input}\n name={field.name}\n value={item.id}\n checked={checked}\n onChange={onRadioChange}\n />\n ) : (\n <input\n type=\"checkbox\"\n className={styles.xapp_select_input}\n name={item.id}\n checked={checked}\n onChange={onCheckboxChange}\n aria-invalid={invalid || undefined}\n />\n )}\n <Icon className={styles.xapp_select_icon} />\n </span>\n <span className={styles.xapp_select_label}>{item.label}</span>\n </label>\n );\n })}\n </div>\n\n {errorMessage && (\n <p id={helperId} className={styles.xapp_select_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n );\n};\n\nexport default FormFieldSelect;\n","import React, { FC } from \"react\";\n\nimport { FormCardInput } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport styles from \"./FormFieldCard.module.scss\";\n\nexport interface FormCardProps extends FormFieldProps {\n readonly field: Styleable<FormCardInput>;\n}\n\n/**\n * The element each text variant renders as -- MUI Typography's default variant mapping, which\n * this card used until #1741. The variant's look comes from FormFieldCard.module.scss.\n */\nconst VARIANT_ELEMENTS: Record<string, \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\" | \"p\" | \"span\"> = {\n h1: \"h1\",\n h2: \"h2\",\n h3: \"h3\",\n h4: \"h4\",\n h5: \"h5\",\n h6: \"h6\",\n subtitle1: \"h6\",\n subtitle2: \"h6\",\n body1: \"p\",\n body2: \"p\",\n inherit: \"p\",\n button: \"span\",\n caption: \"span\",\n overline: \"span\",\n};\n\nconst DEFAULT_VARIANT = \"body2\";\n\n/**\n * Typography's palette shorthands, at the default MUI theme's values. Anything else is taken\n * to be a CSS colour and passed straight through, as Typography did.\n */\nconst PALETTE_COLORS: Record<string, string> = {\n primary: \"#1976d2\",\n secondary: \"#9c27b0\",\n error: \"#d32f2f\",\n warning: \"#ed6c02\",\n info: \"#0288d1\",\n success: \"#2e7d32\",\n textPrimary: \"rgba(0, 0, 0, 0.87)\",\n textSecondary: \"rgba(0, 0, 0, 0.6)\",\n textDisabled: \"rgba(0, 0, 0, 0.38)\",\n \"text.primary\": \"rgba(0, 0, 0, 0.87)\",\n \"text.secondary\": \"rgba(0, 0, 0, 0.6)\",\n \"text.disabled\": \"rgba(0, 0, 0, 0.38)\",\n};\n\nconst DEFAULT_COLOR = \"textSecondary\";\n\nfunction resolveColor(color: string): string {\n return PALETTE_COLORS[color] || color;\n}\n\nexport const FormFieldCard: FC<FormCardProps> = (props) => {\n const { field } = props;\n\n const variant = field.variant && VARIANT_ELEMENTS[field.variant] ? field.variant : DEFAULT_VARIANT;\n const Text = VARIANT_ELEMENTS[variant];\n\n return (\n <div className={styles.xapp_form_card}>\n <div className={styles.xapp_form_card_body}>\n {field.header && (\n <div className={styles.xapp_form_card_header}>\n <span className={styles.xapp_form_card_header_title}>{field.header.title}</span>\n {field.header.subheader && (\n <span className={styles.xapp_form_card_header_subheader}>{field.header.subheader}</span>\n )}\n </div>\n )}\n\n {field.media && (\n <img\n className={styles.xapp_form_card_media}\n src={field.media.imageUrl}\n alt={field.media.alt}\n height={field.media.height}\n width={field.media.width}\n />\n )}\n\n {field.text && (\n <div className={styles.xapp_form_card_content}>\n <Text\n className={`${styles.xapp_form_card_text} ${styles[`xapp_form_card_text_${variant}`] || \"\"}`}\n data-variant={variant}\n style={{\n whiteSpace: \"pre-line\",\n textAlign: (field.align || \"center\") as React.CSSProperties[\"textAlign\"],\n color: resolveColor(field.color || DEFAULT_COLOR),\n ...field.style,\n }}>\n {field.text}\n </Text>\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default FormFieldCard;\n","import React, { FC, useEffect, useId, useState } from \"react\";\n\nimport { FormChipsInput, ActionableItem, SelectableItem } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\nimport { CheckIcon } from \"../icons\";\n\nimport styles from \"./FormFieldChips.module.scss\";\n\nexport function isSelectableItem(item: ActionableItem | SelectableItem): item is SelectableItem {\n return !!item && !(item as ActionableItem).url;\n}\n\nexport function isActionableItem(item: ActionableItem | SelectableItem): item is ActionableItem {\n return !!(item as ActionableItem).url;\n}\n\nexport interface FormFieldChipsProps extends FormFieldProps {\n readonly field: Styleable<FormChipsInput>;\n /** Optional prefilled value that takes precedence over items' selected state.\n * Only used for initial mount; late-arriving updates (after mount) are not supported. */\n readonly value?: string[];\n /** Chips that cannot be picked right now; one already selected is cleared. */\n readonly disabledItemIds?: readonly string[];\n}\n\nexport const FormFieldChips: FC<FormFieldChipsProps> = (props) => {\n const { field, onFieldChange, errorMessage, value, disabledItemIds } = props;\n\n /**\n * Selected chips\n */\n // Use prefilled value if provided, otherwise look for pre-selected items\n const selectedFromProps = value || props.field.items\n .filter(isSelectableItem) // filter out actionable items\n .filter((item) => item.selected)\n .map((item) => item.id);\n const [selectedChips, setSelectedChips] = useState<string[]>(selectedFromProps); // array!\n\n // Keyed on the joined ids so a new array with the same contents does not re-run it.\n const disabledKey = (disabledItemIds || []).join(\",\");\n\n useEffect(() => {\n const disabled = disabledKey ? disabledKey.split(\",\") : [];\n if (disabled.length > 0) {\n setSelectedChips((prev) => {\n const next = prev.filter((chipId) => !disabled.includes(chipId));\n return next.length === prev.length ? prev : next;\n });\n }\n }, [disabledKey]);\n\n const handleChipClick = (id: string) => {\n if (disabledItemIds?.includes(id)) {\n return;\n }\n\n const checked = selectedChips.includes(id);\n\n if (field.radio) {\n setSelectedChips((_prevOptions) => {\n if (!checked) {\n return [id]; // add\n } else {\n return []; // delete\n }\n });\n } else {\n setSelectedChips((prevOptions) => {\n if (!checked) {\n return [...prevOptions, id]; // add\n } else {\n return prevOptions.filter((option) => option !== id); // delete\n }\n });\n }\n };\n\n const id = `xapp-chips-${useId()}`;\n const titleId = `${id}-title`;\n const helperId = `${id}-helper-text`;\n\n useEffect(() => {\n if (typeof onFieldChange === \"function\") {\n onFieldChange(field.name, selectedChips);\n }\n }, [selectedChips, field.name, onFieldChange]);\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignContent: \"center\",\n alignItems: \"center\",\n }}>\n <div\n className={`${styles.xapp_chips_title_container}${!field.title ? \"__empty\" : \"\"}`}\n style={{ ...field.style }}>\n <p id={titleId}>{field.title}</p>\n </div>\n\n <div\n className={styles.xapp_chips_container}\n role=\"group\"\n aria-labelledby={field.title ? titleId : undefined}\n aria-describedby={errorMessage ? helperId : undefined}>\n {field.items.map((item, index) => {\n const selected = selectedChips.includes(item.id);\n const disabled = !!disabledItemIds?.includes(item.id);\n const className = `${styles.xapp_checkbox_chip} ${selected ? styles.xapp_chip_clicked : \"\"}`;\n const content = (\n <>\n {selected && <CheckIcon className={styles.xapp_chip_icon} />}\n <span className={styles.xapp_chip_label}>{item.label}</span>\n </>\n );\n\n if (isSelectableItem(item)) {\n return (\n <div key={index} className={styles.xapp_chip_wrapper}>\n <button\n type=\"button\"\n aria-pressed={selected}\n disabled={disabled}\n onClick={() => handleChipClick(item.id)}\n className={className}>\n {content}\n </button>\n </div>\n );\n } else if (isActionableItem(item)) {\n return (\n <div key={index} className={styles.xapp_chip_wrapper}>\n <a href={item.url} className={`${className} ${styles.xapp_chip_link}`}>\n {content}\n </a>\n </div>\n );\n } else {\n return <></>;\n }\n })}\n </div>\n\n {errorMessage && (\n <p id={helperId} className={styles.xapp_chips_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n );\n};\n\nexport default FormFieldChips;\n","import { FormTextInput } from \"stentor-models\";\n\n/**\n * The HTML input helper attributes we derive for a form field.\n *\n * These are what give mobile users the right keyboard and let iOS/Android\n * AutoFill offer the right saved value - neither happens without explicit tokens.\n */\nexport interface InputHelperProps {\n /**\n * The real HTML input type. Note this is NOT FormInput.type, which is the\n * widget discriminator (\"TEXT\" | \"DROPDOWN\" | ...) and is not a valid input type.\n */\n readonly type: \"text\" | \"tel\" | \"email\";\n readonly inputMode: \"text\" | \"tel\" | \"email\" | \"numeric\";\n /**\n * Left off entirely when we cannot confidently pick a token - a wrong\n * autocomplete is worse than none.\n */\n readonly autoComplete?: string;\n readonly enterKeyHint: \"next\" | \"done\";\n}\n\nexport interface FormatToInputPropsRequest {\n readonly format?: FormTextInput[\"format\"];\n readonly name?: string;\n /**\n * When true the keyboard shows \"done\" rather than \"next\".\n */\n readonly isLastField?: boolean;\n}\n\ntype FormatMapping = Omit<InputHelperProps, \"enterKeyHint\">;\n\nconst FORMAT_PROPS: Record<NonNullable<FormTextInput[\"format\"]>, FormatMapping> = {\n PHONE: { type: \"tel\", inputMode: \"tel\", autoComplete: \"tel\" },\n EMAIL: { type: \"email\", inputMode: \"email\", autoComplete: \"email\" },\n // Deliberately not type=\"number\" - that adds spinners and strips the leading\n // zero from real US postal codes such as 02134.\n ZIP_CODE: { type: \"text\", inputMode: \"numeric\", autoComplete: \"postal-code\" },\n ADDRESS: { type: \"text\", inputMode: \"text\", autoComplete: \"street-address\" },\n};\n\nconst DEFAULT_PROPS: FormatMapping = { type: \"text\", inputMode: \"text\" };\n\n/**\n * Field names we can map to an autocomplete token without guessing. Keys are\n * normalized - lowercased with everything but letters and digits removed - so\n * \"FULL_NAME\", \"fullName\" and \"full name\" all land on the same entry.\n *\n * Keep this conservative. Anything ambiguous belongs on field.format instead.\n */\nconst NAME_AUTOCOMPLETE: Record<string, string> = {\n name: \"name\",\n fullname: \"name\",\n yourname: \"name\",\n customername: \"name\",\n contactname: \"name\",\n firstname: \"given-name\",\n fname: \"given-name\",\n givenname: \"given-name\",\n lastname: \"family-name\",\n lname: \"family-name\",\n surname: \"family-name\",\n familyname: \"family-name\",\n email: \"email\",\n emailaddress: \"email\",\n phone: \"tel\",\n phonenumber: \"tel\",\n telephone: \"tel\",\n tel: \"tel\",\n mobile: \"tel\",\n mobilephone: \"tel\",\n cellphone: \"tel\",\n zip: \"postal-code\",\n zipcode: \"postal-code\",\n postalcode: \"postal-code\",\n postcode: \"postal-code\",\n address: \"street-address\",\n streetaddress: \"street-address\",\n street: \"street-address\",\n city: \"address-level2\",\n town: \"address-level2\",\n state: \"address-level1\",\n province: \"address-level1\",\n company: \"organization\",\n companyname: \"organization\",\n organization: \"organization\",\n business: \"organization\",\n businessname: \"organization\",\n};\n\nfunction autoCompleteFromName(name?: string): string | undefined {\n if (!name) {\n return undefined;\n }\n\n return NAME_AUTOCOMPLETE[name.toLowerCase().replace(/[^a-z0-9]/g, \"\")];\n}\n\n/**\n * Derive the mobile input helper attributes for a text field.\n *\n * `field.format` carries the real semantics (\"PHONE\", \"ZIP_CODE\", ...); when it\n * is unset we fall back to plain text and only infer autoComplete from the field\n * name where that is unambiguous.\n */\nexport function formatToInputProps(request: FormatToInputPropsRequest): InputHelperProps {\n const { format, name, isLastField } = request;\n\n const mapped = format ? FORMAT_PROPS[format] : undefined;\n const enterKeyHint = isLastField ? \"done\" : \"next\";\n\n if (mapped) {\n return { ...mapped, enterKeyHint };\n }\n\n const autoComplete = autoCompleteFromName(name);\n\n return autoComplete\n ? { ...DEFAULT_PROPS, autoComplete, enterKeyHint }\n : { ...DEFAULT_PROPS, enterKeyHint };\n}\n\nexport default formatToInputProps;\n","import React, { FC, useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\n\nimport { FormTextInput } from \"stentor-models\";\n\nimport { Styleable } from \"../../types\";\nimport { formatToInputProps } from \"../../utils/formatToInputProps\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport styles from \"./FormFieldTextInput.module.scss\";\n\nexport interface FormTextInputProps extends FormFieldProps {\n readonly field: Styleable<FormTextInput>;\n readonly value?: string | undefined;\n /**\n * When this is the last field of the step the keyboard shows \"done\" rather than \"next\".\n */\n readonly isLastField?: boolean;\n}\n\n// Show counter when within this percentage of the limit\nconst COUNTER_THRESHOLD_PERCENT = 0.8;\n\nexport const FormFieldTextInput: FC<FormTextInputProps> = (props) => {\n const { field, onFieldChange, value, errorMessage, required, isLastField } = props;\n\n const [text, setText] = useState(value || \"\");\n const [focused, setFocused] = useState(false);\n\n const id = `xapp-text-${useId()}`;\n const helperId = `${id}-helper-text`;\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const { value } = e.target;\n setText(value);\n };\n\n useEffect(() => {\n onFieldChange(field.name, text);\n }, [field.name, onFieldChange, text]);\n\n useEffect(() => {\n setText(value || \"\");\n }, [value]);\n\n // A multiline field with no fixed `rows` grows with its content up to `rowsMax`, the way the\n // MUI textarea it replaces did. Fixed `rows` is left to the browser.\n const autosize = !!field.multiline && !field.rows;\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!autosize || !textarea) {\n return;\n }\n textarea.style.height = \"auto\";\n const lineHeight = parseFloat(getComputedStyle(textarea).lineHeight) || 0;\n const maxHeight = field.rowsMax && lineHeight ? lineHeight * field.rowsMax : Infinity;\n const next = Math.min(textarea.scrollHeight, maxHeight);\n if (next > 0) {\n textarea.style.height = `${next}px`;\n }\n }, [autosize, field.rowsMax, text]);\n\n const maxLength = field.maxLength;\n const currentLength = text.length;\n const isAtLimit = maxLength !== undefined && currentLength >= maxLength;\n const showCounter = maxLength !== undefined && currentLength >= maxLength * COUNTER_THRESHOLD_PERCENT;\n\n // field.type is the widget discriminator (\"TEXT\" | \"DROPDOWN\" | ...), not an HTML\n // input type - the real semantics live on field.format.\n const { type, ...inputHelpers } = formatToInputProps({\n format: field.format,\n name: field.name,\n isLastField,\n });\n\n // MUI's floating label: resting inside the field until it is focused or has a value. With no\n // label to collide with, the placeholder is always shown.\n const shrink = focused || text.length > 0 || !field.label;\n\n const controlProps = {\n ...inputHelpers,\n id,\n name: field.name,\n className: styles.xapp_text_input_control,\n placeholder: field.placeholder,\n value: text,\n onChange,\n onFocus: () => setFocused(true),\n onBlur: () => setFocused(false),\n required,\n maxLength: field.maxLength || undefined,\n \"aria-invalid\": !!errorMessage,\n \"aria-describedby\": errorMessage ? helperId : undefined,\n // Read by the stylesheet, which hides the placeholder behind a resting label.\n \"data-shrink\": shrink ? \"true\" : \"false\",\n };\n\n return (\n <div className={styles.xapp_text_input_container}>\n {field.title && (\n <div className={styles[\"xapp_text_input_container__title\"]}>\n <p>{field.title}</p>\n </div>\n )}\n\n <div className={styles[\"xapp_text_input_container__field\"]}>\n <div\n className={`${styles.xapp_text_input_text} ${errorMessage ? styles.xapp_text_input_error : \"\"}`}\n style={field.style}>\n <div\n className={`${styles.xapp_text_input_root} ${focused ? styles.xapp_text_input_focused : \"\"} ${\n field.multiline ? styles.xapp_text_input_multiline : \"\"\n }`}>\n {field.label && (\n <label\n htmlFor={id}\n className={styles.xapp_text_input_label}\n data-shrink={shrink ? \"true\" : \"false\"}>\n {field.label}\n {required && (\n <span className={styles.xapp_text_input_asterisk} aria-hidden=\"true\">\n {\" *\"}\n </span>\n )}\n </label>\n )}\n {field.multiline ? (\n <textarea {...controlProps} ref={textareaRef} rows={field.rows || 1} />\n ) : (\n <input {...controlProps} type={type} />\n )}\n </div>\n {errorMessage && (\n <p id={helperId} className={styles.xapp_text_input_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n {showCounter && (\n <div className={`${styles.xapp_text_input_counter} ${isAtLimit ? styles[\"xapp_text_input_counter--limit\"] : \"\"}`}>\n {currentLength}/{maxLength}\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default FormFieldTextInput;\n","import React, { FC, useEffect, useRef, useState } from \"react\";\n\nimport { FormDropdownInput } from \"stentor-models\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\nimport { ArrowDropDownIcon } from \"../icons\";\n\nimport styles from \"./FormFieldDropdown.module.scss\";\n\nconst PLACEHOLDER_LABEL = \"Select an option\";\n\n/**\n * Extended SelectableItem interface to support free-form text input for dropdown items.\n * This allows dropdown options to trigger an additional text input field when selected.\n *\n * Note: This extends the stentor-models SelectableItem type with additional properties.\n * Consider adding these properties to stentor-models SelectableItem in a future release\n * if this pattern becomes widely used across the platform.\n */\nexport interface SelectableItemWithFreeForm {\n label: string;\n id: string;\n selected?: boolean;\n /**\n * If true, shows a free-form text input field when this item is selected.\n * Useful for \"Other\" options that require additional user input.\n */\n freeFormInput?: boolean;\n /**\n * Custom field name for the free-form input value.\n * Defaults to \"message\" if not specified.\n * This allows multiple dropdowns to have different free-form field names.\n */\n freeFormFieldName?: string;\n}\n\nexport interface FormDropdownProps extends FormFieldProps {\n readonly field: FormDropdownInput;\n}\n\nexport const FormFieldDropdown: FC<FormDropdownProps> = (props) => {\n const { field, onFieldChange, errorMessage, required, freeFormErrorMessage } = props;\n\n const helperId = `${field.name}-helper-text`;\n const freeFormId = `${field.name}-free-form`;\n const freeFormHelperId = `${freeFormId}-helper-text`;\n\n const [dropValue, setDropValue] = useState(() => {\n const selectedItem = field.items.find(item => item.selected);\n return selectedItem?.id || \"none\";\n });\n const [freeFormValue, setFreeFormValue] = useState(\"\");\n const [showFreeForm, setShowFreeForm] = useState(() => {\n const selectedItem = field.items.find(item => item.selected) as SelectableItemWithFreeForm;\n return selectedItem?.freeFormInput || false;\n });\n\n const onChange = (e: React.ChangeEvent<HTMLSelectElement>) => {\n const { value } = e.target;\n\n // Get the previous selected item to clear its free-form value if needed\n const prevSelectedItem = field.items.find(\n (item) => item.id === dropValue\n ) as SelectableItemWithFreeForm;\n\n setDropValue(value);\n\n // Check if the selected item has freeFormInput enabled\n const selectedItem = field.items.find(\n (item) => item.id === value\n ) as SelectableItemWithFreeForm;\n if (selectedItem && selectedItem.freeFormInput) {\n setShowFreeForm(true);\n } else {\n setShowFreeForm(false);\n\n // Only clear if switching away from a free-form item AND there was actually a value\n if (prevSelectedItem?.freeFormInput && freeFormValue) {\n const messageFieldName = prevSelectedItem?.freeFormFieldName || \"message\";\n setFreeFormValue(\"\"); // Clear local state\n onFieldChange(messageFieldName, \"\"); // Clear parent state\n }\n }\n };\n\n const onFreeFormChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n setFreeFormValue(e.target.value);\n };\n\n // Track onFieldChange reference to detect if it's not memoized in development\n const onFieldChangeRef = useRef(onFieldChange);\n useEffect(() => {\n if (process.env.NODE_ENV === \"development\" && onFieldChangeRef.current !== onFieldChange) {\n console.warn(\n \"FormFieldDropdown: onFieldChange prop is not memoized. \" +\n \"This may cause performance issues. Please wrap it in useCallback in the parent component.\"\n );\n }\n onFieldChangeRef.current = onFieldChange;\n }, [onFieldChange]);\n\n // Get the current free-form field name if applicable\n const currentFreeFormFieldName = React.useMemo(() => {\n if (showFreeForm) {\n const selectedItem = field.items.find(\n (item) => item.id === dropValue\n ) as SelectableItemWithFreeForm;\n return selectedItem?.freeFormFieldName || \"message\";\n }\n return null;\n }, [showFreeForm, dropValue, field.items]);\n\n // IMPORTANT: Parent components MUST use useCallback for onFieldChange\n // to prevent infinite re-renders. See FormStepDisplay.tsx:352-373 for correct usage.\n useEffect(() => {\n // Send the raw dropdown ID value (formatting happens during text interpolation)\n if (dropValue !== \"none\") {\n onFieldChange(field.name, dropValue);\n }\n\n // If freeform is active and has a value, also send it to the configured field name\n if (showFreeForm && freeFormValue && currentFreeFormFieldName) {\n onFieldChange(currentFreeFormFieldName, freeFormValue);\n }\n }, [dropValue, freeFormValue, showFreeForm, field.name, currentFreeFormFieldName, onFieldChange]);\n\n // A native <select> at every width. Mobile already had it -- the OS wheel/sheet picker,\n // momentum scrolling, no focus trap inside the fixed modal -- and desktop now gets the same\n // control in place of MUI's listbox (#1741). The outline and floating label are drawn to\n // match the outlined MUI field it replaces.\n return (\n <div className={styles.xapp_dropdown_container}>\n <div className={`${styles.xapp_dropdown_control} ${errorMessage ? styles.xapp_dropdown_error : \"\"}`}>\n <label htmlFor={field.name} className={styles.xapp_dropdown_label}>\n {field.title}\n {required && <span aria-hidden=\"true\">{\" *\"}</span>}\n </label>\n <select\n className={styles.xapp_dropdown_select}\n name={field.name}\n id={field.name}\n value={dropValue}\n onChange={onChange}\n required={required}\n aria-invalid={!!errorMessage}\n aria-describedby={errorMessage ? helperId : undefined}>\n <option value=\"none\">{PLACEHOLDER_LABEL}</option>\n {field.items.map((item) => (\n <option key={item.id} value={item.id}>\n {item.label}\n </option>\n ))}\n </select>\n <ArrowDropDownIcon className={styles.xapp_dropdown_arrow} />\n <fieldset aria-hidden=\"true\" className={styles.xapp_dropdown_outline}>\n <legend>\n <span>\n {field.title}\n {required && \" *\"}\n </span>\n </legend>\n </fieldset>\n </div>\n {errorMessage && (\n <p id={helperId} className={styles.xapp_dropdown_helper}>\n {errorMessage}\n </p>\n )}\n\n {showFreeForm && (\n <div className={styles.xapp_dropdown_free_form}>\n <input\n type=\"text\"\n id={freeFormId}\n className={`${styles.xapp_dropdown_free_form_input} ${\n freeFormErrorMessage ? styles.xapp_dropdown_error : \"\"\n }`}\n required\n placeholder=\"Please specify\"\n aria-label=\"Please specify\"\n value={freeFormValue}\n onChange={onFreeFormChange}\n maxLength={field.maxLength || undefined}\n aria-invalid={!!freeFormErrorMessage}\n aria-describedby={freeFormErrorMessage ? freeFormHelperId : undefined}\n />\n {freeFormErrorMessage && (\n <p id={freeFormHelperId} className={styles.xapp_dropdown_helper}>\n {freeFormErrorMessage}\n </p>\n )}\n </div>\n )}\n </div>\n );\n};\n\nexport default FormFieldDropdown;\n","import React, {\n FC,\n KeyboardEvent,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport dayjs, { Dayjs } from \"dayjs\";\n\nimport { ChevronLeftIcon, ChevronRightIcon } from \"../icons/FieldIcons\";\n\nimport styles from \"./Calendar.module.scss\";\n\n/**\n * Extra classes for the calendar's parts, so a field can restyle them from its own stylesheet.\n */\nexport interface CalendarClasses {\n readonly header?: string;\n readonly weekday?: string;\n readonly weeks?: string;\n readonly day?: string;\n readonly daySelected?: string;\n readonly dayToday?: string;\n}\n\nexport interface CalendarProps {\n /**\n * The selected day, if any.\n */\n readonly value?: Dayjs | null;\n /**\n * Called with the picked day, at the start of that day in local time.\n */\n readonly onChange: (day: Dayjs) => void;\n /**\n * Whether a day can not be picked. Days before `minDate` and after `maxDate` are\n * already excluded and never reach this.\n */\n readonly shouldDisableDate?: (day: Dayjs) => boolean;\n /**\n * The first day that can be picked. The previous-month arrow stops at its month.\n */\n readonly minDate?: Dayjs;\n /**\n * The last day that can be picked. The next-month arrow stops at its month.\n */\n readonly maxDate?: Dayjs;\n /**\n * The day marked as today. Injectable so a caller that is handed its own \"now\" marks\n * the same day it judges availability against. Defaults to the real clock.\n */\n readonly today?: Dayjs;\n /**\n * The month to open on when there is no value. Defaults to today's.\n */\n readonly referenceDate?: Dayjs;\n /**\n * Availability is still being fetched: the days are replaced by a skeleton.\n */\n readonly loading?: boolean;\n /**\n * Draw the neighbouring months' days in the leading and trailing weeks instead of\n * leaving those cells blank.\n */\n readonly showDaysOutsideCurrentMonth?: boolean;\n /**\n * Always draw this many weeks, padding with the following month's, so the calendar\n * does not change height between months.\n */\n readonly fixedWeekNumber?: number;\n /**\n * An extra class for a day, on top of the calendar's own.\n */\n readonly getDayClassName?: (day: Dayjs, disabled: boolean) => string | undefined;\n readonly classes?: CalendarClasses;\n readonly className?: string;\n}\n\n/**\n * The longest a keyboard search walks looking for a day that can be picked, so a calendar\n * with nothing available can never loop.\n */\nconst SEARCH_LIMIT_DAYS = 366;\n\nconst FULL_DATE_FORMAT = \"dddd, MMMM D, YYYY\";\n\nfunction classNames(...names: (string | false | undefined)[]): string {\n return names.filter((name) => !!name).join(\" \");\n}\n\n/**\n * The weeks drawn for a month, Sunday first, padded with the following month's weeks up\n * to `fixedWeekNumber`.\n */\nfunction weeksOf(month: Dayjs, fixedWeekNumber?: number): Dayjs[][] {\n const first = month.startOf(\"month\");\n const weeksInMonth = Math.ceil((first.day() + first.daysInMonth()) / 7);\n const count = Math.max(weeksInMonth, fixedWeekNumber || 0);\n const start = first.startOf(\"week\");\n\n return Array.from({ length: count }, (_, week) =>\n Array.from({ length: 7 }, (__, day) => start.add(week * 7 + day, \"day\"))\n );\n}\n\n/**\n * A month grid of days in the ARIA grid pattern, replacing @mui/x-date-pickers' DateCalendar\n * (#1745).\n *\n * One day is in the tab order at a time; the arrow keys move between days, skipping any that\n * can not be picked, Page Up and Page Down move a month, and Home and End go to the start and\n * end of the week. Each day is named by its full date, so a screen reader announces \"Monday,\n * August 24, 2026\" rather than \"24\".\n */\nexport const Calendar: FC<CalendarProps> = (props) => {\n const {\n value,\n onChange,\n shouldDisableDate,\n minDate,\n maxDate,\n referenceDate,\n loading,\n showDaysOutsideCurrentMonth,\n fixedWeekNumber,\n getDayClassName,\n classes = {},\n className,\n } = props;\n\n const today = useMemo(\n () => (props.today || dayjs()).startOf(\"day\"),\n // Keyed on the day, so a caller handing down a fresh object each render is not a change.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [props.today ? props.today.format(\"YYYY-MM-DD\") : undefined]\n );\n\n const labelId = useId();\n const gridRef = useRef<HTMLDivElement>(null);\n // Set when the keyboard moves the focused day, so the effect below moves real focus to it.\n const focusOnRender = useRef(false);\n\n const [month, setMonth] = useState<Dayjs>(() =>\n (value || referenceDate || today).startOf(\"month\")\n );\n const [focusedDay, setFocusedDay] = useState<Dayjs>(() => (value || today).startOf(\"day\"));\n\n // A value set from outside -- a resumed selection, a preselected date -- brings its month\n // into view, as MUI's calendar did.\n const valueKey = value ? value.format(\"YYYY-MM-DD\") : undefined;\n useEffect(() => {\n if (!value) {\n return;\n }\n\n setFocusedDay(value.startOf(\"day\"));\n setMonth((current) => (value.isSame(current, \"month\") ? current : value.startOf(\"month\")));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [valueKey]);\n\n const isOutOfRange = useCallback(\n (day: Dayjs): boolean =>\n (!!minDate && day.isBefore(minDate, \"day\")) ||\n (!!maxDate && day.isAfter(maxDate, \"day\")),\n [minDate, maxDate]\n );\n\n const isDisabled = useCallback(\n (day: Dayjs): boolean =>\n isOutOfRange(day) || (!!shouldDisableDate && shouldDisableDate(day)),\n [isOutOfRange, shouldDisableDate]\n );\n\n /**\n * The nearest day to `target` between `from` and `to` inclusive that can be picked.\n */\n const closestEnabled = useCallback(\n (target: Dayjs, from: Dayjs, to: Dayjs): Dayjs | undefined => {\n const clamped = target.isBefore(from, \"day\")\n ? from\n : target.isAfter(to, \"day\")\n ? to\n : target;\n const span = to.diff(from, \"day\");\n\n for (let offset = 0; offset <= span; offset++) {\n for (const candidate of [clamped.add(-offset, \"day\"), clamped.add(offset, \"day\")]) {\n if (\n !candidate.isBefore(from, \"day\") &&\n !candidate.isAfter(to, \"day\") &&\n !isDisabled(candidate)\n ) {\n return candidate;\n }\n }\n }\n\n return undefined;\n },\n [isDisabled]\n );\n\n // The one day in the tab order: the focused day when it is in view and can be picked,\n // otherwise the nearest one in this month that can.\n const tabbableDay = useMemo(() => {\n if (focusedDay.isSame(month, \"month\") && !isDisabled(focusedDay)) {\n return focusedDay;\n }\n\n return closestEnabled(\n focusedDay,\n month.startOf(\"month\"),\n month.endOf(\"month\").startOf(\"day\")\n );\n }, [focusedDay, month, isDisabled, closestEnabled]);\n\n useEffect(() => {\n if (!focusOnRender.current) {\n return;\n }\n focusOnRender.current = false;\n\n const timestamp = String(focusedDay.valueOf());\n const target = gridRef.current?.querySelector<HTMLElement>(\n `[data-timestamp=\"${timestamp}\"]`\n );\n target?.focus();\n }, [focusedDay, month]);\n\n const moveFocus = (day: Dayjs) => {\n focusOnRender.current = true;\n setFocusedDay(day);\n if (!day.isSame(month, \"month\")) {\n setMonth(day.startOf(\"month\"));\n }\n };\n\n /** Walk from `day` in steps of `delta` days to the first one that can be picked. */\n const step = (day: Dayjs, delta: number): Dayjs | undefined => {\n let candidate = day;\n\n for (let walked = 0; walked < SEARCH_LIMIT_DAYS; walked += Math.abs(delta)) {\n candidate = candidate.add(delta, \"day\");\n if (isOutOfRange(candidate)) {\n return undefined;\n }\n if (!isDisabled(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n };\n\n /** The first day that can be picked walking from `from` towards `to`, inclusive. */\n const scan = (from: Dayjs, to: Dayjs): Dayjs | undefined => {\n const direction = to.isBefore(from, \"day\") ? -1 : 1;\n const span = Math.abs(to.diff(from, \"day\"));\n\n for (let offset = 0; offset <= span; offset++) {\n const candidate = from.add(offset * direction, \"day\");\n if (!isDisabled(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n };\n\n /** The same day of the month `delta` months away, or the nearest day there that can be picked. */\n const monthJump = (day: Dayjs, delta: number): Dayjs | undefined => {\n const target = day.add(delta, \"month\");\n return closestEnabled(\n target,\n target.startOf(\"month\"),\n target.endOf(\"month\").startOf(\"day\")\n );\n };\n\n const onDayKeyDown = (event: KeyboardEvent<HTMLButtonElement>, day: Dayjs) => {\n let next: Dayjs | undefined;\n\n switch (event.key) {\n case \"ArrowLeft\":\n next = step(day, -1);\n break;\n case \"ArrowRight\":\n next = step(day, 1);\n break;\n case \"ArrowUp\":\n next = step(day, -7);\n break;\n case \"ArrowDown\":\n next = step(day, 7);\n break;\n case \"Home\":\n case \"End\": {\n let edge =\n event.key === \"Home\" ? day.startOf(\"week\") : day.endOf(\"week\").startOf(\"day\");\n // With the neighbouring months' days left blank, the week ends at the month's edge.\n if (!showDaysOutsideCurrentMonth && !edge.isSame(day, \"month\")) {\n edge =\n event.key === \"Home\"\n ? day.startOf(\"month\")\n : day.endOf(\"month\").startOf(\"day\");\n }\n next = scan(edge, day);\n break;\n }\n case \"PageUp\":\n next = monthJump(day, -1);\n break;\n case \"PageDown\":\n next = monthJump(day, 1);\n break;\n default:\n return;\n }\n\n event.preventDefault();\n\n if (next && !next.isSame(day, \"day\")) {\n moveFocus(next);\n }\n };\n\n const onDayClick = (day: Dayjs) => {\n setFocusedDay(day);\n if (!day.isSame(month, \"month\")) {\n setMonth(day.startOf(\"month\"));\n }\n onChange(day);\n };\n\n const previousDisabled = !!minDate && !month.isAfter(minDate, \"month\");\n const nextDisabled = !!maxDate && !month.isBefore(maxDate, \"month\");\n\n const weeks = useMemo(() => weeksOf(month, fixedWeekNumber), [month, fixedWeekNumber]);\n const weekdays = weeks[0];\n\n return (\n <div className={classNames(styles.xapp_calendar, className)} data-xapp-calendar=\"\">\n <div className={classNames(styles.xapp_calendar_header, classes.header)}>\n <span aria-live=\"polite\" className={styles.xapp_calendar_label} id={labelId}>\n {month.format(\"MMMM YYYY\")}\n </span>\n <div className={styles.xapp_calendar_nav}>\n <button\n aria-label=\"Previous month\"\n className={styles.xapp_calendar_nav_button}\n disabled={previousDisabled}\n onClick={() => setMonth(month.add(-1, \"month\"))}\n type=\"button\"\n >\n <ChevronLeftIcon />\n </button>\n <button\n aria-label=\"Next month\"\n className={styles.xapp_calendar_nav_button}\n disabled={nextDisabled}\n onClick={() => setMonth(month.add(1, \"month\"))}\n type=\"button\"\n >\n <ChevronRightIcon />\n </button>\n </div>\n </div>\n\n <div\n aria-busy={loading ? true : undefined}\n aria-labelledby={labelId}\n ref={gridRef}\n role=\"grid\"\n >\n <div className={styles.xapp_calendar_week} role=\"row\">\n {weekdays.map((day) => (\n <span\n aria-label={day.format(\"dddd\")}\n className={classNames(styles.xapp_calendar_weekday, classes.weekday)}\n key={day.day()}\n role=\"columnheader\"\n >\n {day.format(\"dd\").charAt(0)}\n </span>\n ))}\n </div>\n\n {loading ? (\n <div aria-hidden=\"true\" className={styles.xapp_calendar_skeleton}>\n {weeks.map((week, row) => (\n <div className={styles.xapp_calendar_week} key={row}>\n {week.map((day) => (\n <span\n className={styles.xapp_calendar_skeleton_day}\n key={day.valueOf()}\n />\n ))}\n </div>\n ))}\n </div>\n ) : (\n <div\n className={classNames(styles.xapp_calendar_weeks, classes.weeks)}\n role=\"rowgroup\"\n >\n {weeks.map((week, row) => (\n <div className={styles.xapp_calendar_week} key={row} role=\"row\">\n {week.map((day) => {\n const outside = !day.isSame(month, \"month\");\n\n if (outside && !showDaysOutsideCurrentMonth) {\n return (\n <span\n className={styles.xapp_calendar_filler}\n key={day.valueOf()}\n role=\"gridcell\"\n />\n );\n }\n\n const disabled = isDisabled(day);\n const selected = !!value && day.isSame(value, \"day\");\n const isToday = day.isSame(today, \"day\");\n\n return (\n <button\n aria-current={isToday ? \"date\" : undefined}\n aria-label={day.format(FULL_DATE_FORMAT)}\n aria-selected={selected}\n className={classNames(\n styles.xapp_calendar_day,\n classes.day,\n selected && styles.xapp_calendar_day_selected,\n selected && classes.daySelected,\n isToday && styles.xapp_calendar_day_today,\n isToday && classes.dayToday,\n outside && styles.xapp_calendar_day_outside,\n getDayClassName && getDayClassName(day, disabled)\n )}\n data-timestamp={day.valueOf()}\n disabled={disabled}\n key={day.valueOf()}\n onClick={() => onDayClick(day)}\n onKeyDown={(event) => onDayKeyDown(event, day)}\n role=\"gridcell\"\n tabIndex={\n !!tabbableDay && day.isSame(tabbableDay, \"day\")\n ? 0\n : -1\n }\n type=\"button\"\n >\n {day.date()}\n </button>\n );\n })}\n </div>\n ))}\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default Calendar;\n","import { Dayjs } from \"dayjs\";\n\n/**\n * The days an FSM/CRM has declared full.\n *\n * They reach the widget as one comma delimited string on a channel action response -\n * never on the initial render - and each entry is either a \"YYYY-MM-DD\" date, a weekday\n * name as `dddd` formats it (\"Saturday\"), or either of those with `*` standing in for any\n * run of characters (\"2026-08-*\").\n */\n\n/**\n * Split what the channel sent into the entries to match against.\n *\n * Reports `undefined` rather than an empty array when nothing has arrived, so a caller\n * can tell \"no availability information yet\" from \"nothing is busy\".\n *\n * @param busyDays The comma delimited list, as the channel sends it.\n */\nexport function parseBusyDays(busyDays?: string): string[] | undefined {\n if (!busyDays) {\n return undefined;\n }\n\n const entries = busyDays\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => !!entry);\n\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * Whether the CRM has declared the given day full.\n *\n * An absent or empty list means nothing is busy, so a picker shows its own availability\n * rather than greying everything or nothing out while the response is still in flight.\n *\n * @param day The day being drawn.\n * @param busyDays The entries from {@link parseBusyDays}.\n */\nexport function isBusyDay(day: Dayjs, busyDays?: readonly string[]): boolean {\n if (!busyDays || busyDays.length === 0) {\n return false;\n }\n\n const dateString = day.format(\"YYYY-MM-DD\");\n const dayString = day.format(\"dddd\");\n\n return busyDays.some((busyDay) => isMatch(dateString, busyDay) || isMatch(dayString, busyDay));\n}\n\n// Replace * with a regex that matches any number of characters\nfunction isMatch(str: string, pattern: string): boolean {\n const regexPattern = pattern.split(\"*\").map(escapeRegExp).join(\".*\");\n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(str);\n}\n\nfunction escapeRegExp(str: string): string {\n return str.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n}\n","import { Dayjs } from \"dayjs\";\n\nimport { BusyDayDescription } from \"stentor-models\";\n\n/**\n * Determines whether a calendar day counts as a bookable \"business day\" for the business.\n *\n * When `availableDays` is provided, those are the business's operating days — a business open\n * 7 days a week includes weekends. Only when `availableDays` is absent do we fall back to the\n * legacy Monday–Friday definition of a business day.\n */\nexport function isBusinessDay(day: Dayjs, busyDays: BusyDayDescription): boolean {\n if (Array.isArray(busyDays.availableDays) && busyDays.availableDays.length > 0) {\n const availableDays = busyDays.availableDays.map((d) => d.toLowerCase());\n return availableDays.includes(day.format(\"dddd\").toLowerCase());\n }\n\n // No explicit availableDays — business days are Monday to Friday.\n return day.day() !== 0 && day.day() !== 6;\n}\n\n/**\n * Pure implementation of the default busy-day rules for the date picker.\n *\n * Returns true when the given date should be disabled (not selectable).\n *\n * @param d The date being evaluated.\n * @param busyDays The busy-day configuration.\n * @param now The current moment, used for \"current day\" and time-of-day checks.\n */\nexport function isDisabledByBusyDays(d: Dayjs, busyDays: BusyDayDescription, now: Dayjs): boolean {\n if (busyDays.blockWeekends && (d.day() === 0 || d.day() === 6)) {\n return true;\n }\n\n if (busyDays.blockCurrentDay && d.isSame(now, \"day\")) {\n return true;\n }\n\n if (busyDays.blockNextBusinessDays) {\n let nextBusinessDay = now;\n let count = 0;\n // Bound the search so a misconfigured availableDays can never loop forever.\n let guard = 0;\n while (count < busyDays.blockNextBusinessDays && guard < 366) {\n nextBusinessDay = nextBusinessDay.add(1, \"day\");\n guard++;\n // Only count days the business is actually open, so a 7-day-a-week business\n // doesn't skip weekends (the cause of Friday showing Monday instead of Saturday).\n if (isBusinessDay(nextBusinessDay, busyDays)) {\n count++;\n }\n }\n\n if (d.isBefore(nextBusinessDay, \"day\")) {\n return true;\n }\n }\n\n if (busyDays.currentDayAvailableUntil && d.isSame(now, \"day\")) {\n // currentDayAvailableUntil is 24 hour format (HH:mm), in the client's local time.\n const time = now.format(\"HH:mm\");\n // if we are after the time, we should disable the current day\n if (time > busyDays.currentDayAvailableUntil) {\n return true;\n }\n }\n\n if (Array.isArray(busyDays.availableDays) && busyDays.availableDays.length > 0) {\n // availableDays are days of the week the business is open\n const availableDays = busyDays.availableDays.map((day) => day.toLowerCase());\n\n if (!availableDays.includes(d.format(\"dddd\").toLowerCase())) {\n return true;\n }\n }\n\n return false;\n}\n","import React, { FC, useCallback, useEffect } from \"react\";\n\nimport { FormDateInput, BusyDayDescription } from \"stentor-models\";\n\nimport dayjs, { Dayjs } from \"dayjs\";\n\nimport { Calendar } from \"../Calendar\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport { isBusyDay, parseBusyDays } from \"../../utils/busyDays\";\n\nimport { isDisabledByBusyDays } from \"./dateAvailability\";\n\nimport styles from \"./FormFieldDate.module.scss\";\n\nexport const DEFAULT_BUSY_DAYS: BusyDayDescription = {\n blockWeekends: true,\n blockCurrentDay: true,\n blockNextBusinessDays: 2,\n};\n\nexport interface FormDateProps extends FormFieldProps {\n /**\n * The date field\n */\n readonly field: FormDateInput;\n /**\n * Busy days as dates comma delimited, for example \"YYYY-MM-DD,YYYY-MM-DD\"\n */\n readonly busyDays?: string;\n /**\n * Are we loading availability information\n */\n readonly loading: boolean;\n /**\n * A day to keep closed whatever the busy days say, \"YYYY-MM-DD\": the next business day\n * when the after-hours block leaves it no time to offer.\n */\n readonly blockedDate?: string;\n}\n\nconst loadingMessage = \"Getting latest availability...\";\n\nexport const FormFieldDate: FC<FormDateProps> = (props) => {\n // Only go up to 2 months in the future\n const MAX_DATE = dayjs().add(2, \"month\");\n const TODAY = dayjs();\n\n const { field, onFieldChange, errorMessage, busyDays, loading, blockedDate } = props;\n\n /**\n * Tints a day by whether it can be booked: grey for the past and beyond the two month\n * horizon, green for a day that is open. A day blocked by the busy-day rules keeps no tint.\n */\n const getDayClassName = (day: Dayjs, disabled: boolean): string | undefined => {\n const isPast = day.isBefore(TODAY, \"day\");\n\n const isBeyondMaxDate = day.isAfter(MAX_DATE, \"day\");\n\n if (isPast || isBeyondMaxDate) {\n return styles.xapp_date_picker_past;\n } else if (disabled) {\n return undefined;\n }\n\n // available\n return styles.xapp_date_picker_available;\n };\n\n const [dateTimeValue, setDateTimeValue] = React.useState<Dayjs>();\n\n const onChange = (newValue: Dayjs) => {\n setDateTimeValue(newValue);\n };\n\n useEffect(() => {\n onFieldChange(field.name, dateTimeValue);\n }, [dateTimeValue, field.name, onFieldChange]);\n\n const disabledDays = parseBusyDays(busyDays);\n\n /**\n * Callback to determine if a date should be disabled used by the calendar\n */\n const shouldDisableDate = useCallback(\n (d: Dayjs): boolean => {\n if (blockedDate && d.format(\"YYYY-MM-DD\") === blockedDate) {\n return true;\n }\n\n if (!disabledDays) {\n // See if field has any defaultBusyDays by checking keys\n const hasDefaultBusyDays = Object.keys(field?.defaultBusyDays || {}).length > 0;\n\n // look for defaultBusyDays on the form or use the DEFAULT_BUSY_DAYS\n const busyDays = hasDefaultBusyDays\n ? // the extra '|| {}' is to make the subsequent types happy\n field.defaultBusyDays || {}\n : DEFAULT_BUSY_DAYS;\n\n return isDisabledByBusyDays(d, busyDays, TODAY);\n }\n\n try {\n return isBusyDay(d, disabledDays);\n } catch (err) {\n console.error(`shouldDisableDate: ${err}`);\n }\n\n return false;\n },\n [TODAY, disabledDays, field.defaultBusyDays, blockedDate]\n );\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignContent: \"center\",\n alignItems: \"center\",\n }}\n >\n <div className={styles.xapp_date_picker_container}>\n <Calendar\n className={styles.xapp_date_picker}\n classes={{\n header: styles.xapp_date_picker_header,\n weekday: styles.xapp_date_picker_weekday,\n weeks: styles.xapp_date_picker_weeks,\n day: styles.xapp_date_picker_day,\n daySelected: styles.xapp_date_picker_day_selected,\n dayToday: styles.xapp_date_picker_day_today,\n }}\n fixedWeekNumber={6}\n getDayClassName={getDayClassName}\n loading={loading}\n maxDate={MAX_DATE}\n minDate={TODAY}\n onChange={onChange}\n shouldDisableDate={shouldDisableDate}\n showDaysOutsideCurrentMonth={true}\n today={TODAY}\n value={dateTimeValue}\n />\n </div>\n\n {loading && <p className={styles.xapp_date_picker_loading}>{loadingMessage}</p>}\n\n {!loading && errorMessage && (\n <p className={styles.xapp_date_picker_error}>{errorMessage}</p>\n )}\n </div>\n );\n};\n\nexport default FormFieldDate;\n","import React, { FC, useEffect, useState } from \"react\";\n\nimport { FormDateRangeInput } from \"stentor-models\";\n\nimport { FormFieldProps } from \"../FormDisplay\";\n\n/**\n * The value this field reports through onFieldChange, and the shape it accepts\n * back as its initial value. Both halves are \"YYYY-MM-DD\" - what an\n * <input type=\"date\"> reads and writes.\n */\nexport interface FormDateRangeValue {\n from: string;\n to: string;\n}\n\nexport interface FormDateRangeProps extends FormFieldProps {\n readonly field: FormDateRangeInput;\n /**\n * Initial value, so the field can be pre-populated or resumed. Dates may\n * arrive as strings (stored form config is JSON) or as real Date objects.\n */\n readonly value?: { from?: string | Date; to?: string | Date };\n /**\n * When this is the last field of the step the keyboard shows \"done\" rather than \"next\".\n */\n readonly isLastField?: boolean;\n}\n\nexport const FROM_LABEL = \"From\";\nexport const TO_LABEL = \"To\";\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}/;\n\n/**\n * Coerce whatever the config or the model hands us into the \"YYYY-MM-DD\" an\n * <input type=\"date\"> accepts. Anything we cannot parse becomes an empty field\n * rather than a date we invented.\n */\nfunction toInputDate(value?: string | Date): string {\n if (!value) {\n return \"\";\n }\n\n if (typeof value === \"string\" && ISO_DATE.test(value)) {\n // Already in the right form - including the leading date of a full ISO timestamp.\n return value.slice(0, 10);\n }\n\n const date = value instanceof Date ? value : new Date(value);\n\n // A date-only string parses as UTC midnight, so read the UTC parts back out.\n // Going through the local parts would shift the day east of Greenwich.\n return isNaN(date.getTime()) ? \"\" : date.toISOString().slice(0, 10);\n}\n\nexport const FormFieldDateRange: FC<FormDateRangeProps> = (props) => {\n const { field, onFieldChange, value, errorMessage, required, isLastField } = props;\n\n // preselecteDates is the model's spelling - it is the field's own default,\n // used only when the step has no value for us already.\n const initialFrom = toInputDate(value?.from || field.preselecteDates?.from);\n const initialTo = toInputDate(value?.to || field.preselecteDates?.to);\n\n const [range, setRange] = useState<FormDateRangeValue>({ from: initialFrom, to: initialTo });\n\n useEffect(() => {\n setRange({ from: initialFrom, to: initialTo });\n }, [initialFrom, initialTo]);\n\n const change = (next: FormDateRangeValue) => {\n setRange(next);\n // An untouched range reports as undefined rather than a pair of empty\n // strings: an object with keys reads as \"filled\" to the mandatory checks.\n onFieldChange(field.name, next.from || next.to ? next : undefined);\n };\n\n const onFromChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n change({ ...range, from: e.target.value });\n };\n\n const onToChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n change({ ...range, to: e.target.value });\n };\n\n const fromId = `${field.name}-from`;\n const toId = `${field.name}-to`;\n\n // No autoComplete on either input: there is no standard token for an arbitrary\n // from/to pair, and a wrong autocomplete is worse than none - the same rule\n // formatToInputProps follows. type=\"date\" is what keeps mobile off the text\n // keyboard, so there is no iOS auto-zoom to guard against either.\n return (\n <div style={field.style}>\n {field.title && <h2>{field.title}</h2>}\n <label htmlFor={fromId}>{FROM_LABEL}</label>\n <input\n id={fromId}\n name={fromId}\n type=\"date\"\n value={range.from}\n onChange={onFromChange}\n max={range.to || undefined}\n required={required}\n enterKeyHint=\"next\"\n />\n <label htmlFor={toId}>{TO_LABEL}</label>\n <input\n id={toId}\n name={toId}\n type=\"date\"\n value={range.to}\n onChange={onToChange}\n min={range.from || undefined}\n required={required}\n enterKeyHint={isLastField ? \"done\" : \"next\"}\n />\n {errorMessage && <p>{errorMessage}</p>}\n </div>\n );\n};\n\nexport default FormFieldDateRange;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from \"react\";\n\nimport dayjs, { Dayjs } from \"dayjs\";\n\nimport { ClockTime, FormDateTimeInput, NextBusinessDayBlock, TimeOffering } from \"stentor-models\";\n\nimport { isBusyDay, parseBusyDays } from \"../../utils/busyDays\";\nimport {\n firstSelectableDate,\n formatOfferingLabel,\n formatTimezoneLabel,\n generateOfferings,\n horizonDaysOf,\n hostTimezone,\n isDateSelectable,\n isUsableTimezone,\n OfferingsByDate,\n toCalendarDate,\n toOffsetIso,\n} from \"../../utils/timeSlots\";\n\nimport { Calendar } from \"../Calendar\";\nimport { FormFieldProps } from \"../FormDisplay\";\n\nimport styles from \"./FormFieldDateTime.module.scss\";\n\n/**\n * What the field reports through `onFieldChange`, and what it accepts back to resume.\n *\n * Everything a lead consumer needs is resolved here rather than at submit time, because\n * this is where the schedule - and so the timezone the times are expressed in - is known.\n */\nexport interface FormDateTimeValue {\n /**\n * The chosen day as the business sees it, \"YYYY-MM-DD\". Never shifted into UTC.\n */\n date: string;\n /**\n * What the chosen time reads as, and what is submitted for the field itself.\n */\n label: string;\n /**\n * When the appointment starts, \"HH:MM\".\n */\n start: ClockTime;\n /**\n * When it ends, \"HH:MM\". Absent for a discrete start time.\n */\n end?: ClockTime;\n /**\n * Date and time together as ISO 8601 carrying the schedule's offset on that date,\n * e.g. \"2026-08-24T09:30:00-04:00\", so the value survives a DST transition.\n */\n datetime: string;\n}\n\nexport const NO_DATE_MESSAGE = \"Select a date to see the available times.\";\nexport const NO_TIMES_MESSAGE = \"No times are available on this date.\";\nexport const TIMES_LABEL = \"Appointment times\";\nexport const TIMEZONE_NOTICE_PREFIX = \"Times shown in\";\n\nexport interface FormDateTimeProps extends FormFieldProps {\n readonly field: FormDateTimeInput;\n /**\n * A previously chosen date and time, so stepping back into the form resumes it.\n */\n readonly value?: FormDateTimeValue;\n /**\n * The current moment. Injectable so tests and Storybook get a fixed calendar rather\n * than whatever day they happen to run on.\n */\n readonly now?: Date;\n /**\n * The days the tenant's CRM has declared full, comma delimited - \"YYYY-MM-DD,YYYY-MM-DD\".\n *\n * Arrives on a channel action response and so is absent on the first render; until it\n * turns up the calendar shows the schedule's own availability. Busy days narrow that\n * availability, they never widen it.\n */\n readonly busyDays?: string;\n /**\n * The CRM's own open windows per date, \"YYYY-MM-DD\" to offerings, for a CRM that\n * books live slots.\n *\n * When present it replaces what `field.schedule` would generate: a mapped date offers\n * exactly its entries, and a date absent from the map - or mapped to nothing - cannot\n * be picked. `busyDays` and the schedule's horizon and timezone still apply.\n */\n readonly offeringsByDate?: OfferingsByDate;\n /**\n * The next business day's morning, held back from a lead that arrived after hours.\n * Times on that date before `blockedUntil` are not offered, and the date cannot be\n * picked if that leaves none.\n */\n readonly nextBusinessDayBlock?: NextBusinessDayBlock;\n /**\n * Open on the soonest date that actually has times, instead of on the prompt.\n *\n * For a preview that lands straight on this step: a calendar with an empty\n * column beside it reads as a form with nothing to offer, when the schedule\n * is in fact full of slots one click away.\n *\n * Off by default, and deliberately not derived from `demoMode`. On a real\n * booking page a preselected date is a date the customer never chose, and\n * nothing stops them carrying it through to submit -- an appointment request\n * for a day picked by the software. Only the date is chosen; the time is\n * still theirs.\n */\n readonly preselectFirstAvailable?: boolean;\n}\n\n/**\n * Identifies an offering within a day's column. Start and end together, rather than the\n * index, so a selection survives a re-render that regenerates the array.\n */\nfunction offeringKey(offering: TimeOffering): string {\n return `${offering.start}|${offering.end || \"\"}`;\n}\n\n/**\n * Whether two selections name the same appointment.\n *\n * Compared field by field rather than by reference, so a value rebuilt from the same date\n * and offering counts as unchanged.\n */\nfunction sameSelection(a: FormDateTimeValue, b: FormDateTimeValue): boolean {\n return (\n a.date === b.date &&\n a.start === b.start &&\n a.end === b.end &&\n a.label === b.label &&\n a.datetime === b.datetime\n );\n}\n\n/**\n * What the column says the times are expressed in.\n *\n * A visitor two zones away reads \"9:30 AM\" as their own 9:30 unless something says\n * otherwise, so the zone is named outright - and named again as theirs when the two\n * differ, which is the only case where the distinction costs them an appointment. Zones\n * that merely have different identifiers but read the same, \"America/Detroit\" against\n * \"America/New_York\", are not a difference worth raising.\n *\n * @param timezone The zone the times are actually in.\n * @param visitorTimezone The zone the visitor's browser reports, if any.\n */\nfunction timezoneNotice(timezone: string, visitorTimezone: string): string {\n const name = formatTimezoneLabel(timezone);\n\n if (!name) {\n return \"\";\n }\n\n const visitorName =\n visitorTimezone && visitorTimezone !== timezone\n ? formatTimezoneLabel(visitorTimezone)\n : \"\";\n\n if (visitorName && visitorName !== name) {\n return `${TIMEZONE_NOTICE_PREFIX} ${name}, not your time zone (${visitorName}).`;\n }\n\n return `${TIMEZONE_NOTICE_PREFIX} ${name}.`;\n}\n\n/**\n * Calendar beside a scrollable column of appointment times, in the manner of Calendly.\n *\n * The column is generated from `field.schedule` on the client, so picking a date repaints\n * it immediately - there is no availability lookup and no round trip to wait on. Changing\n * the date clears the chosen time, because a time that exists on one day frequently does\n * not exist on the next.\n */\nexport const FormFieldDateTime: FC<FormDateTimeProps> = (props) => {\n const {\n field,\n onFieldChange,\n errorMessage,\n value,\n required,\n busyDays,\n offeringsByDate,\n nextBusinessDayBlock,\n preselectFirstAvailable,\n } = props;\n\n const schedule = field.schedule;\n\n // A fresh `new Date()` on every render would churn every memo below it.\n const now = useMemo(() => props.now || new Date(), [props.now]);\n\n const [selectedDate, setSelectedDate] = useState<Dayjs | undefined>(() =>\n value?.date ? dayjs(`${value.date}T00:00:00`) : undefined\n );\n const [selectedKey, setSelectedKey] = useState<string | undefined>(() =>\n value ? offeringKey(value) : undefined\n );\n\n const offerings = useMemo(\n () =>\n selectedDate\n ? generateOfferings(\n schedule,\n selectedDate.toDate(),\n now,\n offeringsByDate,\n nextBusinessDayBlock\n )\n : [],\n [schedule, selectedDate, now, offeringsByDate, nextBusinessDayBlock]\n );\n\n const selected = useMemo(\n () => offerings.find((offering) => offeringKey(offering) === selectedKey),\n [offerings, selectedKey]\n );\n\n const fieldValue = useMemo<FormDateTimeValue | undefined>(() => {\n if (!selectedDate || !selected) {\n return undefined;\n }\n\n const date = toCalendarDate(selectedDate.toDate());\n\n const next: FormDateTimeValue = {\n date,\n label: formatOfferingLabel(selected),\n start: selected.start,\n datetime: toOffsetIso(date, selected.start, schedule?.timezone),\n };\n\n if (selected.end) {\n next.end = selected.end;\n }\n\n // Hand back the very object the step passed down when the selection has not\n // actually moved off it. The step's prefill guard only releases on reference\n // equality, so reporting a freshly built twin reads as a stale update: the guard\n // stays closed and every later edit is silently discarded, leaving the submitted\n // value frozen at the prefill while the UI shows the new choice.\n if (value && sameSelection(value, next)) {\n return value;\n }\n\n return next;\n }, [selectedDate, selected, schedule, value]);\n\n // fieldValue is memoised, so this only reaches the step when the selection really\n // changed - not every time the parent hands down a new onFieldChange.\n useEffect(() => {\n onFieldChange(field.name, fieldValue);\n }, [fieldValue, field.name, onFieldChange]);\n\n // Memoised on the string itself so a busyDays that arrives later - or changes -\n // gives shouldDisableDate a new identity and the calendar repaints.\n const disabledDays = useMemo(() => parseBusyDays(busyDays), [busyDays]);\n\n // A date chosen before the CRM answered can turn out to be full. The selection is\n // dropped entirely rather than kept and greyed: the lead is asked again instead of\n // submitting against a day with no capacity, and the field reports undefined so a\n // mandatory step will not advance on it.\n useEffect(() => {\n if (selectedDate && isBusyDay(selectedDate, disabledDays)) {\n setSelectedDate(undefined);\n setSelectedKey(undefined);\n }\n }, [selectedDate, disabledDays]);\n\n // The soonest day with times, for a caller that asked to open on one.\n //\n // Recomputed against `disabledDays`, so this also answers the case the effect\n // above creates: busy days arrive after the first render, and a preselected\n // day that turns out to be full is cleared there and re-picked here as the\n // next day that is not. The search excludes busy days, so the day it lands on\n // cannot be cleared again and the two effects settle rather than trade.\n const preselected = useMemo(\n () =>\n preselectFirstAvailable\n ? firstSelectableDate(\n schedule,\n now,\n (date) => isBusyDay(dayjs(date), disabledDays),\n offeringsByDate,\n nextBusinessDayBlock\n )\n : undefined,\n [\n preselectFirstAvailable,\n schedule,\n now,\n disabledDays,\n offeringsByDate,\n nextBusinessDayBlock,\n ]\n );\n\n // Only ever fills an empty selection: a resumed value, or a day they picked\n // themselves, is theirs. And only the date -- the time is the answer, and\n // answering for someone is how a preview stops being a preview of their form.\n useEffect(() => {\n if (!preselected || selectedDate) {\n return;\n }\n\n setSelectedDate(dayjs(preselected));\n }, [preselected, selectedDate]);\n\n const onDateChange = (next: Dayjs) => {\n setSelectedDate(next);\n // A 9:30 slot valid on Tuesday may not exist on Saturday, so the time goes.\n setSelectedKey(undefined);\n };\n\n const shouldDisableDate = useCallback(\n (day: Dayjs): boolean =>\n !isDateSelectable(schedule, day.toDate(), now, offeringsByDate, nextBusinessDayBlock) ||\n isBusyDay(day, disabledDays),\n [schedule, now, disabledDays, offeringsByDate, nextBusinessDayBlock]\n );\n\n const horizon = horizonDaysOf(schedule);\n\n // What the times are *actually* in. An unusable zone is substituted for the host's\n // deep inside timeSlots rather than thrown, so the notice has to follow that\n // substitution or it would name a zone the column is not using.\n const hasSchedule = !!schedule;\n const scheduleTimezone = schedule?.timezone;\n const timezoneUsable = isUsableTimezone(scheduleTimezone);\n const notice = useMemo(() => {\n if (!hasSchedule) {\n return \"\";\n }\n\n const visitorTimezone = hostTimezone();\n\n return timezoneNotice(\n timezoneUsable ? scheduleTimezone : visitorTimezone,\n visitorTimezone\n );\n }, [hasSchedule, scheduleTimezone, timezoneUsable]);\n\n // The substitution is otherwise silent, and a typo'd zone renders times that are\n // wrong for everybody. Once per schedule, not once per render: a warning that\n // repeats on every click is one a developer learns to scroll past.\n // Keyed on the values rather than on the schedule object, so a parent that rebuilds\n // its field on every render does not turn this into a warning per keystroke.\n useEffect(() => {\n if (hasSchedule && !timezoneUsable) {\n console.warn(\n `FormFieldDateTime: \"${scheduleTimezone}\" is not a usable timezone, so ` +\n `times are shown in the visitor's zone instead. Set the schedule's ` +\n `timezone to an IANA identifier such as \"America/New_York\".`\n );\n }\n }, [hasSchedule, scheduleTimezone, timezoneUsable]);\n\n // Rendered as one flat list rather than nested lists: a group is a heading in the\n // middle of the column, so a schedule that names only some of its offerings still\n // reads as a single scrollable run.\n let previousGroup: string | undefined;\n\n return (\n <div className={styles.xapp_datetime} style={field.style}>\n {!!field.title && <h2 className={styles.xapp_datetime_title}>{field.title}</h2>}\n\n <div className={styles.xapp_datetime_body}>\n <div className={styles.xapp_datetime_calendar}>\n <Calendar\n // No minDate: past dates are already unselectable through\n // shouldDisableDate, which measures them against the now this\n // component was handed rather than the real clock.\n maxDate={dayjs(now).add(horizon, \"day\")}\n onChange={onDateChange}\n referenceDate={dayjs(now)}\n shouldDisableDate={shouldDisableDate}\n today={dayjs(now)}\n value={selectedDate || null}\n />\n </div>\n\n <div className={styles.xapp_datetime_times_column}>\n {!!notice && (\n // Deliberately a sibling of the group rather than a child: the\n // group's accessible name already carries the requirement, and a\n // screen reader reads this on its way past either way.\n <p className={styles.xapp_datetime_timezone}>{notice}</p>\n )}\n\n <div\n // `aria-required` is not valid on role=\"group\", and the offerings\n // are buttons rather than form controls, so the requirement rides\n // in the accessible name where a screen reader will actually\n // announce it.\n aria-label={required ? `${TIMES_LABEL} (required)` : TIMES_LABEL}\n className={styles.xapp_datetime_times}\n role=\"group\"\n >\n {!selectedDate && (\n <p className={styles.xapp_datetime_message}>{NO_DATE_MESSAGE}</p>\n )}\n\n {!!selectedDate && offerings.length === 0 && (\n <p className={styles.xapp_datetime_message}>{NO_TIMES_MESSAGE}</p>\n )}\n\n {offerings.map((offering, index) => {\n const key = offeringKey(offering);\n const header =\n offering.group !== previousGroup ? offering.group : undefined;\n previousGroup = offering.group;\n\n return (\n <React.Fragment key={`${key}-${index}`}>\n {!!header && (\n <h3 className={styles.xapp_datetime_group}>{header}</h3>\n )}\n <button\n aria-pressed={key === selectedKey}\n className={`${styles.xapp_datetime_time} ${\n key === selectedKey\n ? styles.xapp_datetime_time_selected\n : \"\"\n }`}\n onClick={() => setSelectedKey(key)}\n type=\"button\"\n >\n {formatOfferingLabel(offering)}\n </button>\n </React.Fragment>\n );\n })}\n </div>\n </div>\n </div>\n\n {!!errorMessage && (\n <p className={styles.xapp_datetime_error}>{errorMessage}</p>\n )}\n </div>\n );\n};\n\nexport default FormFieldDateTime;\n","!function(t,e){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define([],e):\"object\"==typeof exports?exports.AutosuggestHighlightParse=e():t.AutosuggestHighlightParse=e()}(this,(()=>{return t={705:t=>{t.exports=function(t,e){const h=[];return 0===e.length?h.push({text:t,highlight:!1}):e[0][0]>0&&h.push({text:t.slice(0,e[0][0]),highlight:!1}),e.forEach(((i,o)=>{const s=i[0],r=i[1];h.push({text:t.slice(s,r),highlight:!0}),o===e.length-1?r<t.length&&h.push({text:t.slice(r,t.length),highlight:!1}):r<e[o+1][0]&&h.push({text:t.slice(r,e[o+1][0]),highlight:!1})})),h}}},e={},function h(i){var o=e[i];if(void 0!==o)return o.exports;var s=e[i]={exports:{}};return t[i](s,s.exports,h),s.exports}(705);var t,e}));","import { AddressAutocompleteParameters } from \"stentor-models\";\n\nimport { err } from \".\";\n\nexport interface AddressAutocompleteConfig {\n apiKey?: string;\n baseUrl?: string;\n}\n\nexport interface AddressAutocompleteQuery {\n input: string;\n componentRestrictions?: {\n country: \"US\";\n };\n params?: AddressAutocompleteParameters;\n}\n\nexport interface MainTextMatchedSubstrings {\n offset: number;\n length: number;\n}\n\nexport interface StructuredFormatting {\n main_text: string;\n secondary_text: string;\n main_text_matched_substrings?: readonly MainTextMatchedSubstrings[];\n}\n\nexport interface PlaceType {\n description: string;\n structured_formatting: StructuredFormatting;\n /**\n * Google Place ID for the prediction, used to resolve full place details\n * (the prediction description never includes the postal code).\n */\n placeId?: string;\n}\n\n/**\n * Place details from the New Places API (v1). Only the fields the widget uses.\n */\nexport interface PlaceDetails {\n id?: string;\n formattedAddress?: string;\n}\n\n// New Places API (v1) response types\ninterface NewApiMatch {\n startOffset?: number;\n endOffset: number;\n}\n\ninterface NewApiFormattedText {\n text: string;\n matches?: NewApiMatch[];\n}\n\ninterface NewApiPlacePrediction {\n placeId: string;\n text: NewApiFormattedText;\n structuredFormat: {\n mainText: NewApiFormattedText;\n secondaryText?: { text: string };\n };\n}\n\n// The New Places API can return placePrediction or queryPrediction items\ninterface NewApiSuggestion {\n placePrediction?: NewApiPlacePrediction;\n}\n\ninterface PlaceSuggestion {\n placePrediction: NewApiPlacePrediction;\n}\n\ninterface NewApiResponse {\n suggestions?: NewApiSuggestion[];\n}\n\nfunction isPlaceSuggestion(s: NewApiSuggestion): s is PlaceSuggestion {\n return s.placePrediction != null;\n}\n\nfunction mapSuggestion(suggestion: PlaceSuggestion): PlaceType {\n const { placePrediction } = suggestion;\n return {\n placeId: placePrediction.placeId,\n description: placePrediction.text.text,\n structured_formatting: {\n main_text: placePrediction.structuredFormat.mainText.text,\n secondary_text: placePrediction.structuredFormat.secondaryText?.text || \"\",\n main_text_matched_substrings: (\n placePrediction.structuredFormat.mainText.matches || []\n ).map((m) => ({\n offset: m.startOffset ?? 0,\n length: (m.endOffset ?? 0) - (m.startOffset ?? 0),\n })),\n },\n };\n}\n\n/**\n * A service that interacts with a Google Places Autocomplete compatible API (New Places API v1).\n */\nexport class AddressAutocompleteService {\n private readonly baseUrl: string;\n private readonly key?: string;\n\n constructor(config: AddressAutocompleteConfig) {\n this.baseUrl = config.baseUrl || \"https://api.xapp.ai\";\n this.key = config.apiKey;\n }\n\n public getPlacePredictions(\n query: AddressAutocompleteQuery,\n callback: (results?: readonly PlaceType[]) => void\n ) {\n const requestBody: Record<string, unknown> = {};\n\n // Translate legacy params to New Places API v1 fields\n if (query.params) {\n // Convert legacy \"components\" (e.g. \"country:us\" or \"country:us|country:ca\")\n // to New API \"includedRegionCodes\" (e.g. [\"us\", \"ca\"])\n if (query.params.components) {\n const regionCodes = query.params.components\n .split(\"|\")\n .filter((c) => c.startsWith(\"country:\"))\n .map((c) => c.replace(\"country:\", \"\").toLowerCase());\n if (regionCodes.length > 0) {\n requestBody.includedRegionCodes = regionCodes;\n }\n }\n // Convert legacy \"language\" to New API \"languageCode\"\n if (query.params.language) {\n requestBody.languageCode = query.params.language;\n }\n // Convert legacy \"location\" (lat,lng string) + \"radius\" to New API \"locationBias\"\n if (query.params.location) {\n const [lat, lng] = query.params.location.split(\",\").map(Number);\n if (!isNaN(lat) && !isNaN(lng)) {\n requestBody.locationBias = {\n circle: {\n center: { latitude: lat, longitude: lng },\n radius: Number(query.params.radius) || 50000,\n },\n };\n }\n }\n }\n\n requestBody.input = query.input;\n\n // componentRestrictions overrides params; default to US unless already set\n if (query.componentRestrictions?.country) {\n requestBody.includedRegionCodes = [query.componentRestrictions.country.toLowerCase()];\n } else if (!requestBody.includedRegionCodes) {\n requestBody.includedRegionCodes = [\"us\"];\n }\n\n let url = `${this.baseUrl}/places/autocomplete`;\n if (this.key) {\n url += `?key=${encodeURIComponent(this.key)}`;\n }\n\n fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(requestBody),\n })\n .then((response) => {\n if (!response.ok) {\n throw new Error(`getPlacePredictions: HTTP error! Status: ${response.status}`);\n }\n return response.json();\n })\n .then((data: NewApiResponse) => {\n callback((data.suggestions || []).filter(isPlaceSuggestion).map(mapSuggestion));\n })\n .catch((error) => {\n err(\"getPlacePredictions: Fetch error:\", error);\n callback([]);\n });\n }\n\n /**\n * Resolves a place id from a prediction to full place details, which include\n * the formatted address with postal code. Calls back with undefined on failure.\n */\n public getPlaceDetails(placeId: string, callback: (details?: PlaceDetails) => void) {\n let url = `${this.baseUrl}/places/details/${encodeURIComponent(placeId)}`;\n if (this.key) {\n url += `?key=${encodeURIComponent(this.key)}`;\n }\n\n fetch(url)\n .then((response) => {\n if (!response.ok) {\n throw new Error(`getPlaceDetails: HTTP error! Status: ${response.status}`);\n }\n return response.json();\n })\n .then((data: PlaceDetails) => {\n callback(data);\n })\n .catch((error) => {\n err(\"getPlaceDetails: Fetch error:\", error);\n callback(undefined);\n });\n }\n}\n","import React, { FC, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\nimport parse from \"autosuggest-highlight/parse\";\n\nimport { AddressAutocompleteParameters, FormFieldTextAddressInput } from \"stentor-models\";\n\nimport { FormTextInputProps } from \"../FormFieldTextInput/FormFieldTextInput\";\nimport { AddressAutocompleteService, PlaceType } from \"../../utils/AddressAutocompleteService\";\n\nimport styles from \"./FormFieldTextInputAddress.module.scss\";\n\nconst POWERED_BY_GOOGLE_URL =\n \"https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white3.png\";\n\n// How long typing has to pause before we ask for predictions, as MUI's Google Maps demo did.\nconst DEBOUNCE_MS = 400;\n\ntype PredictionRequest = { input: string; params?: AddressAutocompleteParameters };\ntype PredictionCallback = (results?: readonly PlaceType[]) => void;\n\n/**\n * Trailing-edge debounce with a `clear`, the part of `@mui/material/utils`'s debounce we used.\n */\nfunction debounce<A extends unknown[]>(fn: (...args: A) => void, wait: number) {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const debounced = (...args: A) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => fn(...args), wait);\n };\n debounced.clear = () => clearTimeout(timeout);\n return debounced;\n}\n\n// MUI's LocationOn icon\nconst LocationOnIcon: FC = () => (\n <svg\n className={styles.xapp_address_option_icon}\n viewBox=\"0 0 24 24\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <path d=\"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7m0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5\" />\n </svg>\n);\n\nexport interface FormFieldTextInputAddressProps\n extends FormTextInputProps,\n Pick<FormFieldTextAddressInput, \"googleMapsApiKey\" | \"mapsBaseUrl\"> {\n readonly field: FormFieldTextAddressInput;\n /**\n * When true, the user must select an address from the autocomplete suggestions.\n * Free-text entry is not allowed.\n *\n * Can also be set via `field.requireSelection` (field-level takes precedence).\n * @see https://github.com/stentorium/stentor/issues/3040\n */\n readonly requireSelection?: boolean;\n}\n\n/**\n * An address field with Places suggestions: a WAI-ARIA combobox (an input plus a listbox), native\n * since XappMedia/chat-widget#1744. It behaves as the MUI Autocomplete it replaced did.\n */\nexport const FormFieldTextInputAddress: FC<FormFieldTextInputAddressProps> = (props) => {\n const {\n field,\n onFieldChange,\n errorMessage,\n required,\n googleMapsApiKey,\n mapsBaseUrl,\n requireSelection,\n } = props;\n\n // Field-level takes precedence, then component prop, default false\n const isFreeSolo = !(field.requireSelection ?? requireSelection);\n\n const [address, setAddress] = useState<PlaceType | null>(null);\n const [text, setText] = useState(\"\");\n const [options, setOptions] = useState<readonly PlaceType[]>([]);\n const [open, setOpen] = useState(false);\n const [focused, setFocused] = useState(false);\n // -1 is the text itself: nothing in the list is active\n const [activeIndex, setActiveIndex] = useState(-1);\n\n const id = `xapp-address-${useId()}`;\n const listboxId = `${id}-listbox`;\n const helperId = `${id}-helper-text`;\n const optionId = (index: number) => `${id}-option-${index}`;\n\n const listboxRef = useRef<HTMLUListElement>(null);\n\n // Mirrors the current input text so async place details callbacks can tell\n // whether the customer has typed or reselected since the request was made.\n const textRef = useRef(\"\");\n\n const onTextChange = (t: string) => {\n textRef.current = t;\n setText(t);\n };\n\n useEffect(() => {\n onFieldChange(field.name, text);\n }, [field.name, onFieldChange, text]);\n\n const apiKey = field.googleMapsApiKey || googleMapsApiKey;\n const baseUrl = field.mapsBaseUrl || mapsBaseUrl;\n\n const autocompleteService = useMemo(\n () => new AddressAutocompleteService({ apiKey, baseUrl }),\n [apiKey, baseUrl]\n );\n\n // Show Google attribution when using the xapp.ai proxy (which forwards to Google Places API).\n // Custom non-xapp.ai base URLs are assumed to be non-Google backends that handle their own attribution.\n const showGoogleAttribution = (() => {\n if (!baseUrl) return true;\n try {\n const hostname = new URL(baseUrl).hostname;\n return hostname === \"xapp.ai\" || hostname.endsWith(\".xapp.ai\");\n } catch {\n return false;\n }\n })();\n\n const fetch = useMemo(\n () =>\n debounce((request: PredictionRequest, callback: PredictionCallback) => {\n autocompleteService.getPlacePredictions(request, callback);\n }, DEBOUNCE_MS),\n [autocompleteService]\n );\n\n // A request still waiting out the debounce must not fire after the field is gone\n useEffect(() => () => fetch.clear(), [fetch]);\n\n useEffect(() => {\n let active = true;\n\n if (text === \"\") {\n setOptions([]);\n return undefined;\n }\n\n const queryParams = field.mapsUrlQueryParams || undefined;\n\n fetch({ input: text, params: queryParams }, (results?: readonly PlaceType[]) => {\n // A response for text the customer has since changed is dropped\n if (active) {\n setOptions(results || []);\n }\n });\n\n return () => {\n active = false;\n };\n }, [text, fetch, field.mapsUrlQueryParams]);\n\n // The option already chosen is not offered again (MUI's filterSelectedOptions)\n const visibleOptions = useMemo(\n () => (address ? options.filter((o) => o.description !== address.description) : options),\n [options, address]\n );\n\n // A free-text field has nothing to say when there are no suggestions; one that requires a\n // selection says so.\n const popupOpen = open && (visibleOptions.length > 0 || (!isFreeSolo && text !== \"\"));\n\n // New suggestions reset the active option, and it can never point past the list\n useEffect(() => {\n setActiveIndex(-1);\n }, [visibleOptions]);\n\n // Keep the active option in view inside the list without scrolling the page around it\n useLayoutEffect(() => {\n const listbox = listboxRef.current;\n const option = activeIndex >= 0 ? listbox?.children[activeIndex] : undefined;\n if (!listbox || !(option instanceof HTMLElement)) {\n return;\n }\n if (option.offsetTop < listbox.scrollTop) {\n listbox.scrollTop = option.offsetTop;\n } else if (\n option.offsetTop + option.offsetHeight >\n listbox.scrollTop + listbox.clientHeight\n ) {\n listbox.scrollTop = option.offsetTop + option.offsetHeight - listbox.clientHeight;\n }\n }, [activeIndex, popupOpen]);\n\n const close = () => {\n setOpen(false);\n setActiveIndex(-1);\n };\n\n const select = (option: PlaceType) => {\n close();\n setAddress(option);\n onTextChange(option.description);\n // Resolve the selected prediction to full place details so the displayed\n // and stored address includes the postal code (predictions never carry one).\n if (option.placeId) {\n const { placeId, description } = option;\n autocompleteService.getPlaceDetails(placeId, (details) => {\n // Skip stale results: only apply if the field still shows this prediction\n if (details?.formattedAddress && textRef.current === description) {\n setAddress({ ...option, description: details.formattedAddress });\n onTextChange(details.formattedAddress);\n }\n });\n }\n };\n\n const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const { value } = e.target;\n onTextChange(value);\n if (value === \"\") {\n // Clearing the text clears the selection too, as MUI did\n setAddress(null);\n } else {\n setOpen(true);\n }\n };\n\n // Up/Down cycle through the options and back to the text itself (MUI's includeInputInList)\n const move = (step: 1 | -1) => {\n const count = visibleOptions.length;\n if (count === 0) {\n return;\n }\n setActiveIndex((current) => {\n const next = current + step;\n if (next >= count) return -1;\n if (next < -1) return count - 1;\n return next;\n });\n };\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n switch (e.key) {\n case \"ArrowDown\":\n case \"ArrowUp\":\n e.preventDefault();\n setOpen(true);\n move(e.key === \"ArrowDown\" ? 1 : -1);\n break;\n case \"Enter\":\n if (popupOpen && activeIndex >= 0 && visibleOptions[activeIndex]) {\n // Choosing a suggestion must not also submit the form\n e.preventDefault();\n select(visibleOptions[activeIndex]);\n } else {\n close();\n }\n break;\n case \"Escape\":\n if (popupOpen) {\n // Closes the list, not the dialog the form sits in\n e.preventDefault();\n e.stopPropagation();\n close();\n }\n break;\n default:\n break;\n }\n };\n\n const onBlur = () => {\n setFocused(false);\n close();\n // A field that requires a selection drops text that isn't one (MUI's clearOnBlur)\n if (!isFreeSolo) {\n const chosen = address?.description || \"\";\n if (text !== chosen) {\n onTextChange(chosen);\n }\n }\n };\n\n // MUI's floating label: resting inside the field until it is focused or has a value. With no\n // label to collide with, the placeholder is always shown.\n const shrink = focused || text.length > 0 || !field.label;\n const activeOption = popupOpen && activeIndex >= 0 ? optionId(activeIndex) : undefined;\n\n return (\n <div\n className={`${styles.xapp_text_input_address} ${\n errorMessage ? styles.xapp_address_error : \"\"\n }`}\n style={field.style}\n >\n <div className={styles.xapp_address_anchor}>\n <div\n className={`${styles.xapp_address_root} ${\n focused ? styles.xapp_address_focused : \"\"\n }`}\n >\n {field.label && (\n <label\n htmlFor={id}\n className={styles.xapp_address_label}\n data-shrink={shrink ? \"true\" : \"false\"}\n >\n {field.label}\n {required && (\n <span className={styles.xapp_address_asterisk} aria-hidden=\"true\">\n {\" *\"}\n </span>\n )}\n </label>\n )}\n <input\n id={id}\n name={field.name}\n type=\"text\"\n className={styles.xapp_address_control}\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-expanded={popupOpen}\n aria-controls={listboxId}\n aria-activedescendant={activeOption}\n aria-invalid={!!errorMessage}\n aria-describedby={errorMessage ? helperId : undefined}\n // The browser's own autofill list would cover the suggestions\n autoComplete=\"off\"\n autoCapitalize=\"none\"\n spellCheck={false}\n placeholder={field.placeholder}\n required={required}\n maxLength={field.maxLength || undefined}\n value={text}\n onChange={onChange}\n onKeyDown={onKeyDown}\n onFocus={() => setFocused(true)}\n onBlur={onBlur}\n onMouseDown={() => {\n // A click opens the list, as MUI's did; it never toggles it shut\n if (!popupOpen && text !== \"\") {\n setOpen(true);\n }\n }}\n // Read by the stylesheet, which hides the placeholder behind a resting label.\n data-shrink={shrink ? \"true\" : \"false\"}\n />\n </div>\n <div\n className={styles.xapp_address_popup}\n hidden={!popupOpen}\n // Keeps the input focused while an option is clicked\n onMouseDown={(e) => e.preventDefault()}\n >\n <ul\n ref={listboxRef}\n id={listboxId}\n role=\"listbox\"\n aria-label={`${field.label || \"Address\"} suggestions`}\n className={styles.xapp_address_listbox}\n >\n {visibleOptions.map((option, index) => {\n const matches =\n option.structured_formatting.main_text_matched_substrings || [];\n const parts = parse(\n option.structured_formatting.main_text,\n matches.map((match) => [match.offset, match.offset + match.length])\n );\n return (\n <li\n key={option.placeId || option.description}\n id={optionId(index)}\n role=\"option\"\n aria-selected={index === activeIndex}\n className={`${styles.xapp_address_option} ${\n index === activeIndex\n ? styles.xapp_address_option_active\n : \"\"\n }`}\n onMouseMove={() => setActiveIndex(index)}\n onClick={() => select(option)}\n >\n <LocationOnIcon />\n <span className={styles.xapp_address_option_text}>\n {parts.map((part, i) => (\n <span\n key={i}\n style={{\n fontWeight: part.highlight ? \"bold\" : \"normal\",\n }}\n >\n {part.text}\n </span>\n ))}\n <span className={styles.xapp_address_secondary}>\n {option.structured_formatting.secondary_text}\n </span>\n </span>\n </li>\n );\n })}\n </ul>\n {popupOpen && visibleOptions.length === 0 && (\n <div className={styles.xapp_address_no_options}>No locations</div>\n )}\n {showGoogleAttribution && (\n <div className={styles.xapp_address_attribution}>\n <img src={POWERED_BY_GOOGLE_URL} alt=\"powered by Google\" />\n </div>\n )}\n </div>\n </div>\n {errorMessage && (\n <p id={helperId} className={styles.xapp_address_helper}>\n {errorMessage}\n </p>\n )}\n </div>\n );\n};\n","export interface FieldValidatorResult {\n valid: boolean;\n message?: string;\n}\n\nexport const validateEmail = (s: string): FieldValidatorResult => {\n const re = /^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;\n\n const valid = re.test(String(s).toLowerCase());\n const message = !valid ? \"Invalid email address\" : undefined;\n\n return { valid, message };\n};\n\nexport const validatePhoneNumber = (s: string): FieldValidatorResult => {\n // Nothing is valid\n if (isEmptyString(s)) {\n return { valid: true };\n }\n\n const valid = validateUSPhoneNumber(s);\n const message = !valid ? \"Invalid phone number\" : undefined;\n\n return { valid, message };\n};\n\nexport const validateZipCode = (s: string): FieldValidatorResult => {\n // Nothing is valid\n if (isEmptyString(s)) {\n return { valid: true };\n }\n\n // US 5-digit: 12345\n const usZip5Regex = /^\\d{5}$/;\n // US 9-digit (ZIP+4): 12345-6789\n const usZip9Regex = /^\\d{5}-\\d{4}$/;\n // Canadian postal code: A1A 1A1 or A1A1A1 (letter-digit-letter space digit-letter-digit, space optional)\n const canadianPostalCodeRegex = /^[A-Za-z]\\d[A-Za-z]\\s?\\d[A-Za-z]\\d$/;\n\n const valid =\n usZip5Regex.test(s) ||\n usZip9Regex.test(s) ||\n canadianPostalCodeRegex.test(s);\n\n const message = !valid ? \"Invalid zip code or postal code\" : undefined;\n\n return { valid, message };\n};\n\nexport const isEmptyString = (s: string): boolean => {\n return typeof s !== \"string\" || s.trim().length === 0;\n};\n\nconst validateUSPhoneNumber = (s: string) => {\n const sanitizedNumber = s.replace(/\\D/g, \"\");\n\n if (\n sanitizedNumber.length === 10 ||\n (sanitizedNumber.length === 11 && sanitizedNumber.startsWith(\"1\"))\n ) {\n const validPattern = /^(1)?[-. ]?\\(?(\\d{3})\\)?[-. ]?(\\d{3})[-. ]?(\\d{4})$/;\n return validPattern.test(sanitizedNumber);\n }\n\n return false;\n};\n\nexport const formatUSPhoneNumber = (s: string) => {\n if (isEmptyString(s) || !validateUSPhoneNumber(s)) {\n return s;\n }\n\n let sanitizedNumber = s.replace(/\\D/g, \"\");\n\n if (sanitizedNumber.length === 11 && sanitizedNumber.startsWith(\"1\")) {\n sanitizedNumber = sanitizedNumber.slice(1);\n }\n\n const formattedNumber = sanitizedNumber.replace(/(\\d{3})(\\d{3})(\\d{4})/, \"($1) $2-$3\");\n\n return formattedNumber;\n};\n\nexport const formatZipCode = (s: string): string => {\n if (isEmptyString(s)) {\n return s;\n }\n\n const trimmed = s.trim();\n\n // Check if it looks like a Canadian postal code without space\n const canadianNoSpace = /^([A-Za-z]\\d[A-Za-z])(\\d[A-Za-z]\\d)$/;\n const match = trimmed.match(canadianNoSpace);\n if (match) {\n return `${match[1].toUpperCase()} ${match[2].toUpperCase()}`;\n }\n\n // Uppercase Canadian postal codes with space\n const canadianWithSpace = /^[A-Za-z]\\d[A-Za-z]\\s\\d[A-Za-z]\\d$/;\n if (canadianWithSpace.test(trimmed)) {\n return trimmed.toUpperCase();\n }\n\n // Return as-is for US zip codes or invalid input\n return s;\n};\n\nexport const fieldErrorsEqual = (\n obj1: { [key: string]: FieldValidatorResult },\n obj2: { [key: string]: FieldValidatorResult }\n): boolean => {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n\n if (keys1.length !== keys2.length) {\n return false;\n }\n\n for (const key of keys1) {\n if (!obj2.hasOwnProperty(key)) {\n return false;\n }\n\n const attr1 = obj1[key];\n const attr2 = obj2[key];\n\n if (attr1.valid !== attr2.valid) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isEmpty = (obj: unknown) => {\n // Check if the value is null or undefined\n if (obj == null) {\n return true;\n }\n // Check if the value is an empty or whitespace-only string\n if (typeof obj === \"string\") {\n return obj.trim().length === 0;\n }\n // Check if the value is an array\n if (Array.isArray(obj)) {\n return obj.length === 0;\n }\n // Check if the value is a plain object\n if (typeof obj === \"object\" && obj.constructor === Object) {\n return Object.keys(obj).length === 0;\n }\n // For other types (e.g., Map, Set), check if they are empty\n if (typeof obj === \"object\") {\n return Object.keys(obj as object).length === 0;\n }\n // If none of the above conditions are met, return false\n return false;\n};\n","import React, {\n FC,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport type { Dayjs } from \"dayjs\";\n\nimport {\n FormCardInput,\n FormChipsInput,\n FormDateInput,\n FormDateRangeInput,\n FormDateTimeInput,\n FormDropdownInput,\n FormField,\n FormFieldTextAddressInput,\n FormStep,\n FormStepIFrame,\n FormSteps,\n FormTextInput,\n SelectableItem,\n} from \"stentor-models\";\n\nimport { addContextPrefix, shallowEqualBooleanMap } from \"../../utils/comparator\";\nimport {\n isFormCheckInput,\n isFormChipsInput,\n isFormDateInput,\n isFormDateRangeInput,\n isFormDateTimeInput,\n isFormTextInput,\n isFormDropdownInput,\n} from \"../../utils/guards\";\nimport { joinWithAnd, reformatDate, replaceValues } from \"../../utils/templating\";\nimport {\n blockedChipIds,\n isDateFullyBlocked,\n parseNextBusinessDayBlock,\n} from \"../../utils/nextBusinessDayBlock\";\nimport {\n DEFAULT_DATE_FIELD_NAME,\n DEFAULT_DATE_TIME_FIELD_NAME,\n DEFAULT_TIME_ZONE_FIELD_NAME,\n FormDateTimeInputWithTimeZone,\n parseOfferingsByDate,\n timeZoneOf,\n} from \"../../utils/timeSlots\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\nimport { useSearchState } from \"../../store\";\nimport { useExternalWidget, ExternalWidgetConfig } from \"../../utils/useExternalWidget\";\n\nimport FormFieldSelect from \"../FormFieldChips/FormFieldSelect\";\nimport { FormFieldCard } from \"../FormFieldCard\";\nimport { FormFieldChips } from \"../FormFieldChips\";\nimport { FormFieldTextInput } from \"../FormFieldTextInput\";\nimport { FormFieldDropdown } from \"../FormFieldDropdown\";\nimport { FormFieldDate } from \"../FormFieldDate\";\nimport { FormDateRangeValue, FormFieldDateRange } from \"../FormFieldDateRange\";\nimport { FormDateTimeValue, FormFieldDateTime } from \"../FormFieldDateTime\";\nimport { FormFieldTextInputAddress } from \"../FormFieldTextInputAddress\";\nimport { SpinnerIcon } from \"../icons\";\n\nimport {\n FieldValidatorResult,\n fieldErrorsEqual,\n formatUSPhoneNumber,\n formatZipCode,\n isEmpty,\n isEmptyString,\n validateEmail,\n validatePhoneNumber,\n validateZipCode,\n} from \"./validators\";\n\nimport styles from \"./FormStepDisplay.module.scss\";\n// Global (non-module) overrides that restyle the CostGuide partner embed rendered under\n// #airo-anchor. Kept separate from the CSS-module styles above because it targets the\n// partner's own light-DOM class names, which must not be scoped. See costguide-overrides.scss.\nimport \"./costguide-overrides.scss\";\nimport { isSelectableItem } from \"../FormFieldChips/FormFieldChips\";\n\n/**\n * Extended FormStep interface for per-step properties not yet in stentor-models.\n * Until they land upstream (targeting stentor-models@1.75.0), we use this type\n * extension to maintain type safety.\n */\ninterface FormStepWithUnloadWarning extends FormStep {\n warnBeforeUnload?: boolean;\n warnBeforeUnloadMessage?: string;\n /**\n * Suppresses the horizontal gutters (ModalDialog + step padding) for this\n * step only, so a full-width embed (e.g. an external booking widget) can\n * render edge-to-edge. From stentor-models@1.75.0's FormStep.fullBleed.\n */\n fullBleed?: boolean;\n}\n\n/**\n * Local extension of FormStep for the external booking-widget handoff step,\n * mirroring stentor-models@1.75.0's FormStepExternalWidget. See the note on\n * FormStepWithUnloadWarning above for why this is redeclared locally.\n */\nexport interface FormStepExternalWidget extends FormStep {\n externalWidget: ExternalWidgetConfig;\n}\n\nexport function isFormStepIframe(step: FormSteps): step is FormStepIFrame {\n return !!step && (step as FormStepIFrame).iframe !== undefined;\n}\n\nexport function isFormStepExternalWidget(step: FormSteps): step is FormStepExternalWidget {\n return !!step && (step as FormStepExternalWidget).externalWidget !== undefined;\n}\n\ntype FormFieldWithValue = FormField & { value: unknown };\nfunction hasFieldValue(f: FormField): f is FormFieldWithValue {\n return \"value\" in f && (f as FormFieldWithValue).value !== undefined;\n}\n\nexport interface StepData {\n current?: { [key: string]: unknown };\n}\n\n/**\n * What the step shows in place of its date and time fields when the CRM will not take a\n * scheduled booking.\n */\nexport const SCHEDULING_DISABLED_MESSAGE = \"We'll contact you to schedule a time.\";\n\n/**\n * The CHIPS fields that pick a date or time rather than answer some other question. Matched by\n * name because that is the only thing that tells a \"Morning / Afternoon\" chip apart from any\n * other: it is the name every lead consumer already reads.\n */\nconst SCHEDULING_CHIPS_NAMES = [\"preferred_time\", \"preferred_date\"];\n\n/**\n * Whether a field asks when the appointment should be, and so goes when scheduling is off.\n */\nfunction isSchedulingField(field: FormField): boolean {\n if (field.type === \"DATE\" || field.type === \"DATETIME\") {\n return true;\n }\n\n return field.type === \"CHIPS\" && SCHEDULING_CHIPS_NAMES.indexOf(field.name) >= 0;\n}\n\n/**\n * Every lead field a scheduling field writes when it is pushed - see `pushData` - so a value\n * pushed before scheduling went off can be cleared from all of them.\n */\nfunction leadFieldNamesOf(field: FormField): string[] {\n const names = [field.name, `${field.name}_start`, `${field.name}_end`];\n\n if (field.type === \"DATETIME\") {\n const dateTimeField = field as FormDateTimeInputWithTimeZone;\n names.push(\n dateTimeField.dateFieldName || DEFAULT_DATE_FIELD_NAME,\n dateTimeField.dateTimeFieldName || DEFAULT_DATE_TIME_FIELD_NAME,\n dateTimeField.timeZoneFieldName || DEFAULT_TIME_ZONE_FIELD_NAME\n );\n }\n\n return names;\n}\n\n/**\n * `schedulingDisabled` off the BusyDays context. Context parameters are typed as strings but\n * carry whatever the handler set, so the boolean and its string form both count.\n */\nfunction isSchedulingDisabled(context?: { [key: string]: unknown }): boolean {\n const flag = context?.schedulingDisabled;\n\n return flag === true || flag === \"true\";\n}\n\n/**\n * The calendar date a DATE field reported, \"YYYY-MM-DD\", or undefined when it is cleared.\n */\nfunction pickedCalendarDate(value: unknown): string | undefined {\n return value && typeof (value as Dayjs).format === \"function\"\n ? (value as Dayjs).format(\"YYYY-MM-DD\")\n : undefined;\n}\n\ntype Groupable<T extends FormField> = T & { mandatoryGroup?: string };\n\ninterface GroupableFieldStep extends FormStep {\n fields: Groupable<FormField>[];\n}\n\nfunction isGroupableFieldField(step: FormField): step is Groupable<FormField> {\n return !!step && (step as Groupable<FormField>).mandatoryGroup !== undefined;\n}\n\nexport interface FormStepDisplayProps {\n /**\n * Step data\n */\n readonly formStep: FormSteps | GroupableFieldStep;\n /**\n * Open a DATETIME field on the soonest day that has times, rather than on\n * \"Select a date to see the available times.\" For a preview that lands\n * straight on that step; off by default.\n */\n readonly preselectFirstAvailableDate?: boolean;\n /**\n * When the user hits the next button.\n *\n * If submit is true, then the form should be submitted.\n * May return a Promise when a FORM_NEXT server callback is in flight.\n */\n onNextStep: ((submit?: boolean) => Promise<void> | void) | undefined;\n /**\n * When the user hits the previous button\n */\n onPrevStep: (() => void) | undefined;\n /**\n * Data from the step\n */\n onData: (data: StepData) => void;\n /**\n * Data from the step but split up into key, value pairs.\n *\n * For example, {\"name\": \"John Smith\"}\n */\n onDataWithLabels: (data: object) => void;\n\n getData: () => object;\n /**\n * Returns the data needed for the form\n *\n * @returns\n */\n getDataWithLabels: () => object;\n /**\n * Is the form loading\n */\n loading: boolean;\n /**\n * Current step index (0-indexed)\n */\n currentStepIndex?: number;\n /**\n * Total number of steps in the form\n */\n totalSteps?: number;\n /**\n * Callback to track next_step event\n */\n onTrackNextStep?: (\n stepName: string,\n stepIndex: number,\n stepData: Record<string, unknown>,\n isLastStep: boolean\n ) => void;\n /**\n * Optional ref to sync current step data for tracking purposes.\n * This allows parent components to access live form data before step completion.\n */\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /**\n * Whether this step is the one currently visible. Every step's FormStepDisplay\n * is mounted at once (FormDisplay toggles visibility via CSS), so this is what\n * gates the external-widget mount sequence to only run once the step actually\n * becomes active, rather than for every handoff step on the form's first render.\n */\n isActive?: boolean;\n /**\n * True while this step's partner-widget config is still missing the values that only the\n * FORM_SUBMIT response carries. Injecting before they land hands the partner a config with no\n * zipCode, name or trade, and one that reads its global at load never sees the real one.\n */\n externalWidgetConfigPending?: boolean;\n /**\n * Fired when a booking-widget handoff step's anchor gains content within\n * its render timeout.\n */\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n /**\n * Fired when a booking-widget handoff step's render timeout elapses with\n * an empty anchor.\n */\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n /**\n * Fired when the partner script invokes the configured success callback.\n */\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n /**\n * Fired when a booking-widget handoff step's script fails to load or is rejected.\n */\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n /**\n * Fired when a booking-widget handoff step fails to render (timeout or script\n * error) and `externalWidget.fallbackStep` is set, so the parent can navigate\n * there. Not fired when fallbackStep is unset -- an inline fallback message is\n * rendered in place instead.\n */\n onExternalWidgetFallback?: (fallbackStep: string) => void;\n /**\n * Message shown when this step's FORM_SUBMIT dispatch failed, so the user knows\n * their submission did not land and can retry rather than assuming it worked\n * (issue #1373). Undefined when the step has no failed submit.\n */\n submitError?: string;\n /**\n * Suppresses this step's own title/subtitle block. Set when a partner frame is\n * around the step, since the frame's intro block renders them instead -- and\n * placement is the frame's decision (it can sit outside the frame entirely).\n */\n hideIntro?: boolean;\n}\n\n/**\n * Both halves present. `FormFieldDateRange` reports `undefined` when both are empty and a\n * partial object when only one is filled, so this distinguishes \"untouched\" from \"half done\"\n * without either being treated as a usable range.\n */\n/**\n * A datetime field holds two values and is only satisfied by both. `start` rather than\n * the label, because an offering without a label still formats one for display.\n */\nfunction isCompleteDateTime(value: unknown): boolean {\n const selection = value as FormDateTimeValue | undefined;\n\n return !!selection?.date && !!selection?.start;\n}\n\nfunction isCompleteRange(value: unknown): boolean {\n const range = value as { from?: string; to?: string } | undefined;\n return !!range?.from && !!range?.to;\n}\n\nexport const FormStepDisplay: FC<FormStepDisplayProps> = (props) => {\n const stepData = useRef<StepData>({});\n // Track which fields were prefilled from server values (not user input)\n const prefilledFields = useRef<Set<string>>(new Set());\n const hasNotifiedPrefill = useRef(false);\n const prevFieldsRef = useRef(props.formStep.fields);\n\n const fieldTests = useRef({});\n\n const [mandatoryGroups, setMandatoryGroups] = useState<{ [name: string]: string[] }>({});\n const [fieldConditions, setFieldConditions] = useState<{ [name: string]: boolean }>({});\n const [fieldErrors, setFieldErrors] = useState<{ [name: string]: FieldValidatorResult }>({});\n const [isSubmitting, setIsSubmitting] = useState(false);\n\n const { context } = useSearchState();\n\n // Both arrive on the BusyDays context alongside busyDays, from a CRM that either books\n // live slots or will not take a scheduled booking at all right now.\n const schedulingDisabled = isSchedulingDisabled(context);\n const rawOfferingsByDate: unknown = context?.offeringsByDate;\n const offeringsByDate = useMemo(\n () => parseOfferingsByDate(rawOfferingsByDate),\n [rawOfferingsByDate]\n );\n\n // The next business day's morning, held back from a lead that arrived after hours (#1829).\n // The date picked on this step decides which time chips it disables.\n const rawNextBusinessDayBlock: unknown = context?.nextBusinessDayBlock;\n const nextBusinessDayBlock = useMemo(\n () => parseNextBusinessDayBlock(rawNextBusinessDayBlock),\n [rawNextBusinessDayBlock]\n );\n const [pickedDate, setPickedDate] = useState<string | undefined>();\n\n // A field that is not shown cannot be asked for, and its value - a preselected chip, a\n // date picked before the flag arrived - is not an answer the lead gave.\n const isHiddenSchedulingField = useCallback(\n (field?: FormField) => schedulingDisabled && !!field && isSchedulingField(field),\n [schedulingDisabled]\n );\n\n const {\n formStep,\n onNextStep: nextStep,\n onPrevStep: prevStep,\n onData: handleData,\n onDataWithLabels: handleDataWithLabels,\n getData,\n getDataWithLabels,\n loading,\n currentStepIndex,\n totalSteps,\n onTrackNextStep,\n currentStepDataRef,\n isActive,\n externalWidgetConfigPending,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n onExternalWidgetFallback,\n submitError,\n hideIntro,\n } = props;\n\n // Gated on isActive: every step's FormStepDisplay is mounted at once, so\n // without this the mount sequence would fire for a handoff step as soon as\n // the form first renders, rather than when the step actually becomes active.\n //\n // Also gated on the submit's config having arrived. Becoming active is not enough: the step is\n // reached by a fire-and-forget FORM_SUBMIT, so it renders before the response carrying zipCode,\n // name and trade. Our own placeholder shows in the meantime, which is the same thing the\n // visitor sees while the partner's script boots.\n const externalWidgetConfig =\n isActive && !externalWidgetConfigPending && isFormStepExternalWidget(formStep)\n ? formStep.externalWidget\n : undefined;\n\n const { outcome: externalWidgetOutcome } = useExternalWidget(externalWidgetConfig, {\n onRendered: (provider) => onTrackHandoffRendered?.(formStep.name, provider),\n onNoRender: (provider) => onTrackHandoffNoRender?.(formStep.name, provider),\n onScheduled: (provider, payload) =>\n onTrackHandoffScheduled?.(formStep.name, provider, payload),\n onError: (provider) => onTrackHandoffError?.(formStep.name, provider),\n onFallback: (fallbackStep) => onExternalWidgetFallback?.(fallbackStep),\n });\n\n // The partner embed shows its OWN loading UI (e.g. CostGuide's #step-loading) while it works,\n // which the hook still reports as \"pending\". Watch the anchor locally so our placeholder steps\n // aside the moment their content appears -- otherwise two spinners show at once.\n //\n // Deliberately local state rather than something exposed from useExternalWidget: returning\n // anchor state from the hook re-runs its mount effect on a fresh config object, which\n // early-exits via hasMountedRef *after* cleanup has torn down the render-timeout timer, so\n // no_render never fires. The hook's own tests catch that. externalWidgetConfig is a stable\n // reference here, so watching it from this component is safe.\n //\n // ASSUMPTION for the next partner integration: \"any child element\" is treated as \"the partner\n // is showing something\". That holds for CostGuide, whose first write is its own visible\n // #step-loading spinner. A partner whose first write is an empty wrapper it populates a moment\n // later would retire our placeholder early and leave a blank gap until their content paints.\n // If that shows up, tighten the predicate here (e.g. require text content or a known step id)\n // rather than removing the check -- without it CostGuide stacks two spinners.\n //\n // useLayoutEffect, NOT useEffect: steps are never unmounted, only shown and hidden via a CSS\n // class (FormDisplay), so re-entering a handoff step whose embed already rendered goes through\n // a real render with the flag freshly reset to false. A passive effect runs after paint, which\n // would flash the placeholder over an embed that is already there for one frame -- the exact\n // jarring pop-in this component exists to remove. Correcting before paint closes that window.\n // jsdom never paints, so no test can catch a regression here; see WidgetStylesheet for the\n // same reasoning.\n const [externalWidgetContentShown, setExternalWidgetContentShown] = useState(false);\n useLayoutEffect(() => {\n if (!externalWidgetConfig) {\n setExternalWidgetContentShown(false);\n return undefined;\n }\n const anchorId = externalWidgetConfig.anchorId;\n const anchor = document.getElementById(anchorId);\n if (!anchor) {\n return undefined;\n }\n if (anchor.childElementCount > 0) {\n setExternalWidgetContentShown(true);\n return undefined;\n }\n const observer = new MutationObserver(() => {\n const el = document.getElementById(anchorId);\n if (el && el.childElementCount > 0) {\n setExternalWidgetContentShown(true);\n // Nothing left to watch, and a booking widget mutates its subtree constantly\n // once it is live -- keeping this attached would invoke the callback for the\n // rest of the step's lifetime for no benefit.\n observer.disconnect();\n }\n });\n observer.observe(anchor, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, [externalWidgetConfig]);\n\n const checkConditions = useCallback(() => {\n const newConditions = {};\n\n Object.entries(fieldTests.current).forEach(([name, f]) => {\n try {\n // Create context with null-safe helper functions\n const context = {\n ...getData(),\n ...stepData.current,\n // Helper for safe array/string checking\n safeIncludes: (value: any, searchElement: any): boolean => {\n if (Array.isArray(value)) return value.includes(searchElement);\n if (typeof value === \"string\") return value === searchElement;\n return false;\n },\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n newConditions[name] = (f as Function).call(context);\n } catch (error) {\n // Log error in development mode for debugging\n if (process.env.NODE_ENV === \"development\") {\n console.error(`Condition evaluation failed for field \"${name}\":`, error);\n }\n // Default to false if condition fails - field will be hidden\n newConditions[name] = false;\n }\n });\n\n if (!shallowEqualBooleanMap(newConditions, fieldConditions)) {\n setFieldConditions(newConditions);\n }\n }, [fieldConditions, getData]);\n\n useEffect(() => {\n const groups: { [key: string]: string[] } = {};\n\n for (const field of formStep.fields) {\n if (isGroupableFieldField(field) && !isHiddenSchedulingField(field)) {\n const groupName = field.mandatoryGroup;\n if (groupName) {\n if (!groups[groupName]) {\n groups[groupName] = [];\n }\n groups[groupName].push(field.name);\n }\n }\n }\n\n setMandatoryGroups(groups);\n }, [formStep.fields, isHiddenSchedulingField]);\n\n // Reset prefill tracking when formStep.fields is replaced by a new array reference\n // (e.g. via FORM_STEP_UPDATE). This must happen in the render phase — not useEffect —\n // for the same reason as the seeding loop below (see lines 247–252).\n const resetPrefillTracking = () => {\n prefilledFields.current.clear();\n hasNotifiedPrefill.current = false;\n stepData.current = {};\n };\n\n if (prevFieldsRef.current !== formStep.fields) {\n prevFieldsRef.current = formStep.fields;\n resetPrefillTracking();\n }\n\n // Seed prefilled values synchronously during render so they're available\n // as value props when children mount. This must happen in the render phase\n // (not useEffect/useLayoutEffect) because both fire children-first, and child\n // components (e.g. FormFieldTextInput) call onFieldChange on mount with their\n // default value, which would overwrite the prefill. The guards make this idempotent\n // and safe under Strict Mode double-renders.\n for (const field of formStep.fields) {\n if (\n hasFieldValue(field) &&\n !prefilledFields.current.has(field.name) &&\n !Object.prototype.hasOwnProperty.call(stepData.current, field.name)\n ) {\n stepData.current[field.name] = field.value;\n prefilledFields.current.add(field.name);\n }\n }\n\n // The step's values without those of hidden scheduling fields, for everything that leaves\n // the step: the prefill notify, the push and the next-step tracking.\n const visibleStepValues = (stepValues: object): { [key: string]: unknown } => {\n const visibleValues: { [key: string]: unknown } = { ...stepValues };\n\n for (const field of formStep.fields) {\n if (isHiddenSchedulingField(field)) {\n delete visibleValues[field.name];\n }\n }\n\n return visibleValues;\n };\n\n useEffect(() => {\n // check for initial data and look for conditions\n for (const field of formStep.fields) {\n if (field.type === \"CHIPS\") {\n // look for preselected chips\n const chipsSelectedFromProps = (field as FormChipsInput).items\n .filter((item) => isSelectableItem(item))\n .filter((item) => item.selected)\n .map((item) => item.id);\n\n // if we have length, set it (guard prevents overwriting prefilled or user-entered data)\n if (\n chipsSelectedFromProps.length > 0 &&\n !Object.prototype.hasOwnProperty.call(stepData.current, field.name)\n ) {\n stepData.current[field.name] = chipsSelectedFromProps;\n }\n }\n\n if (field.condition) {\n const conditionWithThis = addContextPrefix(field.condition);\n\n // eslint-disable-next-line no-new-func\n fieldTests.current[field.name] = new Function(`return (${conditionWithThis});`);\n }\n }\n\n // Notify parent of prefilled data once (not on every formStep.fields change)\n if (prefilledFields.current.size > 0 && !hasNotifiedPrefill.current) {\n hasNotifiedPrefill.current = true;\n handleData(visibleStepValues(stepData.current));\n }\n\n checkConditions();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [checkConditions, formStep.fields]); // once\n\n const validate: () => boolean = useCallback(() => {\n const errors: { [name: string]: FieldValidatorResult } = {};\n let isValid = true;\n const corrections: { [name: string]: string } = {};\n\n // Validate individual fields first\n formStep.fields.forEach((field) => {\n let result: FieldValidatorResult = { valid: true };\n\n const value = stepData.current[field.name];\n\n // Skip validation for hidden fields\n if (fieldConditions[field.name] === false || isHiddenSchedulingField(field)) {\n errors[field.name] = result;\n return;\n }\n\n // For dropdowns, always validate if mandatory (even if not touched)\n if (isFormDropdownInput(field)) {\n // Check if mandatory field has a value selected\n if (\n field.mandatory &&\n (value === undefined || value === null || value === \"none\")\n ) {\n result = {\n valid: false,\n message: field.mandatoryError || \"Please select an option\",\n };\n } else if (value !== undefined && value !== null && value !== \"none\") {\n // Check if the selected dropdown item requires free-form input\n const selectedItem = field.items.find((item) => item.id === value);\n\n if (selectedItem && (selectedItem as any).freeFormInput) {\n // Get the free-form field name (default to \"message\")\n const freeFormFieldName =\n (selectedItem as any).freeFormFieldName || \"message\";\n const freeFormValue = stepData.current[freeFormFieldName];\n\n // Validate that free-form field has a value\n // If validation fails, set error on the free-form field, not the dropdown\n if (\n !freeFormValue ||\n (typeof freeFormValue === \"string\" && freeFormValue.trim() === \"\")\n ) {\n // Set error on the free-form field specifically\n errors[freeFormFieldName] = {\n valid: false,\n message: \"Please specify additional details\",\n };\n // Mark the form as invalid\n result = {\n valid: false,\n message: \"\", // No error on dropdown itself\n };\n }\n }\n }\n }\n // Like dropdowns, a mandatory range is validated whether or not it was touched.\n // FormFieldDateRange only reports through onFieldChange once the user edits it,\n // so an untouched field never lands in stepData and the touched-only branch below\n // would skip it entirely - which is exactly how a mandatory range submitted empty.\n //\n // The inputs' own required/min/max cannot cover this: the step has no <form> and\n // Next is not type=\"submit\", so the browser never runs constraint validation.\n //\n // A half-filled range fails too. An open-ended window is not a date range, and\n // delivering one as a lead is worse than asking the user to finish.\n else if (isFormDateRangeInput(field)) {\n if (field.mandatory && !isCompleteRange(value)) {\n result = {\n valid: false,\n message: field.mandatoryError || \"Please select a date range\",\n };\n }\n }\n // Same reasoning as the range above, and the same failure to avoid: a\n // mandatory datetime needs BOTH halves, and a field the user never touched\n // has to fail rather than fall through the touched-only branch below.\n else if (isFormDateTimeInput(field)) {\n if (field.mandatory && !isCompleteDateTime(value)) {\n result = {\n valid: false,\n message: field.mandatoryError || \"Please select a date and a time\",\n };\n }\n }\n // Only validate other fields if they've been touched\n else if (Object.prototype.hasOwnProperty.call(stepData.current, field.name)) {\n if (isFormTextInput(field)) {\n if (field.mandatory === true && isEmptyString(value)) {\n result = {\n valid: false,\n message: field.mandatoryError || \"This field is mandatory\",\n };\n } else if (field.format === \"EMAIL\" && !isEmptyString(value)) {\n result = validateEmail(value);\n } else if (field.format === \"PHONE\" && !isEmptyString(value)) {\n result = validatePhoneNumber(value);\n if (result.valid) {\n const formattedNumber = formatUSPhoneNumber(value);\n if (formattedNumber !== value)\n corrections[field.name] = formattedNumber;\n }\n } else if (field.format === \"ZIP_CODE\" && !isEmptyString(value)) {\n result = validateZipCode(value);\n if (result.valid) {\n const formattedZip = formatZipCode(value);\n if (formattedZip !== value) corrections[field.name] = formattedZip;\n }\n }\n } else if (isFormChipsInput(field)) {\n if (field.minRequired && value.length < field.minRequired) {\n result = {\n valid: false,\n message: `Please select at least ${field.minRequired} option(s)`,\n };\n } else if (field.maxAllowed && value.length > field.maxAllowed) {\n result = {\n valid: false,\n message: `Please select no more than ${field.maxAllowed} option(s)`,\n };\n } else if (field.mandatory && value?.length !== 1) {\n result = { valid: false, message: \"Please select one option\" };\n }\n } else if (isFormDateInput(field) && field.mandatory && value == null) {\n result = { valid: false, message: \"Please select a day\" };\n } else if (isFormCheckInput(field) && field.mandatory && !value?.length) {\n // CHECK is a multi-select unless radio, so any selection satisfies mandatory\n result = {\n valid: false,\n message: field.mandatoryError || \"This field is mandatory\",\n };\n }\n }\n\n isValid = isValid && result.valid;\n errors[field.name] = result;\n });\n\n // Validate mandatoryGroups: only ONE field in the group is needed\n for (const [, fieldNames] of Object.entries(mandatoryGroups)) {\n const hasValue = fieldNames.some((name) => !isEmpty(stepData.current[name]));\n\n if (!hasValue) {\n // get the mandatoryError off the field\n const field = formStep.fields.find((f) => f.name === fieldNames[0]);\n const fieldError = fieldErrors[fieldNames[0]];\n const errorMessage =\n fieldError?.message ||\n field?.mandatoryError ||\n \"At least one of these fields is required\";\n\n // Mark each field in the group as invalid\n fieldNames.forEach((name) => {\n errors[name] = {\n valid: false,\n message: errorMessage,\n };\n });\n\n isValid = false;\n }\n }\n\n // Apply corrections if needed\n if (!isEmpty(corrections)) {\n stepData.current = { ...stepData.current, ...corrections };\n }\n\n // Only update state if different\n if (!fieldErrorsEqual(fieldErrors, errors)) {\n setFieldErrors(errors);\n }\n\n return isValid;\n }, [fieldConditions, fieldErrors, formStep.fields, mandatoryGroups, isHiddenSchedulingField]);\n\n const continueToNext = async () => {\n if (!validate() || isSubmitting) {\n return;\n }\n\n setIsSubmitting(true);\n try {\n pushData(stepData.current);\n\n // Track next_step event if tracking callback is provided\n if (onTrackNextStep && currentStepIndex !== undefined && totalSteps !== undefined) {\n const isLastStep = currentStepIndex === totalSteps - 1;\n onTrackNextStep(\n formStep.name,\n currentStepIndex,\n visibleStepValues(stepData.current),\n isLastStep\n );\n }\n\n if (nextStep) {\n await nextStep(formStep.nextAction === \"submit\");\n }\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const pushData = (stepValues: object) => {\n const data: object = visibleStepValues(stepValues);\n\n // The form merges what each push sends, so a hidden field's value pushed before\n // scheduling went off - stepping back pushes too - would outlive the field unless it\n // is cleared. Only keys the form already holds, so nothing new appears in the lead.\n const pushedData: object = getData();\n const pushedLabels: object = getDataWithLabels();\n const clearedData: { [key: string]: undefined } = {};\n const clearedLabels: { [key: string]: undefined } = {};\n\n for (const field of formStep.fields) {\n if (isHiddenSchedulingField(field)) {\n for (const name of leadFieldNamesOf(field)) {\n if (Object.prototype.hasOwnProperty.call(pushedData, name)) {\n clearedData[name] = undefined;\n }\n if (Object.prototype.hasOwnProperty.call(pushedLabels, name)) {\n clearedLabels[name] = undefined;\n }\n }\n }\n }\n\n // Cleared first, so a visible field writing the same key still wins.\n const augmentedData: { [key: string]: unknown } = { ...clearedData, ...data };\n\n // Now create the equivalent with string representation for templating\n const dataWithLabels: { [name: string]: string } = {};\n\n // One place that turns collected times into the `<field>_start` / `<field>_end`\n // lead fields, so the chips field and the datetime field cannot drift apart on\n // the shape a CRM receives.\n const applyTimes = (fieldName: string, startTimes: string[], endTimes: string[]) => {\n if (startTimes.length > 0) {\n const joinedStart = startTimes.join(\", \");\n augmentedData[`${fieldName}_start`] = joinedStart;\n dataWithLabels[`${fieldName}_start`] = joinedStart;\n }\n if (endTimes.length > 0) {\n const joinedEnd = endTimes.join(\", \");\n augmentedData[`${fieldName}_end`] = joinedEnd;\n dataWithLabels[`${fieldName}_end`] = joinedEnd;\n }\n };\n\n for (const fieldName of Object.keys(data)) {\n const value = data[fieldName];\n\n const formField = formStep.fields.find((field) => field.name === fieldName);\n\n if (formField?.type === \"CHIPS\" && value !== undefined) {\n const valueLabels: string[] = [];\n const startTimes: string[] = [];\n const endTimes: string[] = [];\n\n (value as string[]).forEach((s) => {\n const item = (formField as FormChipsInput).items.find((chip) => chip.id === s);\n if (item) {\n valueLabels.push(item.label);\n const timedItem = item as SelectableItem;\n if (timedItem.startTime) {\n startTimes.push(timedItem.startTime);\n }\n if (timedItem.endTime) {\n endTimes.push(timedItem.endTime);\n }\n }\n });\n\n dataWithLabels[fieldName] = joinWithAnd(valueLabels);\n applyTimes(fieldName, startTimes, endTimes);\n } else if (formField?.type === \"DATETIME\" && value !== undefined) {\n // One field, up to six lead fields: the label under the field's own name -\n // the same key and shape the chips field it replaces emits today - plus\n // the start, the optional end, the date, the combined timestamp and the\n // zone that timestamp's wall clock belongs to.\n const dateTimeField = formField as FormDateTimeInputWithTimeZone;\n const selection = value as FormDateTimeValue;\n\n augmentedData[fieldName] = selection.label;\n dataWithLabels[fieldName] = selection.label;\n\n applyTimes(\n fieldName,\n selection.start ? [selection.start] : [],\n selection.end ? [selection.end] : []\n );\n\n // Never hardcoded: a tenant may submit the pair under its own names.\n const dateFieldName = dateTimeField.dateFieldName || DEFAULT_DATE_FIELD_NAME;\n augmentedData[dateFieldName] = selection.date;\n dataWithLabels[dateFieldName] = selection.date;\n\n const dateTimeFieldName =\n dateTimeField.dateTimeFieldName || DEFAULT_DATE_TIME_FIELD_NAME;\n augmentedData[dateTimeFieldName] = selection.datetime;\n dataWithLabels[dateTimeFieldName] = selection.datetime;\n\n // What makes the timestamp above readable as a business wall clock rather\n // than whatever a browser happened to submit under a field called `date`.\n // Absent when the schedule's zone was unusable and the picker fell back to\n // the host's, because then it would be a lie.\n const timeZone = timeZoneOf(dateTimeField.schedule);\n\n if (timeZone) {\n const timeZoneFieldName =\n dateTimeField.timeZoneFieldName || DEFAULT_TIME_ZONE_FIELD_NAME;\n augmentedData[timeZoneFieldName] = timeZone;\n dataWithLabels[timeZoneFieldName] = timeZone;\n }\n } else if (formField?.type === \"DROPDOWN\" && value !== undefined) {\n // Find the selected item by ID\n const item = (formField as FormDropdownInput).items.find(\n (item) => item.id === value\n );\n if (item) {\n // Use label if available, otherwise format the ID (remove _ and capitalize)\n if (item.label && item.label.trim().length > 0) {\n dataWithLabels[fieldName] = item.label;\n } else {\n // Format ID: \"contact_us\" -> \"Contact Us\"\n dataWithLabels[fieldName] = value\n .replace(/_/g, \" \")\n .split(\" \")\n .map(\n (word: string) =>\n word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()\n )\n .join(\" \");\n }\n } else {\n dataWithLabels[fieldName] = value;\n }\n } else if (formField?.type === \"DATE\" && value !== undefined) {\n dataWithLabels[fieldName] = reformatDate(value);\n } else {\n dataWithLabels[fieldName] = value;\n }\n }\n\n handleData(augmentedData);\n handleDataWithLabels({ ...clearedLabels, ...dataWithLabels });\n };\n\n const goBackToPrevious = () => {\n pushData(stepData.current);\n\n if (prevStep) {\n prevStep();\n }\n };\n\n const isNextDisabled = () => {\n // for each of the fields, check...\n // 1. for the required ones, do we have entries and are they are valid\n // 2. for the optional ones, if they have any content, make sure they are value\n\n for (const key in fieldErrors) {\n // make sure we are only looking at required fields\n if (fieldConditions[key] === false) {\n continue;\n }\n if (!fieldErrors[key].valid) {\n return true;\n }\n }\n return false;\n };\n\n const onFieldChange = useCallback(\n (name: string, value: string | string[] | object | undefined) => {\n const isFirst = !Object.prototype.hasOwnProperty.call(stepData.current, name);\n\n // When a field was just prefilled (e.g. after FORM_STEP_UPDATE reset), the child\n // component's stale useEffect may fire onFieldChange with its old value before it\n // syncs to the new value prop. Block stale updates; clear the guard once the child\n // reports the matching prefilled value (or any subsequent call after sync).\n if (prefilledFields.current.has(name)) {\n if (!isFirst && stepData.current[name] === value) {\n // Child synced to the prefilled value — clear guard, no-op (value unchanged)\n prefilledFields.current.delete(name);\n return;\n }\n if (!isFirst && stepData.current[name] !== value) {\n // Stale update from child's old state — skip to preserve prefill\n return;\n }\n }\n\n if (!isFirst && stepData.current[name] === value) {\n return;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n value = undefined; // treat empty arrays as undefined\n }\n\n stepData.current = { ...stepData.current, [name]: value };\n\n if (formStep?.fields?.some((field) => field.name === name && field.type === \"DATE\")) {\n setPickedDate(pickedCalendarDate(value));\n }\n\n // Sync to parent ref for tracking purposes\n if (currentStepDataRef) {\n currentStepDataRef.current = stepData.current as Record<string, unknown>;\n }\n\n checkConditions();\n\n if (!isEmpty(fieldErrors)) {\n validate();\n }\n },\n [checkConditions, fieldErrors, validate, currentStepDataRef, formStep]\n );\n\n const config = useContext(SearchWidgetConfigContext);\n\n checkConditions();\n\n const getFields = (): JSX.Element[] => {\n if (!formStep) {\n return [];\n }\n\n const stepFields = formStep.fields || [];\n\n // The card goes where the first of the hidden fields would have been, so it reads in\n // the place the visitor would otherwise have been asked.\n const firstHiddenIndex = stepFields.findIndex((field) => isHiddenSchedulingField(field));\n\n // A date the block leaves no time chip on is not offered at all.\n const blockedDate =\n nextBusinessDayBlock &&\n stepFields.some(\n (field) =>\n isSchedulingField(field) &&\n field.type === \"CHIPS\" &&\n isDateFullyBlocked(\n (field as FormChipsInput).items,\n nextBusinessDayBlock.date,\n nextBusinessDayBlock\n )\n )\n ? nextBusinessDayBlock.date\n : undefined;\n\n const fields = stepFields.map((field, index) => {\n let fieldComponent: JSX.Element | null;\n // The last field of the step gets \"done\" rather than \"next\" on the mobile keyboard\n const isLastField = index === stepFields.length - 1;\n\n if (isHiddenSchedulingField(field)) {\n return index === firstHiddenIndex ? (\n <div key={index} className={`${styles.xapp_formfield} ${styles.active}`}>\n <FormFieldCard\n field={{\n name: \"scheduling_disabled\",\n type: \"CARD\",\n text: SCHEDULING_DISABLED_MESSAGE,\n }}\n onFieldChange={onFieldChange}\n />\n </div>\n ) : null;\n }\n\n switch (field.type) {\n case \"TEXT\":\n if ((field as FormFieldTextAddressInput).format === \"ADDRESS\") {\n fieldComponent = (\n <FormFieldTextInputAddress\n key={field.name}\n field={field as FormFieldTextAddressInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name]}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n googleMapsApiKey={config.googleMapsApiKey}\n mapsBaseUrl={config.mapsBaseUrl}\n />\n );\n } else {\n fieldComponent = (\n <FormFieldTextInput\n key={field.name}\n field={field as FormTextInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name]}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n isLastField={isLastField}\n />\n );\n }\n break;\n case \"DROPDOWN\": {\n // Compute free-form error message if applicable\n const dropdownField = field as FormDropdownInput;\n const currentValue = stepData.current[dropdownField.name];\n let freeFormError: string | undefined;\n\n if (currentValue && currentValue !== \"none\") {\n const selectedItem = dropdownField.items.find(\n (item) => item.id === currentValue\n );\n if (selectedItem && (selectedItem as any).freeFormInput) {\n const freeFormFieldName =\n (selectedItem as any).freeFormFieldName || \"message\";\n freeFormError = fieldErrors[freeFormFieldName]?.message;\n }\n }\n\n fieldComponent = (\n <FormFieldDropdown\n key={field.name}\n field={dropdownField}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n freeFormErrorMessage={freeFormError}\n />\n );\n break;\n }\n case \"CHECK\":\n fieldComponent = (\n <FormFieldSelect\n key={field.name}\n field={field as FormChipsInput}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n />\n );\n break;\n case \"CHIPS\":\n fieldComponent = (\n <FormFieldChips\n key={field.name}\n field={field as FormChipsInput}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n value={stepData.current[field.name] as string[] | undefined}\n disabledItemIds={\n isSchedulingField(field)\n ? blockedChipIds(\n (field as FormChipsInput).items,\n pickedDate,\n nextBusinessDayBlock\n )\n : undefined\n }\n />\n );\n break;\n case \"DATE\":\n const busyDays = context?.busyDays;\n\n fieldComponent = (\n <FormFieldDate\n key={field.name}\n field={field as FormDateInput}\n onFieldChange={onFieldChange}\n errorMessage={fieldErrors[field.name]?.message}\n busyDays={busyDays}\n loading={loading}\n blockedDate={blockedDate}\n />\n );\n break;\n case \"DATETIME\":\n fieldComponent = (\n <FormFieldDateTime\n key={field.name}\n field={field as FormDateTimeInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name] as FormDateTimeValue | undefined}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n busyDays={context?.busyDays}\n offeringsByDate={offeringsByDate}\n nextBusinessDayBlock={nextBusinessDayBlock}\n preselectFirstAvailable={props.preselectFirstAvailableDate}\n />\n );\n break;\n case \"DATERANGE\":\n fieldComponent = (\n <FormFieldDateRange\n key={field.name}\n field={field as FormDateRangeInput}\n onFieldChange={onFieldChange}\n value={stepData.current[field.name] as FormDateRangeValue | undefined}\n errorMessage={fieldErrors[field.name]?.message}\n required={field.mandatory}\n isLastField={isLastField}\n />\n );\n break;\n\n case \"CARD\":\n fieldComponent = (\n <FormFieldCard\n key={field.name}\n field={replaceValues(field, getDataWithLabels()) as FormCardInput}\n onFieldChange={onFieldChange}\n />\n );\n break;\n\n default:\n fieldComponent = null;\n }\n\n return (\n <div\n key={index}\n className={`${styles.xapp_formfield} ${\n fieldConditions[field.name] !== false ? styles.active : \"\"\n }`}\n >\n {fieldComponent}\n </div>\n );\n });\n\n return fields.filter((field): field is JSX.Element => field !== null);\n };\n\n const fullBleed = !!formStep && (formStep as FormStepWithUnloadWarning).fullBleed;\n\n return (\n <div className={fullBleed ? styles.xapp_step_full_bleed : undefined}>\n {!hideIntro && !!formStep && (formStep.title || formStep.subtitle) && (\n <div className={styles.xapp_formfield_title}>\n {!!formStep.title && <p>{formStep.title}</p>}\n {!!formStep.subtitle && (\n <p className={styles.xapp_formfield_subtitle}>{formStep.subtitle}</p>\n )}\n </div>\n )}\n\n {!!formStep && (formStep as FormStepWithUnloadWarning).warnBeforeUnloadMessage && (\n <div\n style={{\n backgroundColor: \"#fff3cd\",\n color: \"#856404\",\n padding: \"12px 16px\",\n marginBottom: \"16px\",\n borderRadius: \"4px\",\n border: \"1px solid #ffeaa7\",\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n }}\n >\n <span style={{ fontSize: \"20px\" }}>⚠️</span>\n <span>{(formStep as FormStepWithUnloadWarning).warnBeforeUnloadMessage}</span>\n </div>\n )}\n\n {isFormStepIframe(formStep) && (\n <div className={styles.xapp_step_iframe_wrapper}>\n <iframe\n src={formStep.iframe.src}\n title={formStep.title}\n width={formStep.iframe.width || \"100%\"}\n height={formStep.iframe.height || \"100%\"}\n frameBorder=\"0\"\n allowFullScreen\n />\n </div>\n )}\n {isFormStepExternalWidget(formStep) && (\n <div className={styles.xapp_external_widget_container}>\n <div\n id={formStep.externalWidget.anchorId}\n className={styles.xapp_external_widget_anchor}\n />\n {isActive &&\n externalWidgetOutcome === \"pending\" &&\n !externalWidgetContentShown && (\n <div\n className={styles.xapp_external_widget_loading}\n role=\"status\"\n aria-live=\"polite\"\n >\n <span className={styles.xapp_external_widget_spinner}>\n <SpinnerIcon />\n </span>\n <p>Finding available appointments&hellip;</p>\n </div>\n )}\n {(externalWidgetOutcome === \"no_render\" || externalWidgetOutcome === \"error\") &&\n !formStep.externalWidget.fallbackStep && (\n <div className={styles.xapp_external_widget_fallback}>\n <p>\n {\n \"We're sorry, we couldn't load the booking form. Please try again later.\"\n }\n </p>\n </div>\n )}\n </div>\n )}\n <div>{getFields()}</div>\n\n {!!submitError && (\n <div className={styles.xapp_submit_error} role=\"alert\">\n <p>{submitError}</p>\n </div>\n )}\n\n <div\n className={`${styles.xapp_form_actions} ${\n (formStep as any).final ? styles.xapp_form_actions_final : \"\"\n }`}\n // A marker as well as the class: the class is what the css reads, the marker is\n // what a test can see (this module's classes do not resolve under jest).\n {...((formStep as any).final ? { \"data-xapp-final-actions\": \"\" } : {})}\n >\n {/* For final steps, show the next button centered above the previous button --\n or beside it, when the theme asks for `finalButtonPlacement: \"inline\"`. */}\n {!!nextStep && formStep.nextAction !== \"omit\" && (formStep as any).final && (\n <div className={styles.xapp_final_button_container}>\n <button\n type=\"button\"\n className={`${styles.xapp_step_button} ${\n isNextDisabled() || isSubmitting\n ? styles.xapp_disabled_button\n : formStep.nextLabel\n ? styles.xapp_secondary_button\n : styles.xapp_primary_button\n }`}\n disabled={isSubmitting}\n onClick={continueToNext}\n >\n {isSubmitting ? \"Loading...\" : formStep.nextLabel || \"Next\"}\n </button>\n </div>\n )}\n\n <div className={styles.xapp_form_nav_buttons}>\n {prevStep === undefined && <div className={styles.xapp_dummy_button}></div>}\n\n {!!prevStep && formStep.previousAction !== \"omit\" && (\n <button\n type=\"button\"\n className={`${styles.xapp_step_button} ${styles.xapp_primary_button} ${styles.xapp_back_button}`}\n onClick={goBackToPrevious}\n aria-label={formStep.previousLabel || \"Previous\"}\n >\n {/* Both shapes are rendered and the theme displays exactly one -- see\n getBackButtonStyle. The arrow is decorative; the accessible name is\n on the button itself, so the icon variant is not a nameless control. */}\n <span className={styles.xapp_back_button_label}>\n {formStep.previousLabel || \"Previous\"}\n </span>\n <span className={styles.xapp_back_button_icon} aria-hidden=\"true\">\n &#8592;\n </span>\n </button>\n )}\n\n {/* For non-final steps, show the next button in the normal position */}\n {!!nextStep && formStep.nextAction !== \"omit\" && !(formStep as any).final && (\n <button\n type=\"button\"\n className={`${styles.xapp_step_button} ${\n isNextDisabled() || isSubmitting\n ? styles.xapp_disabled_button\n : formStep.nextLabel\n ? styles.xapp_secondary_button\n : styles.xapp_primary_button\n }`}\n disabled={isSubmitting}\n onClick={continueToNext}\n >\n {isSubmitting ? \"Loading...\" : formStep.nextLabel || \"Next\"}\n </button>\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default FormStepDisplay;\n","\nimport {\n FormInput,\n FormTextInput,\n FormChipsInput,\n FormDateRangeInput,\n FormDateTimeInput,\n FormDropdownInput,\n} from \"stentor-models\";\n\nexport function isFormTextInput(field: FormInput): field is FormTextInput {\n return !!field && field.type === \"TEXT\";\n}\n\nexport function isFormChipsInput(field: FormInput): field is FormChipsInput {\n return !!field && field.type === \"CHIPS\";\n}\n\nexport function isFormDateInput(field: FormInput): field is FormChipsInput {\n return !!field && field.type === \"DATE\";\n}\n\nexport function isFormCheckInput(field: FormInput): field is FormChipsInput {\n return !!field && field.type === \"CHECK\";\n}\n\nexport function isFormDateRangeInput(field: FormInput): field is FormDateRangeInput {\n return !!field && field.type === \"DATERANGE\";\n}\n\nexport function isFormDateTimeInput(field: FormInput): field is FormDateTimeInput {\n return !!field && field.type === \"DATETIME\";\n}\n\nexport function isFormDropdownInput(field: FormInput): field is FormDropdownInput {\n return !!field && field.type === \"DROPDOWN\";\n}","import React, { FC } from \"react\";\n\nimport { PartnerFormFraming } from \"@xapp/stentor-form-widget-channel\";\n\nimport styles from \"./FormFrame.module.scss\";\n\nexport interface FormFrameProps {\n /**\n * The partner chrome to draw. Without it nothing here renders anything but\n * the children.\n */\n readonly framing?: PartnerFormFraming;\n /**\n * Draw the frame and the tab.\n *\n * Off for a booking handoff step -- the partner's embed brings its own frame,\n * and a second one around it reads as a mistake.\n */\n readonly framed?: boolean;\n readonly children?: React.ReactNode;\n}\n\n/**\n * The partner framing around one form step: the tab off the top of the card, an\n * optional intro block carrying the PRESET's own copy, and the framed card itself.\n *\n * The intro deliberately does not fall back to the step's title. Step titles are\n * progress labels sized for a stepper -- \"Request\", \"Contact Information\" -- and\n * rendering one here turned it into a page-sized banner over the tab that nobody\n * authored. A preset that wants a headline says so with `framing.introTitle`.\n *\n * Only ever rendered when a partner style preset resolved, which only happens on\n * the stand-alone page -- see resolveFormStyle.\n */\nexport const FormFrame: FC<FormFrameProps> = (props) => {\n const { framing, framed, children } = props;\n\n const tabLabel = framing?.tabLabel;\n const title = framing?.introTitle;\n const subtitle = framing?.introSubtitle;\n const introPlacement = framing?.introPlacement || \"above-tab\";\n\n const intro =\n title || subtitle ? (\n <div className={styles.xapp_form_frame_intro} data-xapp-form-frame-intro=\"\">\n {!!title && (\n <h2 className={styles.xapp_form_frame_title} data-xapp-form-frame-title=\"\">\n {title}\n </h2>\n )}\n {!!subtitle && (\n <p className={styles.xapp_form_frame_subtitle} data-xapp-form-frame-subtitle=\"\">\n {subtitle}\n </p>\n )}\n </div>\n ) : null;\n\n return (\n <div className={styles.xapp_form_frame_root}>\n {introPlacement === \"above-tab\" && intro}\n {/* The tab is a sibling ABOVE the card, not absolutely positioned inside it: in the\n approved design it is a tab sitting on the card's top edge (rounded top corners\n only, square bottom), and the card is pulled up to tuck under it. Centring a fully\n rounded pill over the border reads as a badge instead. The row keeps the intro's\n white background running behind the tab so the two read as one white block. */}\n {framed && !!tabLabel && (\n <div className={styles.xapp_form_frame_tab_row}>\n <span className={styles.xapp_form_frame_tab} data-xapp-form-frame-tab=\"\">\n {tabLabel}\n </span>\n </div>\n )}\n <div\n className={framed ? styles.xapp_form_frame_framed : styles.xapp_form_frame_plain}\n data-xapp-form-frame={framed ? \"framed\" : \"plain\"}\n >\n {introPlacement === \"inline\" && intro}\n {children}\n </div>\n </div>\n );\n};\n\nexport default FormFrame;\n","import React from \"react\";\n\nimport { FormHeaderItem } from \"stentor-models\";\n\nimport styles from './SimpleNavigationHeader.module.scss';\n\ninterface SimpleNavigationHeaderProps {\n items: FormHeaderItem[];\n onHeaderClick(step: string): void;\n labelHeader?: boolean;\n stepName: string;\n isShowCase?: boolean;\n}\n\nexport const SimpleNavigationHeader: React.FC<SimpleNavigationHeaderProps> = (\n props: SimpleNavigationHeaderProps\n) => {\n const { items, onHeaderClick, labelHeader, stepName, isShowCase } = props;\n\n if (!!labelHeader) {\n const header = items.find((item) => item.step === stepName);\n const headerText = header?.label;\n\n // Nothing to say, so nothing is drawn. This used to render the same coloured Box with an\n // empty div inside, which on a step the header has no label for -- the CostGuide booking\n // handoff is not in the header array -- painted a bare teal band above the partner's own\n // form. The band was never authored; it is the header showing up with no content.\n if (headerText === undefined) {\n return null;\n }\n\n return (\n <div\n className={`${styles.xapp_navigation_header_row} ${\n !!isShowCase ? styles.xapp_navigation_header_showcase : styles.xapp_navigation_header_container\n }`}>\n <h4 className={styles.xapp_navigation_header_title}>{headerText}</h4>\n </div>\n );\n } else {\n return (\n <div className={`${styles.xapp_navigation_header_row} ${styles.xapp_navigation_header}`}>\n <div className={styles.xapp_navigation_header_track}>\n {items.map((item, index) => (\n <div key={index} className={styles.xapp_navigation_header_step}>\n <button\n type=\"button\"\n aria-label={item.label}\n className={`${styles.xapp_navigation_header} ${styles.xapp_navigation_header_dot}`}\n onClick={() => {\n onHeaderClick(`${item.step}`);\n }}\n />\n <p className={styles.xapp_navigation_header_label}>{item.label}</p>\n </div>\n ))}\n </div>\n </div>\n );\n }\n};\n","/*! Copyright (c) 2025, XAPP AI */\n\n/**\n * From a given zip code, determine if it is in the service area defined by the provided zip codes.\n *\n * @param zip Zip code as a string\n * @param zipCodes Array of zip codes that define the service area, masking is supported, such as \"12345\", \"1234*\", \"123*5\", \"12*45\".\n */\nexport function isInServiceArea(zip: string, zipCodes: string[]): boolean {\n // Normalize input ZIP: keep only 5 digits\n const baseZip = zip.slice(0, 5);\n\n const foundSupportedZip = zipCodes.find((supportedZip) => {\n // If the supported zip code is an exact match, return true\n if (supportedZip === baseZip) {\n return true;\n }\n\n // If the supported zip code contains asterisks, we need to check for a match\n if (supportedZip.includes(\"*\")) {\n // Replace asterisks with regex wildcard and create a regex pattern\n const regexPattern = supportedZip.replace(/\\*/g, \"\\\\d\") + \"$\";\n const regex = new RegExp(`^${regexPattern}`);\n return regex.test(baseZip);\n }\n\n // If no match found, return false\n return false;\n });\n\n // If we found a supported zip code, return true, otherwise false\n return !!foundSupportedZip;\n}\n","/**\n * Extracts the ZIP code from a given address string.\n *\n * @param address The address string to extract the ZIP code from.\n * @returns The extracted ZIP code, or undefined if no valid ZIP code is found.\n */\nexport function extractZipFromAddress(address?: string): string | undefined {\n if (!address) return undefined;\n\n const matches = address.match(/\\b\\d{5}(?:-\\d{4})?\\b/g);\n if (!matches) return undefined;\n\n for (let i = matches.length - 1; i >= 0; i--) {\n const zip = matches[i];\n const index = address.indexOf(zip);\n const before = address.slice(0, index);\n\n // Heuristic 1: ZIP appears after a comma or 2-letter state code\n if (/(,|\\b[A-Z]{2})\\s*$/.test(before.trim())) {\n return zip;\n }\n\n // Heuristic 2: ZIP appears far enough into the string (e.g. not a house number)\n if (index > 15) {\n return zip;\n }\n }\n\n return undefined;\n}\n","import React, { FC, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { FormStep, MultistepForm } from \"stentor-models\";\n\nimport { FormActionResponseData, FormNextData, FormStepUpdateDisplay } from \".\";\nimport { FormStepDisplay, isFormStepExternalWidget } from \"../FormStepDisplay\";\nimport { FormFrame } from \"../FormFrame\";\nimport { ExternalWidgetConfig } from \"../../utils/useExternalWidget\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\n\nimport { SimpleNavigationHeader } from \"../SimpleNavigationHeader\";\nimport { err } from \"../../utils\";\nimport { addContextPrefix } from \"../../utils/comparator\";\nimport { isInServiceArea } from \"../../utils/isInServiceArea\";\nimport { extractZipFromAddress } from \"../../utils/extractZipFromAddress\";\n\nimport styles from \"./FormDisplay.module.scss\";\n\ninterface FormNextResponse {\n displays?: FormStepUpdateDisplay[];\n}\n\n/**\n * Shown on the step whose FORM_SUBMIT dispatch failed. That dispatch is the request\n * that creates the lead, so a silent failure loses it -- the user must be told rather\n * than left believing they submitted (issue #1373).\n */\nexport const SUBMIT_ERROR_MESSAGE =\n \"We couldn't submit your information. Please check your connection and try again.\";\n\n/**\n * How long the handoff step waits for the FORM_SUBMIT response before injecting the partner\n * script with only the static config.\n *\n * The handoff is reached by a submit, and FormWidget dispatches FORM_SUBMIT fire-and-forget so the\n * UI is not blocked -- the step goes active before the response lands. The per-submission values\n * (zipCode, name, trade) only exist in that response, and a partner script that reads its config\n * global once at load will never see them if we inject first. CostGuide does exactly that: it read\n * the static config, found no zip, and asked the visitor for one we already had.\n *\n * Waiting is bounded so a failed or slow submit still reaches the partner's form. That is degraded\n * -- no prefill -- rather than broken.\n */\nexport const EXTERNAL_WIDGET_CONFIG_WAIT_MS = 5000;\n\ninterface StepOverride {\n fields?: unknown[];\n externalWidget?: {\n config?: Record<string, string | number | boolean>;\n };\n}\n\n/**\n * Extended FormStep interface to support additional per-step properties not yet in stentor-models.\n */\nexport interface ExtendedFormStep extends FormStep {\n /**\n * If true, shows a browser warning dialog when the user attempts to leave the page.\n * Useful for confirmation steps where the user hasn't submitted yet.\n */\n warnBeforeUnload?: boolean;\n /**\n * Optional message to display in a visual warning banner.\n * The browser's beforeunload dialog will show a generic message (browsers ignore custom messages for security).\n * This message is displayed in a yellow warning banner for better visibility, especially on mobile.\n */\n warnBeforeUnloadMessage?: string;\n /**\n * When true, fires a FORM_NEXT server callback before advancing past this step.\n * The server can return a FORM_STEP_UPDATE display to dynamically replace the next step's fields.\n * If the call fails or exceeds 3 seconds, the widget proceeds with the existing client-side fields.\n */\n serverCallback?: boolean;\n}\n\ninterface StandardFormData {\n address?: string;\n email?: string;\n full_name?: string;\n first_name?: string;\n last_name?: string;\n phone?: string;\n zip?: string;\n zip_code?: string;\n\n [key: string]: string | undefined;\n}\n\nexport interface FormDisplayProps {\n readonly form: MultistepForm;\n readonly loading: boolean;\n /**\n * Zero-based step to open on, instead of the first.\n *\n * For previews that want to show a particular step -- the booking preview on\n * get.xapp.ai opens on the date and time step, because the calendar is the\n * part worth showing. Applied once, when the form first arrives with steps,\n * so navigating away from it sticks. An index the form has no step for is\n * ignored and the form opens where it always would.\n */\n readonly initialStep?: number;\n /**\n * Open the date/time step on the soonest day that has times, rather than on\n * \"Select a date to see the available times.\"\n *\n * For a preview that lands straight on that step: an empty column beside a\n * calendar reads as a form with nothing to offer. Off by default -- on a real\n * booking page a preselected date is one the customer never chose.\n */\n readonly preselectFirstAvailableDate?: boolean;\n /**\n * Fired with the step index when {@link FormDisplayProps.initialStep} is\n * actually applied, and not at all when it is ignored.\n *\n * FormWidget keeps its own `currentStepRef` and only ever writes it from the\n * next/previous tracking callbacks, so a form that jumps straight to a step\n * without saying so leaves that ref on 0 -- and every abandonment path (close,\n * the beforeunload beacon, the tab-hidden timeout) reads it for lastStepIndex\n * and completionPercentage. This keeps the two in step.\n */\n onTrackInitialStep?: (stepIndex: number) => void;\n /**\n * Dispatches the form action. For FORM_SUBMIT this is the request that creates the\n * lead, so the returned promise is awaited and a rejection is surfaced to the user\n * -- see onSubmitForm. Implementations that return void keep the old fire-and-forget\n * behaviour.\n */\n onActionResponse(data: unknown, action: string): void | Promise<unknown>;\n isShowCase?: boolean;\n /**\n * Callback to track next_step event\n */\n onTrackNextStep?: (\n stepName: string,\n stepIndex: number,\n stepData: Record<string, unknown>,\n isLastStep: boolean\n ) => void;\n /**\n * Callback to track previous_step event\n */\n onTrackPreviousStep?: (\n fromStepName: string,\n fromStepIndex: number,\n toStepName: string,\n toStepIndex: number\n ) => void;\n /**\n * Callback to track submit event\n */\n onTrackSubmit?: (\n stepName: string,\n stepIndex: number,\n completedData: Record<string, unknown>,\n totalSteps: number\n ) => void;\n /**\n * Callback to track a FORM_SUBMIT dispatch that failed outright. onTrackSubmit fires\n * on a different endpoint before the dispatch, so without this a lost lead leaves a\n * submit event behind and no counter-signal at all.\n */\n onTrackSubmitFailure?: (\n stepName: string,\n stepIndex: number,\n totalSteps: number,\n reason: string\n ) => void;\n /**\n * Ref to sync current step data for tracking purposes\n */\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /**\n * When provided, fires a FORM_NEXT request before advancing to the next step.\n * The server can return a FORM_STEP_UPDATE display to replace the next step's fields.\n * If the call fails or exceeds 3 seconds, the widget proceeds with the existing fields.\n */\n onFormNext?: (data: FormNextData) => Promise<unknown>;\n /**\n * A FORM_STEP_UPDATE display extracted from the (fire-and-forget) FORM_SUBMIT\n * response, forwarded down from FormWidget. A new object reference triggers\n * applying the update to the named step's overrides -- see the effect below.\n */\n stepUpdate?: FormStepUpdateDisplay;\n /**\n * Callback to track a booking-widget handoff step's anchor gaining content\n * within its render timeout\n */\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n /**\n * Callback to track a booking-widget handoff step's render timeout elapsing\n * with an empty anchor\n */\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n /**\n * Callback to track the partner script invoking the configured success callback\n */\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n /**\n * Callback to track a booking-widget handoff step's script failing to load\n */\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n}\n\nexport const FormDisplay: FC<FormDisplayProps> = (props) => {\n const {\n form,\n onActionResponse,\n isShowCase,\n loading,\n onTrackNextStep,\n onTrackPreviousStep,\n onTrackSubmit,\n onTrackSubmitFailure,\n currentStepDataRef,\n initialStep,\n preselectFirstAvailableDate,\n onTrackInitialStep,\n onFormNext,\n stepUpdate,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n } = props;\n // TODO: const title = form?.title;\n\n // Partner chrome from a resolved style preset. Undefined for an embedded form --\n // presets only ever resolve on the stand-alone page -- so the markup below is\n // byte for byte what it was before presets existed.\n const { framing } = useContext(SearchWidgetConfigContext);\n\n const [currentStep, setCurrentStep] = useState(0);\n /** Whether {@link FormDisplayProps.initialStep} has been honoured yet. */\n const appliedInitialStep = useRef(false);\n const [stepOverrides, setStepOverrides] = useState<Record<string, StepOverride>>({});\n // The index of the step whose submit failed, so the message renders on that step\n // only -- an error shown on some *other* step would be nonsense.\n //\n // In practice this is visible for the final step, which is the one that matters:\n // it never advances, so it is still on screen when its dispatch rejects. A\n // non-final submitting step has already advanced by then and inactive steps are\n // display:none, so its banner stays hidden unless the user navigates back to it.\n // That is deliberate: its submit is not the lead (the final one carries all of\n // formData), and blocking the advance would strand the user short of the step that\n // does create the lead. onTrackSubmitFailure still fires for it either way.\n const [failedSubmitStep, setFailedSubmitStep] = useState<number | undefined>(undefined);\n // const [submitted, setSubmitted] = useState(false);\n\n // Applies a FORM_STEP_UPDATE display (from either a FORM_NEXT or FORM_SUBMIT\n // response) to the named step's overrides. externalWidget.config is\n // shallow-merged over whatever config is already present (the static step\n // definition, or an earlier update), with the new values winning on conflict.\n // A fields-only update behaves exactly as before: it fully replaces the\n // override's fields, leaving any existing externalWidget override untouched.\n const applyFormStepUpdate = (display: FormStepUpdateDisplay) => {\n const stepName = display.step;\n if (!stepName) {\n return;\n }\n setStepOverrides((prev) => {\n const existing = prev[stepName];\n const next: StepOverride = { fields: display.fields || [] };\n if (display.externalWidget?.config) {\n handoffConfigSettledRef.current[stepName] = true;\n next.externalWidget = {\n config: {\n ...existing?.externalWidget?.config,\n ...display.externalWidget.config,\n },\n };\n } else if (existing?.externalWidget) {\n next.externalWidget = existing.externalWidget;\n }\n return { ...prev, [stepName]: next };\n });\n };\n\n // Applies a FORM_STEP_UPDATE surfaced from the fire-and-forget FORM_SUBMIT\n // response. `stepUpdate` is a fresh object reference each time FormWidget\n // detects one, so this only ever runs on a genuine new update.\n useEffect(() => {\n if (stepUpdate) {\n applyFormStepUpdate(stepUpdate);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [stepUpdate]);\n\n // True from the moment a submit starts advancing to a handoff step until that submit settles.\n // See EXTERNAL_WIDGET_CONFIG_WAIT_MS.\n const [awaitingHandoffConfig, setAwaitingHandoffConfig] = useState(false);\n // The wait is a once-per-handoff-step thing, keyed by step name. Once per FORM would be\n // wrong twice over: a visitor who steps back and returns would re-arm the wait and sit in\n // front of a spinner over an embed that already rendered, and a form with a SECOND handoff\n // step would inherit the first's settle, never arm its own wait, and hand that partner the\n // static config on the render it became active.\n const handoffConfigSettledRef = useRef<Record<string, boolean>>({});\n\n // Bounds the wait above. Reset per step so returning to a handoff waits again rather than\n // inheriting a previous step's expiry.\n const [externalWidgetWaitElapsed, setExternalWidgetWaitElapsed] = useState(false);\n useEffect(() => {\n setExternalWidgetWaitElapsed(false);\n const activeStep = form.steps?.[currentStep];\n if (!activeStep || !isFormStepExternalWidget(activeStep)) {\n return undefined;\n }\n const timer = setTimeout(() => {\n setExternalWidgetWaitElapsed(true);\n // Given up on for good, for THIS step, not just for this pass.\n handoffConfigSettledRef.current[activeStep.name] = true;\n setAwaitingHandoffConfig(false);\n }, EXTERNAL_WIDGET_CONFIG_WAIT_MS);\n return () => clearTimeout(timer);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [currentStep]);\n\n const fieldTests = useRef({});\n\n useEffect(() => {\n if (Array.isArray(form.steps) && form.steps.length > 0) {\n for (const step of form.steps) {\n if (step.condition) {\n const conditionWithThis = addContextPrefix(step.condition, \"context\", [\n \"isInServiceArea\",\n ]);\n\n fieldTests.current[step.name] = (context) =>\n // eslint-disable-next-line no-new-func\n new Function(\n \"context\",\n \"isInServiceArea\",\n `return (${conditionWithThis});`\n )(context, isInServiceArea);\n }\n }\n }\n }, [form?.steps]);\n\n useEffect(() => {\n // Check if currentIndex is out of bounds\n if (currentStep < 0 || currentStep >= form?.steps?.length) {\n setCurrentStep(0);\n }\n }, [form?.steps, currentStep]);\n\n useEffect(() => {\n // Deliberately not a useState initialiser. The form arrives\n // asynchronously, so at mount there are no steps yet and the bounds\n // guard above would reset the index to 0 before it ever rendered.\n //\n // The ref makes it fire once. Without it, every re-render carrying the\n // same initialStep would drag the user back to the step they had just\n // navigated away from.\n if (appliedInitialStep.current) return;\n if (typeof initialStep !== \"number\") return;\n\n const steps = form?.steps;\n if (!steps?.length) return;\n\n appliedInitialStep.current = true;\n\n // An index the form has no step for is the caller's mistake. Opening\n // where the form always would beats rendering nothing.\n if (initialStep > 0 && initialStep < steps.length) {\n setCurrentStep(initialStep);\n onTrackInitialStep?.(initialStep);\n }\n }, [form?.steps, initialStep, onTrackInitialStep]);\n\n // Memoize the current step's warnBeforeUnload value to prevent unnecessary effect re-runs\n const shouldWarnBeforeUnload = useMemo(() => {\n const currentFormStep = form.steps?.[currentStep] as ExtendedFormStep | undefined;\n return currentFormStep?.warnBeforeUnload ?? false;\n }, [currentStep, form.steps]);\n\n // Handle beforeunload warning for steps that require it\n useEffect(() => {\n if (shouldWarnBeforeUnload) {\n const handleBeforeUnload = (e: BeforeUnloadEvent) => {\n e.preventDefault();\n // eslint-disable-next-line no-param-reassign\n e.returnValue = \"\"; // Required for Chrome\n return \"\"; // For older browsers\n };\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n\n return () => {\n window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n };\n }\n\n return undefined;\n }, [shouldWarnBeforeUnload]);\n\n const formData = useRef<StandardFormData>({});\n const formDataWithLabels = useRef({});\n const lastStepData = useRef<object>({});\n const formSubmittedRef = useRef(false);\n\n // Re-arm the submit guard whenever the form moves to a different step, so the\n // guard only ever collapses repeat submissions of the *same* step. The final\n // step never advances, so its latch holds and the lead is still submitted once.\n useEffect(() => {\n formSubmittedRef.current = false;\n }, [currentStep]);\n\n const nextStep = async (submit?: boolean) => {\n let nextStepIndex = -1;\n\n for (let i = currentStep + 1; i < form.steps.length; i++) {\n const formStepItem = form.steps[i];\n\n const test = fieldTests.current[formStepItem.name];\n\n const zip =\n formData.current.zip_code ||\n formData.current.zip ||\n extractZipFromAddress(formData.current.address);\n\n // Build the context to pass in\n const context = {\n ...formData.current,\n zip,\n };\n\n if (test) {\n // eslint-disable-next-line @typescript-eslint/ban-types\n if ((test as Function)(context)) {\n nextStepIndex = i;\n break;\n }\n } else {\n nextStepIndex = i;\n break;\n }\n }\n\n // Fire FORM_NEXT before advancing only when the current step has serverCallback: true\n const currentStepDef = form.steps[currentStep] as ExtendedFormStep;\n if (nextStepIndex >= 0 && !submit && onFormNext && currentStepDef?.serverCallback) {\n // Clear any stale override for the upcoming step before the server call,\n // so a timeout/error doesn't leave outdated fields from a previous pass.\n setStepOverrides((prev) => {\n const next = { ...prev };\n delete next[form.steps[nextStepIndex].name];\n return next;\n });\n try {\n const timeout = new Promise<undefined>((resolve) =>\n setTimeout(() => resolve(undefined), 3000)\n );\n const request = onFormNext({\n result: lastStepData.current as Record<string, unknown>,\n form: form.name,\n step: form.steps[currentStep].name,\n nextStep: form.steps[nextStepIndex].name,\n });\n const response = await Promise.race([request, timeout]);\n const r = response as FormNextResponse;\n if (r?.displays) {\n for (const display of r.displays) {\n if (display.type === \"FORM_STEP_UPDATE\") {\n applyFormStepUpdate(display);\n }\n }\n }\n } catch {\n // Graceful degradation: proceed with existing step fields\n }\n }\n\n // The handoff step is reached by a submit, and its per-submission config (zipCode, name,\n // trade) only exists in that response. Flag the wait BEFORE advancing so the step never\n // renders unflagged for a frame and injects the partner script with the static config.\n const advancingToHandoff =\n nextStepIndex >= 0 && !!submit && isFormStepExternalWidget(form.steps[nextStepIndex]);\n if (advancingToHandoff && !handoffConfigSettledRef.current[form.steps[nextStepIndex].name]) {\n setAwaitingHandoffConfig(true);\n }\n\n if (nextStepIndex >= 0) {\n setCurrentStep(nextStepIndex);\n }\n\n if (!!submit) {\n // Awaited so FormStepDisplay's own isSubmitting state stays set for the\n // duration of the dispatch, and so a rejection is handled rather than\n // becoming an unhandled rejection (issue #1373).\n // Pass the current step index since state updates are async\n //\n // The wait is deliberately NOT released here. The dispatch resolving is not the\n // config arriving: FormWidget surfaces the FORM_STEP_UPDATE as state, which reaches\n // this component a render later. Releasing on settle injected the partner script\n // inside that gap with the static config only -- 7-14ms measured against the live\n // page, against CostGuide's own bundle landing ~90ms after, so whether a visitor was\n // prefilled came down to which of the two won. It is released by the override\n // actually being present, and bounded by EXTERNAL_WIDGET_CONFIG_WAIT_MS so a submit\n // that fails or returns nothing still reaches the partner's form without prefill.\n await onSubmitForm(currentStep);\n }\n };\n\n const prevStep = () => {\n const fromStepIndex = currentStep;\n const fromStepName = form.steps?.[fromStepIndex]?.name || \"unknown\";\n\n for (let i = currentStep - 1; i >= 0; i--) {\n const step = form.steps[i];\n const test = fieldTests.current[step.name];\n\n const zip =\n formData.current.zip_code ||\n formData.current.zip ||\n extractZipFromAddress(formData.current.address);\n\n const context = {\n ...formData.current,\n zip,\n };\n\n if (test) {\n // eslint-disable-next-line @typescript-eslint/ban-types\n if ((test as Function)(context)) {\n // Track previous_step event before changing step\n if (onTrackPreviousStep) {\n onTrackPreviousStep(fromStepName, fromStepIndex, step.name, i);\n }\n setCurrentStep(i);\n break;\n }\n } else {\n // Track previous_step event before changing step\n if (onTrackPreviousStep) {\n onTrackPreviousStep(fromStepName, fromStepIndex, step.name, i);\n }\n setCurrentStep(i);\n break;\n }\n }\n };\n\n const handleData = (data: object) => {\n lastStepData.current = data;\n formData.current = { ...formData.current, ...data };\n };\n\n const getData = () => {\n return formData.current;\n };\n\n const handleDataWithLabels = (data: object) => {\n formDataWithLabels.current = { ...formDataWithLabels.current, ...data };\n };\n\n const getDataWithLabels = () => {\n return formDataWithLabels.current;\n };\n\n const onSubmitForm = async (submitStepIndex?: number) => {\n // Guard against double-firing the backend submission for a single step: a\n // double-click before the \"submitting\" UI state flushes, a re-render, or a\n // retry can invoke this more than once for the same submission. The latch is\n // scoped to the current step, re-armed by the effect above -- see there for why.\n if (formSubmittedRef.current) {\n return;\n }\n formSubmittedRef.current = true;\n\n // Use provided step index or fall back to currentStep\n const stepIndex = submitStepIndex ?? currentStep;\n const safeStepIndex = stepIndex >= 0 && stepIndex < form.steps.length ? stepIndex : 0;\n\n // Track submit event if tracking callback is provided\n if (onTrackSubmit) {\n onTrackSubmit(\n form.steps[safeStepIndex].name,\n safeStepIndex,\n formData.current as Record<string, unknown>,\n form.steps.length\n );\n }\n\n const data: FormActionResponseData = {\n result: formData.current,\n form: form.name,\n step: form.steps[safeStepIndex].name,\n final: !!form.steps[safeStepIndex].final,\n };\n if (typeof onActionResponse !== \"function\") {\n return;\n }\n\n // This dispatch is what creates the lead. onTrackSubmit above has already\n // recorded the submit on a *different* endpoint, so if this fails and nobody\n // notices, the analytics say the form was submitted and no lead exists --\n // exactly the loss reported in issue #1373. Await it, and on failure re-arm the\n // guard (otherwise the user's retry click is swallowed), tell the user, and\n // emit the counter-signal.\n setFailedSubmitStep(undefined);\n try {\n await onActionResponse(data, \"FORM_SUBMIT\");\n } catch (error) {\n formSubmittedRef.current = false;\n setFailedSubmitStep(safeStepIndex);\n\n const reason = error instanceof Error ? error.message : String(error);\n err(`FORM_SUBMIT failed on step ${form.steps[safeStepIndex].name}: ${reason}`);\n\n if (onTrackSubmitFailure) {\n onTrackSubmitFailure(\n form.steps[safeStepIndex].name,\n safeStepIndex,\n form.steps.length,\n reason\n );\n }\n }\n };\n\n const onHeaderClick = (step: string) => {\n const condition = (formStep: FormStep) => formStep.name === step;\n const index = form.steps.findIndex(condition);\n\n if (index === -1) {\n err(`Header click: Cannot find step to jump to: ${step}`);\n return;\n }\n\n setCurrentStep(index);\n };\n\n // A booking-widget handoff step is terminal (previousAction/nextAction: \"omit\"),\n // so the only way out of it is a forced jump: the partner script failed to\n // render or errored, and externalWidget.fallbackStep names where to go instead.\n const jumpToExternalWidgetFallback = (fallbackStep: string) => {\n const index = form.steps.findIndex((formStep) => formStep.name === fallbackStep);\n\n if (index === -1) {\n err(`External widget fallback: Cannot find step to jump to: ${fallbackStep}`);\n return;\n }\n\n setCurrentStep(index);\n };\n\n let step = currentStep;\n\n // Safety\n if (currentStep < 0 || currentStep >= form?.steps?.length) {\n step = 0;\n }\n\n // In labelHeader mode SimpleNavigationHeader renders the current step's header label as a\n // full-width h4 banner. When a partner preset draws its own tab that is two headers stacked on\n // one step -- and the banner is the one nobody designed for this layout: the labels come from\n // the handler's stepper (\"Request\", \"Contact Info\"), sized for a progress strip. The tab wins.\n //\n // Only the label variant. The stepper variant is genuine progress UI and stays.\n //\n // And only where a tab is actually drawn. The tab is per-step and only on FRAMED steps -- the\n // handoff step is deliberately unframed, since the partner's embed brings its own chrome -- so\n // suppressing form-wide would leave that step identifying itself with neither banner nor tab.\n const activeStepHandsOff = isFormStepExternalWidget(form.steps[step]);\n const activeStepFramed = !activeStepHandsOff;\n const partnerTabReplacesLabelHeader =\n !!framing?.tabLabel && !!form.labelHeader && activeStepFramed;\n\n // The handoff step wears the partner's chrome and none of ours. `form.header` only names\n // OUR steps, so there is no entry for this one and the label header rendered\n // `.empty_step_header`: a 42px bar in the header colour with nothing written in it, sitting\n // directly above the partner's own card. The tab is already off here (the step is unframed),\n // so suppressing the banner leaves the step with no heading of ours at all, which is the\n // point -- their embed introduces itself.\n // Not gated on `framing`. It was, and then the CostGuide preset dropped its framing, which\n // silently switched this whole behaviour back off -- the empty banner and our border returned\n // to the handoff step with every test still green. A handoff step wears the partner's chrome\n // whether or not a preset is drawing any of ours.\n const bareHandoff = activeStepHandsOff;\n const hideLabelHeader = partnerTabReplacesLabelHeader || bareHandoff;\n\n return (\n // The marker, not a class: .xapp_search_response_part reserves space for the header with\n // a hand-written margin, and that margin cannot see whether the header was rendered.\n // FormDisplay is what decides, so it says so here and the ancestor collapses off it.\n //\n // `data-xapp-bare-handoff` is read the same way, by the widget root, to drop its border,\n // radius and shadow for this step -- our box around their box reads as a mistake.\n <div\n {...(hideLabelHeader ? { \"data-xapp-header-suppressed\": \"\" } : {})}\n {...(bareHandoff ? { \"data-xapp-bare-handoff\": \"\" } : {})}\n >\n {form.header.length > 0 && !hideLabelHeader && (\n <div\n className={\n !!isShowCase\n ? styles.xapp_header_container_showcase\n : styles.xapp_header_container\n }\n >\n <SimpleNavigationHeader\n items={form.header}\n onHeaderClick={onHeaderClick}\n labelHeader={form.labelHeader}\n stepName={form.steps[step].name}\n isShowCase={isShowCase}\n />\n </div>\n )}\n <div>\n {form.steps.map((formStep, index) => {\n const override = stepOverrides[formStep.name];\n let effectiveStep = formStep;\n if (override?.fields) {\n effectiveStep = {\n ...effectiveStep,\n fields: override.fields as typeof formStep.fields,\n };\n }\n if (override?.externalWidget?.config) {\n const staticExternalWidget = (\n formStep as unknown as { externalWidget?: ExternalWidgetConfig }\n ).externalWidget;\n if (staticExternalWidget) {\n effectiveStep = {\n ...effectiveStep,\n externalWidget: {\n ...staticExternalWidget,\n config: {\n ...staticExternalWidget.config,\n ...override.externalWidget.config,\n },\n },\n } as FormStep;\n }\n }\n const isActive = form.steps[step].name === formStep.name;\n // The frame goes around the steps we render ourselves. A booking\n // handoff step is the partner's own embed and brings its own\n // frame, so it renders unframed. That is a property of the step,\n // not a piece of state, so crossing into the handoff turns the\n // frame off without remounting anything.\n const framed = !isFormStepExternalWidget(effectiveStep);\n const stepDisplay = (\n <FormStepDisplay\n formStep={effectiveStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onData={handleData}\n onDataWithLabels={handleDataWithLabels}\n onNextStep={step < form.steps.length ? nextStep : undefined}\n onPrevStep={step > 0 ? prevStep : undefined}\n getData={getData}\n getDataWithLabels={getDataWithLabels}\n loading={loading}\n currentStepIndex={index}\n totalSteps={form.steps.length}\n onTrackNextStep={onTrackNextStep}\n currentStepDataRef={currentStepDataRef}\n isActive={isActive}\n // Hold the partner script until the submit's values are merged in.\n externalWidgetConfigPending={\n awaitingHandoffConfig &&\n isFormStepExternalWidget(formStep) &&\n !override?.externalWidget?.config &&\n !externalWidgetWaitElapsed\n }\n onTrackHandoffRendered={onTrackHandoffRendered}\n onTrackHandoffNoRender={onTrackHandoffNoRender}\n onTrackHandoffScheduled={onTrackHandoffScheduled}\n onTrackHandoffError={onTrackHandoffError}\n onExternalWidgetFallback={jumpToExternalWidgetFallback}\n // Only when the frame is actually drawing an intro of its own.\n // The frame no longer borrows the step's title, so hiding the\n // step's intro unconditionally would drop the heading entirely.\n // Suppressed when the frame draws its own intro, and always on a\n // partner-embed step: the embed opens with its own heading, so ours\n // is a second one for the same thing. #1659 narrowed this from \"any\n // framed form\" and switched the handoff step's title back on.\n hideIntro={\n !!framing?.introTitle ||\n !!framing?.introSubtitle ||\n isFormStepExternalWidget(effectiveStep)\n }\n submitError={\n failedSubmitStep === index ? SUBMIT_ERROR_MESSAGE : undefined\n }\n />\n );\n return (\n <div\n key={index}\n className={`${styles.xapp_formstep} ${isActive ? styles.active : \"\"}`}\n data-xapp-form-step-active={isActive ? \"true\" : \"false\"}\n >\n {framing ? (\n <FormFrame framing={framing} framed={framed}>\n {stepDisplay}\n </FormFrame>\n ) : (\n stepDisplay\n )}\n </div>\n );\n })}\n </div>\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { Display } from \"stentor-models\";\nimport { isCarousel, isForm, isList } from \"../../utils/guards\";\nimport { SearchResponseCarouselDisplay } from \"../SearchResponseCarouselDisplay\";\nimport { SearchResponseListDisplay } from \"../SearchResponseListDisplay\";\nimport { FormDisplay } from \"../FormDisplay\";\nimport { FormNextData, FormStepUpdateDisplay } from \"../FormDisplay/model\";\n\nexport interface ResponseDisplayProps {\n readonly display: Display;\n readonly loading: boolean;\n onActionResponse(data: unknown, action: string): void;\n onTrackNextStep?: (stepName: string, stepIndex: number, stepData: Record<string, unknown>, isLastStep: boolean) => void;\n onTrackPreviousStep?: (fromStepName: string, fromStepIndex: number, toStepName: string, toStepIndex: number) => void;\n onTrackSubmit?: (stepName: string, stepIndex: number, completedData: Record<string, unknown>, totalSteps: number) => void;\n /**\n * Callback to track a FORM_SUBMIT dispatch that failed outright (issue #1373).\n */\n onTrackSubmitFailure?: (stepName: string, stepIndex: number, totalSteps: number, reason: string) => void;\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /** Zero-based step to open the form on, instead of the first. */\n readonly initialStep?: number;\n /** Open the date/time step on the soonest day that has times. */\n readonly preselectFirstAvailableDate?: boolean;\n /** Fired with the step index when initialStep is applied. */\n onTrackInitialStep?: (stepIndex: number) => void;\n onFormNext?: (data: FormNextData) => Promise<unknown>;\n stepUpdate?: FormStepUpdateDisplay;\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n}\n\n// TODO: Rename this to ResponseDisplay\nexport const ResponseDisplay: FC<ResponseDisplayProps> = (props) => {\n const {\n display,\n onActionResponse,\n loading,\n onTrackNextStep,\n onTrackPreviousStep,\n onTrackSubmit,\n onTrackSubmitFailure,\n currentStepDataRef,\n initialStep,\n preselectFirstAvailableDate,\n onTrackInitialStep,\n onFormNext,\n stepUpdate,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n } = props;\n\n // TODO: Do we need these others? isList and isCarousel?\n return (\n <div className=\"xapp-search-response-display\">\n {isForm(display) && (\n <FormDisplay\n form={display}\n loading={loading}\n onActionResponse={onActionResponse}\n onTrackNextStep={onTrackNextStep}\n onTrackPreviousStep={onTrackPreviousStep}\n onTrackSubmit={onTrackSubmit}\n onTrackSubmitFailure={onTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={onTrackInitialStep}\n onFormNext={onFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={onTrackHandoffRendered}\n onTrackHandoffNoRender={onTrackHandoffNoRender}\n onTrackHandoffScheduled={onTrackHandoffScheduled}\n onTrackHandoffError={onTrackHandoffError}\n />\n )}\n {isList(display) && <SearchResponseListDisplay list={display} />}\n {isCarousel(display) && <SearchResponseCarouselDisplay carousel={display} />}\n </div>\n );\n};\n","import React, { FC } from \"react\";\n\nexport interface SearchResponseHtmlProps {\n readonly html: string;\n}\n\nexport const SearchResponseHtml: FC<SearchResponseHtmlProps> = props => {\n const { html } = props;\n return (\n <div\n className=\"xapp-search-response-html\"\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n};","import React, { FC } from \"react\";\n\nexport interface SearchResponseTextProps {\n readonly text: string;\n}\n\nexport const SearchResponseText: FC<SearchResponseTextProps> = props => {\n const { text } = props;\n return (\n <div className=\"xapp-search-response-text\">\n <p>\n {text}\n </p>\n </div>\n );\n};","import React, { FC, useEffect, useRef } from \"react\";\n\nimport { log } from \"../../utils\";\n\nexport interface SearchResponseAudioProps {\n readonly audio: string;\n onAudioChange(isOn: boolean): void;\n}\n\nexport const SearchResponseAudio: FC<SearchResponseAudioProps> = props => {\n const { audio, onAudioChange } = props;\n\n const audioRef = useRef(null);\n\n useEffect(() => {\n const audioElement = audioRef.current as unknown as HTMLAudioElement;\n \n const handleAudioEnd = () => {\n log(\"Audio finished playing\");\n onAudioChange(false);\n };\n \n const handleAudioPlay = () => {\n log(\"Audio started playing\");\n onAudioChange(true);\n };\n \n if (audioElement) {\n audioElement.addEventListener(\"ended\", handleAudioEnd);\n audioElement.addEventListener(\"play\", handleAudioPlay);\n }\n\n return () => {\n if (audioElement) {\n audioElement.removeEventListener(\"ended\", handleAudioEnd);\n audioElement.removeEventListener(\"play\", handleAudioPlay);\n }\n };\n }, [audio, onAudioChange]);\n\n return (\n <audio ref={audioRef} autoPlay={true} src={audio} />\n );\n};","import React, { FC, useContext } from \"react\";\nimport { ResponseOutput } from \"stentor-models\";\nimport { SearchResponseHtml } from \"../SearchResponseHtml\";\nimport { SearchResponseText } from \"../SearchResponseText\";\nimport { SearchResponseAudio } from \"../SearchResponseAudio\";\nimport styles from \"./SearchResponseOutputSpeech.module.scss\";\nimport { parseAudio } from \"../../utils/parseAudio\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\n\nexport interface SearchResponseOutputSpeechProps {\n readonly outputSpeech: ResponseOutput | string;\n onAudioChange(isOn: boolean): void;\n}\n\nexport const SearchResponseOutputSpeech: FC<SearchResponseOutputSpeechProps> = props => {\n const { outputSpeech, onAudioChange } = props;\n \n const text = typeof outputSpeech === \"string\" ? outputSpeech : outputSpeech?.displayText;\n const html = typeof outputSpeech === \"string\" ? undefined : outputSpeech?.html;\n const ssml = typeof outputSpeech === \"string\" ? undefined : outputSpeech?.ssml;\n\n const config = useContext(SearchWidgetConfigContext);\n\n // play the firts audio if present\n let audioUrl: string | undefined;\n\n if (!!config.isVoiceEnabled) {\n const mp3s = ssml ? parseAudio(ssml) : [];\n audioUrl = mp3s.length > 0 ? mp3s[0] : undefined;\n }\n\n return (\n <div\n className={styles.xapp_search_response_output_speech}>\n {!!html && <SearchResponseHtml html={html} />}\n {!!text && !html && <SearchResponseText text={text} />}\n {!!audioUrl && <SearchResponseAudio audio={audioUrl} onAudioChange={onAudioChange} />}\n </div>\n );\n}\n","export function parseAudio(ssml: string): string[] {\n const regex = /<audio\\s+src\\s*=\\s*\"(.+?)\"\\s*\\/?>/g;\n const matches: string[] = [];\n let match: string[] | null;\n\n while ((match = regex.exec(ssml)) !== null) {\n matches.push(match[1]);\n }\n\n return matches;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isLinkoutSuggestion = isLinkoutSuggestion;\n/**\n * Determines if the suggestion is a LinkOutSuggestion\n *\n * @param {(LinkOutSuggestion | Suggestion)} suggestion\n * @returns {suggestion is LinkOutSuggestion}\n */\nfunction isLinkoutSuggestion(suggestion) {\n if (!suggestion) {\n return false;\n }\n return suggestion.url !== undefined;\n}\n//# sourceMappingURL=isLinkoutSuggestion.js.map","import React, { FC, PropsWithChildren } from \"react\";\nimport styles from \"./Button.module.scss\";\n\nexport interface ButtonProps {\n readonly className?: string;\n readonly expand?: boolean;\n onClick(): void;\n}\n\nexport const Button: FC<PropsWithChildren<ButtonProps>> = props => {\n const { className, expand, onClick } = props;\n return (\n <button\n type=\"button\"\n className={`${styles.xapp_search_btn} ${expand ? styles['xapp_search_btn__expand'] : \"\"} ${className || \"\"}`}\n onClick={onClick}\n >{props.children}</button>\n );\n};","import React, { FC, useCallback } from \"react\";\nimport { isLinkoutSuggestion } from \"stentor-guards/lib/isLinkoutSuggestion\";\nimport { SuggestionTypes } from \"stentor-models\";\nimport { getActionLabel } from \"../../utils/getActionLabel\";\nimport { Button } from \"../Button\";\nimport styles from \"./SuggestedAction.module.scss\";\n\nexport interface SuggestedActionProps {\n readonly action: SuggestionTypes;\n onClick(action: SuggestionTypes): void;\n readonly className?: string;\n}\n\nexport const SuggestedAction: FC<SuggestedActionProps> = props => {\n const { action, className, onClick } = props;\n\n const handleClick = useCallback(() => {\n onClick(action);\n }, [action, onClick])\n\n if (isLinkoutSuggestion(action)) {\n return (\n <span className={`${styles.xapp_search_suggested_action} ${className || \"\"}`}>\n <a href={action.url}>{getActionLabel(action)}</a>\n </span>\n );\n } else {\n return (\n <Button\n className={`${styles.xapp_search_suggested_action} ${className || \"\"}`}\n onClick={handleClick}\n > {getActionLabel(action)}</Button >\n );\n }\n}","import React, { FC } from \"react\";\nimport { SuggestionTypes } from \"stentor-models\";\nimport { SuggestedAction } from \"../SuggestedAction\";\nimport styles from \"./SuggestedActions.module.scss\";\n\n\nexport interface SuggestedActionsProps {\n readonly actions: readonly SuggestionTypes[];\n onActionClick(action: SuggestionTypes): void;\n}\n\nexport const SuggestedActions: FC<SuggestedActionsProps> = props => {\n const { actions, onActionClick } = props;\n return (\n <div className={styles.xapp_search_suggested_actions}>\n <div className={styles.xapp_search_suggested_actions__actions}>\n {actions.map((act, index) => (\n <SuggestedAction\n key={index}\n action={act}\n className={styles.xapp_search_suggested_actions__item}\n onClick={onActionClick}\n />))}\n </div>\n </div>\n );\n};","import React, { FC, PropsWithChildren } from \"react\";\n\nimport styles from \"./SearchResponsePart.module.scss\";\n\nexport interface SearchResponsePartProps {\n extraClass?: string;\n}\n\nexport const SearchResponsePart: FC<PropsWithChildren<SearchResponsePartProps>> = (props) => {\n const { extraClass } = props;\n\n // A modifier names a rule in THIS module (`&.noHeaderForm`), and the build hashes module\n // classes -- so it has to be looked up, not passed through. Applied as the bare string it\n // never matched, and a form with no header kept the 86px reserved for one as a blank band.\n // An unknown name still passes through as-is, so a genuinely global class keeps working.\n const modifier = extraClass\n ? (styles as Record<string, string | undefined>)[extraClass] || extraClass\n : \"\";\n\n return (\n <div className={`${styles.xapp_search_response_part} ${modifier}`}>\n {props.children}\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport { Response, SuggestionTypes } from \"stentor-models\";\n\nimport { SearchResponseBubble } from \"../SearchResponseBubble\";\nimport { SearchResponseDisplay } from \"../ResponseDisplay\";\nimport { SearchResponseOutputSpeech } from \"../SearchResponseOutputSpeech\";\nimport { SuggestedActions } from \"../SuggestedActions\";\nimport { isForm } from \"../../utils/guards\";\nimport { FormNextData, FormStepUpdateDisplay } from \"../FormDisplay/model\";\n\nimport { SearchResponsePart } from \"./SearchResponsePart\";\n\nimport styles from \"./FormResponse.module.scss\";\n\nexport interface FormResponseProps {\n readonly response: Response;\n readonly className?: string;\n readonly loading: boolean;\n onActionClick(action: SuggestionTypes): void;\n onActionResponse(data: unknown, action: string): void;\n onAudioChange(isOn: boolean): void;\n onTrackNextStep?: (stepName: string, stepIndex: number, stepData: Record<string, unknown>, isLastStep: boolean) => void;\n onTrackPreviousStep?: (fromStepName: string, fromStepIndex: number, toStepName: string, toStepIndex: number) => void;\n onTrackSubmit?: (stepName: string, stepIndex: number, completedData: Record<string, unknown>, totalSteps: number) => void;\n /**\n * Callback to track a FORM_SUBMIT dispatch that failed outright (issue #1373).\n */\n onTrackSubmitFailure?: (stepName: string, stepIndex: number, totalSteps: number, reason: string) => void;\n currentStepDataRef?: React.MutableRefObject<Record<string, unknown>>;\n /** Zero-based step to open the form on, instead of the first. */\n readonly initialStep?: number;\n /** Open the date/time step on the soonest day that has times. */\n readonly preselectFirstAvailableDate?: boolean;\n /** Fired with the step index when initialStep is applied. */\n onTrackInitialStep?: (stepIndex: number) => void;\n onFormNext?: (data: FormNextData) => Promise<unknown>;\n stepUpdate?: FormStepUpdateDisplay;\n onTrackHandoffRendered?: (stepName: string, provider: string) => void;\n onTrackHandoffNoRender?: (stepName: string, provider: string) => void;\n onTrackHandoffScheduled?: (stepName: string, provider: string, payload?: unknown) => void;\n onTrackHandoffError?: (stepName: string, provider: string) => void;\n}\n\n/**\n * FormResponse displays the data from the handler\n */\nexport const FormResponse: FC<FormResponseProps> = (props) => {\n const {\n response,\n className,\n onActionClick,\n onActionResponse,\n onAudioChange,\n loading,\n onTrackNextStep,\n onTrackPreviousStep,\n onTrackSubmit,\n onTrackSubmitFailure,\n currentStepDataRef,\n initialStep,\n preselectFirstAvailableDate,\n onTrackInitialStep,\n onFormNext,\n stepUpdate,\n onTrackHandoffRendered,\n onTrackHandoffNoRender,\n onTrackHandoffScheduled,\n onTrackHandoffError,\n } = props;\n\n const { outputSpeech, displays } = response;\n const actions = typeof outputSpeech === \"object\" ? outputSpeech.suggestions : undefined;\n\n return (\n <div className={`${styles.xapp_search_response} ${className || \"\"}`}>\n {!!outputSpeech && (\n <SearchResponsePart>\n <SearchResponseBubble>\n <SearchResponseOutputSpeech\n outputSpeech={outputSpeech}\n onAudioChange={onAudioChange}\n />\n </SearchResponseBubble>\n </SearchResponsePart>\n )}\n\n {!!actions?.length && actions?.length > 0 && (\n <SuggestedActions actions={actions} onActionClick={onActionClick} />\n )}\n\n {!!displays?.length &&\n displays?.length > 0 &&\n displays.map((display, index) => {\n const noHeaderForm: boolean =\n isForm(display) && (!display.header || display.header.length === 0);\n\n return (\n <SearchResponsePart\n key={index}\n extraClass={noHeaderForm ? \"noHeaderForm\" : \"\"}>\n <SearchResponseDisplay\n display={display}\n onActionResponse={onActionResponse}\n loading={loading}\n onTrackNextStep={onTrackNextStep}\n onTrackPreviousStep={onTrackPreviousStep}\n onTrackSubmit={onTrackSubmit}\n onTrackSubmitFailure={onTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={onTrackInitialStep}\n onFormNext={onFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={onTrackHandoffRendered}\n onTrackHandoffNoRender={onTrackHandoffNoRender}\n onTrackHandoffScheduled={onTrackHandoffScheduled}\n onTrackHandoffError={onTrackHandoffError}\n />\n </SearchResponsePart>\n );\n })}\n </div>\n );\n};\n","/**\n * Service for tracking form widget interaction events\n *\n * API Endpoint: POST /cms/widget/events\n * @see https://github.com/XappMedia/chat-widget/blob/master/docs/widget-events-api.md\n */\n\nimport { readInternalTrafficMark, stripQueryString, visitIdentity } from \"@xapp/chat-widget-core\";\nimport { StentorApi } from \"../api/stentor-api\";\nimport {\n WidgetEventMetadata,\n WidgetEvent,\n FormOpenEventData,\n EngagedEventData,\n NextStepEventData,\n PreviousStepEventData,\n StepChangeEventData,\n SubmitEventData,\n SubmitFailureEventData,\n CloseEventData,\n PartialDataEventData,\n HandoffRenderedEventData,\n HandoffNoRenderEventData,\n HandoffScheduledEventData,\n HandoffErrorEventData,\n} from \"../types/events\";\nimport { log, err } from \"../utils\";\nimport { getStoredTrackingParameters } from \"../utils/tracking\";\n\n/**\n * Service for tracking form widget interaction events.\n * This service provides methods to track user interactions with the form widget\n * without blocking the user experience (all tracking is async and errors are logged).\n *\n * Events are sent to POST /cms/widget/events and stored in OpenSearch as:\n * - load -> eventName: \"WIDGET_FORM_LOAD\"\n * - form_open -> eventName: \"WIDGET_FORM_OPEN\"\n * - engaged -> eventName: \"WIDGET_FORM_ENGAGED\"\n * - next_step -> eventName: \"WIDGET_FORM_STEP\"\n * - previous_step -> eventName: \"WIDGET_FORM_PREV_STEP\"\n * - step_change -> eventName: \"WIDGET_FORM_STEP_CHANGE\"\n * - submit -> eventName: \"WIDGET_FORM_SUBMIT\"\n * - close -> eventName: \"WIDGET_FORM_CLOSE\"\n * - partial_data -> eventName: \"WIDGET_FORM_ABANDON\"\n * - handoff_rendered -> eventName: \"WIDGET_FORM_HANDOFF_RENDERED\"\n * - handoff_no_render -> eventName: \"WIDGET_FORM_HANDOFF_NO_RENDER\"\n * - handoff_scheduled -> eventName: \"WIDGET_FORM_HANDOFF_SCHEDULED\"\n * - handoff_error -> eventName: \"WIDGET_FORM_HANDOFF_ERROR\"\n */\n/**\n * Input that counts as a visitor touching the page. Deliberately broad and document-level: the\n * point is to tell a person from a scripted browser, and a script that drives the form through the\n * DOM produces none of these - as long as only real gestures count, which is why the listener\n * below checks isTrusted. Browsers set that flag only on genuine user input; anything a script\n * dispatches is untrusted and cannot set it.\n */\nconst INTERACTION_EVENTS = [\"pointerdown\", \"keydown\", \"scroll\", \"touchstart\"];\n\nexport class EventTrackingService {\n private api: StentorApi;\n private sessionId: string;\n private formId: string;\n /** When the form opened, so every later event can report how long the visit has lasted. */\n private openedAt?: number;\n /** When the visitor first touched anything. Stays undefined when nobody ever did. */\n private firstInteractionAt?: number;\n private stopWatchingForInteraction?: () => void;\n\n constructor(api: StentorApi, sessionId: string, formId: string) {\n this.api = api;\n this.sessionId = sessionId;\n this.formId = formId;\n }\n\n /**\n * A tracker on the visit's session (started now if the form hasn't sent anything yet), so\n * events sent before the first request - the load - carry the session the visit's open and\n * submit events will.\n */\n public static forVisit(api: StentorApi, formId: string): EventTrackingService {\n return new EventTrackingService(api, api.visitSession().sessionId, formId);\n }\n\n /**\n * Track a form_open event when the form widget is first displayed\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_OPEN\"\n */\n public async trackFormOpen(data: FormOpenEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata({ isOpen: true });\n this.watchForFirstInteraction();\n const event: WidgetEvent = {\n eventType: \"form_open\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] form_open event tracked: ${data.formName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track form_open event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track an engaged event the first time a user takes a genuine action on\n * the form (manual open, chip click, or first step transition).\n * Additive to form_open - does not replace it. Callers are responsible\n * for only calling this once per session.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_ENGAGED\"\n */\n public async trackEngaged(data: EngagedEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"engaged\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] engaged event tracked: ${data.formName} (${data.trigger})`);\n } catch (error) {\n err(`[EventTracking] Failed to track engaged event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a next_step event when user navigates to the next form step\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_STEP\"\n */\n public async trackNextStep(data: NextStepEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"next_step\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] next_step event tracked: ${data.completedStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track next_step event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a previous_step event when user navigates back to a previous step\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_PREV_STEP\"\n */\n public async trackPreviousStep(data: PreviousStepEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"previous_step\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(\n `[EventTracking] previous_step event tracked: ${data.fromStepName} -> ${data.toStepName}`\n );\n } catch (error) {\n err(`[EventTracking] Failed to track previous_step event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a step_change event for any step navigation (forward or backward)\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_STEP_CHANGE\"\n */\n public async trackStepChange(data: StepChangeEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"step_change\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(\n `[EventTracking] step_change event tracked: ${data.fromStepName} -> ${data.toStepName} (${data.direction})`\n );\n } catch (error) {\n err(`[EventTracking] Failed to track step_change event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a submit event when user submits the final form\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_SUBMIT\"\n */\n public async trackSubmit(data: SubmitEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"submit\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] submit event tracked: ${data.finalStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track submit event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a submit that failed to reach the server, after retries.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_SUBMIT_FAILURE\"\n *\n * trackSubmit above fires on this endpoint *before* the FORM_SUBMIT dispatch that\n * actually creates the lead, so a submit event alone never proved a lead existed.\n * This is its counter-signal: submit events minus submit_failure events is the\n * number of submissions that were genuinely dispatched (issue #1373).\n */\n public async trackSubmitFailure(data: SubmitFailureEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"submit_failure\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] submit_failure event tracked: ${data.finalStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track submit_failure event: ${error}`);\n // Don't throw - the user is already being shown the failure.\n }\n }\n\n /**\n * Track a close event when user explicitly closes the form widget\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_CLOSE\"\n */\n public async trackClose(data: CloseEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"close\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] close event tracked: ${data.lastStepName}`);\n } catch (error) {\n err(`[EventTracking] Failed to track close event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a partial_data event when user abandons form (tab close or timeout)\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_ABANDON\"\n *\n * @param data - Event data including abandonmentReason (\"close_tab\" | \"timeout\")\n */\n public async trackPartialData(data: PartialDataEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"partial_data\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(\n `[EventTracking] partial_data event tracked: ${data.lastStepName} (${data.abandonmentReason})`\n );\n } catch (error) {\n err(`[EventTracking] Failed to track partial_data event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_rendered event when a booking-widget handoff step's anchor\n * gains content within its render timeout.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_RENDERED\"\n */\n public async trackHandoffRendered(data: HandoffRenderedEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_rendered\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(\n `[EventTracking] handoff_rendered event tracked: ${data.stepName} (${data.provider})`\n );\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_rendered event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_no_render event when a booking-widget handoff step's render\n * timeout elapses with an empty anchor.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_NO_RENDER\"\n */\n public async trackHandoffNoRender(data: HandoffNoRenderEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_no_render\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(\n `[EventTracking] handoff_no_render event tracked: ${data.stepName} (${data.provider})`\n );\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_no_render event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_scheduled event when the partner script invokes the\n * configured success callback. This is how the booking outcome reaches\n * stentor_events -- joinable on sessionId with the lead.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_SCHEDULED\"\n */\n public async trackHandoffScheduled(data: HandoffScheduledEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_scheduled\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(\n `[EventTracking] handoff_scheduled event tracked: ${data.stepName} (${data.provider})`\n );\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_scheduled event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a handoff_error event when a booking-widget handoff step's partner\n * script fails to load, or its scriptSrc is rejected.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_HANDOFF_ERROR\"\n */\n public async trackHandoffError(data: HandoffErrorEventData): Promise<void> {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"handoff_error\",\n metadata,\n data,\n };\n\n await this.sendEvent(event);\n log(`[EventTracking] handoff_error event tracked: ${data.stepName} (${data.provider})`);\n } catch (error) {\n err(`[EventTracking] Failed to track handoff_error event: ${error}`);\n // Don't throw - we don't want to block the user flow\n }\n }\n\n /**\n * Track a load event: the widget loaded on a page. Sent once per page load (the caller\n * guards that), keepalive and fire-and-forget, so it never blocks rendering.\n * Stored as: eventType: \"AnalyticsEvent\", eventName: \"WIDGET_FORM_LOAD\"\n *\n * @param loadMetadata - page, browser and agent fields from chat-widget-core's\n * buildLoadEventMetadata. They win over the stored attribution: they describe this page.\n * @returns true if the request was queued\n */\n public trackLoad(loadMetadata: Record<string, string>): boolean {\n try {\n const metadata = this.buildMetadata();\n // buildMetadata reports the full href; a load event sends only what\n // buildLoadEventMetadata allowed through, never the raw query string.\n delete metadata.currentUrl;\n const event: WidgetEvent = {\n eventType: \"load\",\n metadata: { ...metadata, ...loadMetadata },\n data: {},\n };\n\n return this.api.trackEventBeacon(event, \"form\");\n } catch (error) {\n err(`[EventTracking] Failed to queue load event: ${error}`);\n return false;\n }\n }\n\n /**\n * Track a partial_data event using beacon/keepalive for page unload scenarios.\n * Use this when the page is being unloaded and you need reliable delivery.\n *\n * @param data - Event data including abandonmentReason (\"close_tab\" | \"timeout\")\n * @returns true if the beacon was queued, false otherwise\n */\n public trackPartialDataBeacon(data: PartialDataEventData): boolean {\n try {\n const metadata = this.buildMetadata();\n const event: WidgetEvent = {\n eventType: \"partial_data\",\n metadata,\n data,\n };\n\n return this.api.trackEventBeacon(event);\n } catch (error) {\n err(`[EventTracking] Failed to queue partial_data beacon: ${error}`);\n return false;\n }\n }\n\n /**\n * Build event metadata from current context.\n *\n * Each optional enrichment (currentUrl, UTM/click-id params) is isolated in its\n * own try/catch. localStorage access in particular can throw synchronously - not just\n * return null - in Safari ITP, a sandboxed iframe without allow-same-origin, or under an\n * enterprise storage policy. Without isolation, one such throw used to take down metadata\n * building entirely, silently dropping the event (including userAgent/currentUrl, which\n * don't depend on storage) via the try/catch in trackFormOpen et al. See issue #1504.\n */\n private buildMetadata({ isOpen = false } = {}): WidgetEventMetadata {\n const now = new Date();\n const nowMs = Date.now();\n if (isOpen && this.openedAt === undefined) {\n this.openedAt = nowMs;\n }\n const metadata: WidgetEventMetadata = {\n timestamp: now.toISOString(),\n sessionId: this.sessionId || \"unknown\",\n formId: this.formId || \"unknown\",\n userAgent: navigator.userAgent,\n };\n\n // Our own crawler, so its funnel events don't read as an AI agent's.\n const internal = readInternalTrafficMark();\n if (internal) {\n metadata.internal = internal;\n }\n\n // How long the visit has lasted, and how long it took the visitor to touch anything.\n // Both are omitted rather than zeroed when unknown: a 0 would read as a real measurement\n // of an instant bounce, which is exactly what these are used to judge.\n if (this.openedAt !== undefined) {\n metadata.msOnPage = String(Math.max(0, nowMs - this.openedAt));\n if (this.firstInteractionAt !== undefined) {\n metadata.msToFirstInteraction = String(\n Math.max(0, this.firstInteractionAt - this.openedAt)\n );\n }\n }\n\n // Environment. Isolated like every other enrichment below - a browser that throws here\n // must still produce an event, not a silent drop (issue #1504).\n try {\n metadata.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch (e) {\n // Intl unavailable or throwing - skip timezone\n }\n\n try {\n metadata.language = navigator.language;\n // Screen against viewport: a real browser puts its own chrome between the two, so a\n // viewport exactly the size of the screen is a headless default.\n metadata.screenWidth = String(window.screen.width);\n metadata.screenHeight = String(window.screen.height);\n metadata.viewportWidth = String(window.innerWidth);\n metadata.viewportHeight = String(window.innerHeight);\n } catch (e) {\n // Screen/navigator unavailable (sandboxed frame) - skip the environment fields\n }\n\n // Who and which visit, shared with the chat widget on the page. The visitor id is also the\n // form's user id. Sending an event is what keeps the visit alive. Never throws.\n const { visitorId, visitId } = visitIdentity();\n metadata.userId = visitorId;\n metadata.visitorId = visitorId;\n metadata.visitId = visitId;\n\n // Add current URL (exclude localhost for privacy)\n try {\n const href = new URL(window.location.href);\n if (!href?.host.toLowerCase().startsWith(\"localhost\")) {\n metadata.currentUrl = window.location.href;\n }\n } catch (e) {\n // If URL parsing fails, skip currentUrl\n }\n\n // The page the visitor came from. The booking page never fires a load event, so form\n // events are the only place its referrer is recorded. Query string dropped: it can\n // carry PII.\n try {\n const referrer = stripQueryString(document.referrer);\n if (referrer) {\n metadata.referrer = referrer;\n }\n } catch (e) {\n // document unavailable - skip referrer\n }\n\n // Add tracking parameters from localStorage\n try {\n const trackingParams = this.getTrackingParameters();\n Object.assign(metadata, trackingParams);\n } catch (e) {\n // localStorage unavailable - skip UTM/click-id params\n }\n\n return metadata;\n }\n\n /**\n * Releases anything this tracker is holding on the page.\n *\n * The interaction listeners otherwise live until a trusted gesture fires one of them, which\n * may never happen: FormWidget's embedded mode mounts and unmounts inside a host app, and a\n * widget unmounted before anyone touches it would leave four document listeners - and the\n * closures behind them - accumulating on the page.\n */\n public dispose(): void {\n this.stopWatchingForInteraction?.();\n }\n\n /**\n * Carries a visit's timing onto a replacement tracker.\n *\n * FormWidget builds a new EventTrackingService every time an intentRequest resolves to a FORM\n * display, and that happens again mid-visit on a chip click. form_open fires only once per\n * mounted widget, so the replacement never calls trackFormOpen and would never learn when the\n * visit began - every later event would silently report no dwell and no interaction, for\n * exactly the multi-step flow these fields exist to measure.\n *\n * The previous tracker's listener is torn down and a fresh one armed here, so a gesture that\n * arrives after the handover still lands on the tracker actually sending events.\n */\n public adoptVisitFrom(previous?: EventTrackingService | null): void {\n if (!previous || previous === this || previous.openedAt === undefined) {\n return;\n }\n\n this.openedAt = previous.openedAt;\n this.firstInteractionAt = previous.firstInteractionAt;\n\n previous.stopWatchingForInteraction?.();\n if (this.firstInteractionAt === undefined) {\n this.watchForFirstInteraction();\n }\n }\n\n /**\n * Records when the visitor first touches the page, then stops listening.\n *\n * Listeners are passive and one-shot, so this costs nothing after the first input and cannot\n * interfere with scrolling. Absence is the signal that matters: a scripted browser drives the\n * form through the DOM and never fires any of these.\n */\n private watchForFirstInteraction(): void {\n if (this.stopWatchingForInteraction || this.firstInteractionAt !== undefined) {\n return;\n }\n if (typeof document === \"undefined\") {\n return;\n }\n\n try {\n const onInteraction = (event: Event): void => {\n // A script can dispatch pointerdown as easily as we can listen for it, so an\n // untrusted event proves nothing. Ignored without tearing the listener down, or\n // one synthetic event would also destroy the real signal that follows it.\n if (!event.isTrusted) {\n return;\n }\n if (this.firstInteractionAt === undefined) {\n this.firstInteractionAt = Date.now();\n }\n this.stopWatchingForInteraction?.();\n };\n\n this.stopWatchingForInteraction = (): void => {\n for (const name of INTERACTION_EVENTS) {\n document.removeEventListener(name, onInteraction, true);\n }\n this.stopWatchingForInteraction = undefined;\n };\n\n for (const name of INTERACTION_EVENTS) {\n document.addEventListener(name, onInteraction, { capture: true, passive: true });\n }\n } catch (e) {\n // Listener registration unavailable - the fields simply stay absent\n }\n }\n\n /**\n * Get this form's tracking parameters from localStorage\n */\n private getTrackingParameters(): Record<string, string> {\n return getStoredTrackingParameters(this.api.trackingScope) as Record<string, string>;\n }\n\n /**\n * Send event to backend API\n */\n private async sendEvent(event: WidgetEvent): Promise<void> {\n try {\n await this.api.trackEvent(event.eventType, event);\n } catch (error) {\n // Log error but don't throw - we don't want to block user flow\n err(`[EventTracking] API call failed: ${error}`);\n }\n }\n}\n","import React, { FC, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { uuid } from \"@xapp/chat-widget-core\";\nimport { Response, SuggestionTypes } from \"stentor-models\";\nimport { StentorApi, wasDroppedAfterFinal } from \"../../api\";\nimport { FormWidgetConfig } from \"../../config\";\nimport { useSearchStore } from \"../../store\";\nimport { getActionLabel } from \"../../utils/getActionLabel\";\nimport { log, err } from \"../../utils\";\nimport { getAllTrackingParameters } from \"../../utils/tracking\";\nimport { SearchWidgetConfigContext } from \"../../utils/SearchWidgetConfigContext\";\nimport { useLoading } from \"../../utils/useLoading\";\nimport { useTrustedForm } from \"../../utils/useTrustedForm\";\nimport { getMetaCookies } from \"../../utils/metaCookies\";\nimport { getGa4LeadExtras, sendGa4LeadEvent } from \"../../utils/ga4\";\nimport { SpinnerIcon } from \"../icons\";\nimport { FormResponse } from \"../FormResponse\";\nimport { FormNextData, FormStepUpdateDisplay } from \"../FormDisplay\";\nimport { EventTrackingService } from \"../../services/EventTrackingService\";\nimport { EngagementTrigger } from \"../../types/events\";\n\nimport styles from \"./FormWidget.module.scss\";\n\n/**\n * Interface for form step data in event tracking\n */\ninterface FormStep {\n name?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for FORM display type used in event tracking\n */\ninterface FormDisplay {\n type: \"FORM\";\n steps?: FormStep[];\n [key: string]: unknown;\n}\n\n/**\n * Backoff between FORM_SUBMIT attempts; its length sets the retry count (3 attempts).\n *\n * Only FORM_SUBMIT is retried: it is the request that creates the lead, and losing it\n * loses the lead outright (issue #1373). StentorApi.send already retries once on a\n * non-ok status, but a transport failure -- fetch rejecting, the case where nothing\n * reaches the server at all -- got no retry and no handler.\n *\n * Retrying a lead-creating POST can duplicate it if the request landed but the response\n * did not. `extras.eventId` is minted once per submission and resent unchanged on every\n * attempt (see getSubmitEventId), so the client side already carries a stable\n * idempotency key -- but nothing consumes it on this path yet: contact-capture-handler's\n * FormActionResponseData does not declare `extras` and never reads `attributes.data`, so\n * the id is dropped before the lead is built, and the lead write itself has no dedupe of\n * any kind. Plumbing it through and keying a dedupe on it is tracked separately.\n */\nconst SUBMIT_RETRY_DELAYS_MS = [1000, 2000];\n\nconst wait = (ms: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n\nasync function dispatchWithRetry<T>(attempt: () => Promise<T>, delays: number[]): Promise<T> {\n let lastError: unknown;\n\n for (let i = 0; i <= delays.length; i++) {\n if (i > 0) {\n await wait(delays[i - 1]);\n }\n\n try {\n return await attempt();\n } catch (error) {\n lastError = error;\n err(`FORM_SUBMIT attempt ${i + 1} of ${delays.length + 1} failed: ${error}`);\n }\n }\n\n throw lastError;\n}\n\nexport const AUDIO_WAIT_NOTHING = 0,\n AUDIO_WAIT_CLOSE = 1,\n AUDIO_WAIT_MINIMIZE = 2;\n\nexport interface FormWidgetProps {\n readonly config: FormWidgetConfig;\n /**\n * Optional initial response to display\n */\n readonly response?: Response;\n\n readonly docked?: boolean;\n /**\n * Rendering inside a container the host page provided and sized (see `isEmbedded`).\n *\n * Drops the framing that makes the widget read as a floating card -- the desktop\n * max-width, border, radius and shadow -- so it fills the customer's div instead.\n */\n readonly embedded?: boolean;\n /**\n * Zero-based step to open the form on, instead of the first.\n *\n * For previews that want to show a particular step -- get.xapp.ai's booking\n * preview opens on the date and time step, because the calendar is the part\n * worth showing. Applied once, when the form arrives; an index the form has\n * no step for is ignored.\n */\n readonly initialStep?: number;\n /**\n * Open the date/time step on the soonest day that has times, rather than on\n * \"Select a date to see the available times.\"\n *\n * For a preview that lands straight on that step: an empty column beside a\n * calendar reads as a form with nothing to offer. Off by default -- on a real\n * booking page a preselected date is one the customer never chose.\n */\n readonly preselectFirstAvailableDate?: boolean;\n /**\n * True when the form was activated by a proactive auto-open trigger\n * (delay/scroll%/exit-intent/inactivity) rather than a genuine user\n * action. Used to keep the `engaged` signal limited to real engagement.\n */\n readonly openedByTrigger?: boolean;\n /**\n * Label of a chip to auto-select after the form loads.\n * If the first response contains chips/suggestions, the form will\n * automatically click the chip matching this label.\n */\n readonly preselectChipLabel?: string;\n /**\n * Callback when preselectChipLabel has been used (to clear it)\n */\n readonly onPreselectChipUsed?: () => void;\n /**\n * Callback invoked when the user submits the final form step.\n *\n * Useful for firing external conversion tracking (e.g. a Meta Pixel\n * `Lead` event) from the embedding page. It receives ONLY a non-PII\n * `eventId` — the same id sent to the backend with the lead — so a\n * browser-side pixel event can be deduplicated against the server-side\n * Conversions API event. The submitted payload (which contains PII) is\n * deliberately never exposed to third-party trackers.\n */\n readonly onSubmit?: (eventId?: string) => void;\n}\n\nexport const FormWidget: FC<FormWidgetProps> = (props) => {\n const { config } = props;\n\n return (\n <SearchWidgetConfigContext.Provider value={config}>\n <FormWidgetRaw\n docked={props.docked}\n embedded={props.embedded}\n initialStep={props.initialStep}\n preselectFirstAvailableDate={props.preselectFirstAvailableDate}\n openedByTrigger={props.openedByTrigger}\n preselectChipLabel={props.preselectChipLabel}\n onPreselectChipUsed={props.onPreselectChipUsed}\n onSubmit={props.onSubmit}\n response={props.response}\n />\n </SearchWidgetConfigContext.Provider>\n );\n};\n\nconst FormWidgetRaw: FC<\n Pick<\n FormWidgetProps,\n | \"docked\"\n | \"embedded\"\n | \"initialStep\"\n | \"preselectFirstAvailableDate\"\n | \"openedByTrigger\"\n | \"response\"\n | \"preselectChipLabel\"\n | \"onPreselectChipUsed\"\n | \"onSubmit\"\n >\n> = (props) => {\n const {\n docked,\n embedded,\n initialStep,\n preselectFirstAvailableDate,\n openedByTrigger,\n preselectChipLabel,\n onPreselectChipUsed,\n onSubmit,\n } =\n props;\n\n const [state, dispatch] = useSearchStore();\n const { loading, run } = useLoading();\n\n const { query, sendRequest, active } = state;\n\n const [response, setResponse] = useState<Response | undefined>(props.response);\n\n // A FORM_STEP_UPDATE display pulled out of a (fire-and-forget) FORM_SUBMIT\n // response, e.g. a booking-widget handoff step's externalWidget.config. Each\n // detected update is a fresh object from the API response, so FormDisplay's\n // effect on this prop always fires for a genuine new update.\n const [stepUpdate, setStepUpdate] = useState<FormStepUpdateDisplay | undefined>(undefined);\n\n const [audioOn, setAudioOn] = useState<boolean>(false);\n\n const [waitingOnAudioToFinish, setwaitingOnAudioToFinish] =\n useState<number>(AUDIO_WAIT_NOTHING);\n\n // why don't we just pass it in as a prop?\n const config = useContext(SearchWidgetConfigContext);\n\n // TrustedForm injects a third-party script that begins certifying the\n // session on mount. A preview must not generate a certificate with\n // ActiveProspect for a visit that isn't a real lead, so demo mode withholds\n // the script URL and the hook no-ops.\n const getTrustedFormData = useTrustedForm(\n config.api.demoMode ? undefined : config.trustedForm?.scriptUrl\n );\n\n const api = useMemo(() => {\n return StentorApi.getApi({\n key: config.api.key,\n url: config.api.url,\n intentId: config.intentId,\n // Carried through so the preview guarantee lives in one place.\n demoMode: config.api.demoMode,\n // prefetchQuery: config.autoGreeting\n });\n }, [config]);\n\n // Event tracking service - initialize with session and form info\n const eventTracker = useRef<EventTrackingService | null>(null);\n const formData = useRef<Record<string, unknown>>({});\n // Ref to sync current step's live data (before step completion)\n const currentStepDataRef = useRef<Record<string, unknown>>({});\n const currentStepRef = useRef<number>(0);\n const formSubmittedRef = useRef<boolean>(false);\n // Guards the docked auto-mount request so it fires exactly once per mount. See the effect below.\n // This never resets, which is correct only because `docked` is fixed for a mounted instance\n // (it is derived once in Form.tsx from config.autoOpen and does not toggle). If `docked` ever\n // becomes a runtime-togglable prop, this guard would suppress the legitimate second request and\n // must reset on the docked false->true transition.\n const dockedRequestSent = useRef<boolean>(false);\n\n // One id per submission, shared between the FORM_SUBMIT payload (sent to the\n // backend, which forwards it to Meta's Conversions API) and the browser Pixel\n // `Lead` event via onSubmit — so Meta deduplicates the two. Lazily created so\n // whichever submit handler runs first mints it and the other reuses it.\n const submitEventIdRef = useRef<string | undefined>(undefined);\n const getSubmitEventId = useCallback((): string => {\n const existing = submitEventIdRef.current;\n if (existing) {\n return existing;\n }\n const id = uuid();\n submitEventIdRef.current = id;\n return id;\n }, []);\n\n // Event ids already sent to GA4 from the browser. A resubmit of the same lead must\n // neither send generate_lead again nor drop the ga4ClientFired flag, or the backend\n // would send a second, undeduplicated one.\n const ga4FiredEventIdsRef = useRef<Set<string>>(new Set());\n // Ref to store form display info for event tracking (avoids useEffect dependency on response)\n const formDisplayRef = useRef<FormDisplay | null>(null);\n // Ref to store the current form's id for event tracking (mirrors eventTracker's private formId)\n const formIdRef = useRef<string>(\"unknown\");\n // Flag to prevent race condition where timeout fires after close/submit\n const abandonEventSentRef = useRef<boolean>(false);\n // Fires the `form_open` event at most once per mounted widget instance. Without this guard,\n // any intentRequest that resolves to a FORM display re-fires WIDGET_FORM_OPEN - e.g. a\n // chip click (handleActionClick) routed back through intentRequest after the form already\n // opened once. Each re-fire still carries full tracking metadata, but it inflates the OPEN\n // denominator the bounce/conversion funnel is measured against. See issue #1504.\n const formOpenSentRef = useRef<boolean>(false);\n // Fires the `engaged` event at most once per session (first genuine user action)\n const engagementSentRef = useRef<boolean>(false);\n const trackEngagement = useCallback((trigger: EngagementTrigger) => {\n if (!eventTracker.current || engagementSentRef.current) {\n return;\n }\n engagementSentRef.current = true;\n eventTracker.current.trackEngaged({\n formName: formIdRef.current,\n trigger,\n firstStepName: formDisplayRef.current?.steps?.[0]?.name,\n });\n }, []);\n\n const handleCancel = useCallback(() => {\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: true,\n sendRequest: false,\n });\n }, [dispatch]);\n\n const handleClose = useCallback(() => {\n // Track close and partial_data events if form wasn't submitted and abandon event not already sent.\n // Note: These are intentionally fire-and-forget (not awaited) to avoid blocking the UI.\n // The close event captures the UI action, while partial_data captures abandonment analytics\n // with abandonmentReason for funnel analysis. Both events serve different purposes.\n if (eventTracker.current && !formSubmittedRef.current && !abandonEventSentRef.current) {\n const form = formDisplayRef.current;\n if (form) {\n const totalSteps = form.steps?.length || 1;\n const currentStep = currentStepRef.current;\n // Merge completed step data with current step's live data\n const allFormData = { ...formData.current, ...currentStepDataRef.current };\n const hasData = Object.keys(allFormData).length > 0;\n\n // Send close event (captures the UI close action)\n eventTracker.current.trackClose({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n formData: hasData ? allFormData : undefined,\n });\n\n // Send partial_data event (captures abandonment with reason for funnel analysis)\n eventTracker.current.trackPartialData({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n partialData: hasData ? allFormData : undefined,\n abandonmentReason: \"widget_close\",\n });\n\n abandonEventSentRef.current = true;\n }\n }\n\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: false,\n sendRequest: false,\n });\n api.channelActionRequest({ data: { result: {}, step: \"\", form: \"\" } }, \"FORM_CLOSE\").then(\n (closeResponse) => {\n log(\n `ACTION Request (FORM_CLOSE). Data: Response: ${JSON.stringify(closeResponse)}`\n );\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n }\n );\n }, [api, dispatch]);\n\n // Release the event tracker's document listeners when the widget goes away. Embedded mode\n // mounts and unmounts inside a host app, and a visit nobody interacted with would otherwise\n // leave its interaction listeners behind on every unmount.\n useEffect(() => {\n return () => {\n eventTracker.current?.dispose();\n };\n }, []);\n\n // Extract and store tracking parameters on mount\n // Note: This is safe to run even if tracking params were already extracted\n // (e.g., by contact-app). The function is idempotent and will just refresh\n // the stored values with the same data from the URL.\n useEffect(() => {\n const trackingParameters = getAllTrackingParameters(window.location.href, {\n persistToLocalStorage: true,\n persistenceDays: 30,\n preferUrlParameters: true,\n scope: api.trackingScope,\n });\n\n // Log tracking parameters for debugging (development only)\n if (process.env.NODE_ENV === \"development\" && Object.keys(trackingParameters).length > 0) {\n log(\"[FormWidget] Captured tracking parameters:\", trackingParameters);\n }\n }, [api]);\n\n // Track partial_data on page unload using sendBeacon for reliable delivery\n useEffect(() => {\n const handleBeforeUnload = () => {\n // Merge completed step data with current step's live data\n const allFormData = { ...formData.current, ...currentStepDataRef.current };\n\n // Track abandon event if form wasn't submitted and no abandon event sent yet\n if (eventTracker.current && !formSubmittedRef.current && !abandonEventSentRef.current) {\n const form = formDisplayRef.current;\n if (form) {\n const totalSteps = form.steps?.length || 1;\n const currentStep = currentStepRef.current;\n\n eventTracker.current.trackPartialDataBeacon({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n partialData: allFormData,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n completionPercentage: Math.round((currentStep / totalSteps) * 100),\n abandonmentReason: \"close_tab\",\n });\n abandonEventSentRef.current = true;\n }\n }\n };\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n return () => window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n }, []);\n\n // Track partial_data when tab is hidden until midnight (abandoned tab scenario)\n useEffect(() => {\n let midnightTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const calculateMsUntilMidnight = (): number => {\n const now = new Date();\n const midnight = new Date(now);\n midnight.setHours(24, 0, 0, 0); // Next midnight\n return midnight.getTime() - now.getTime();\n };\n\n const sendTimeoutEvent = () => {\n // Merge completed step data with current step's live data\n const allFormData = { ...formData.current, ...currentStepDataRef.current };\n\n // Check all flags to prevent race conditions\n if (eventTracker.current && !formSubmittedRef.current && !abandonEventSentRef.current) {\n const form = formDisplayRef.current;\n if (form) {\n const totalSteps = form.steps?.length || 1;\n const currentStep = currentStepRef.current;\n\n // Use beacon for reliable delivery\n eventTracker.current.trackPartialDataBeacon({\n lastStepName: form.steps?.[currentStep]?.name || \"unknown\",\n lastStepIndex: currentStep,\n partialData: allFormData,\n totalStepsCompleted: currentStep,\n totalSteps: totalSteps,\n completionPercentage: Math.round((currentStep / totalSteps) * 100),\n abandonmentReason: \"timeout\",\n });\n\n // Mark abandon event sent to prevent duplicate events\n abandonEventSentRef.current = true;\n }\n }\n };\n\n const handleVisibilityChange = () => {\n if (document.hidden) {\n // Tab became hidden - start timer until midnight\n const msUntilMidnight = calculateMsUntilMidnight();\n midnightTimeoutId = setTimeout(sendTimeoutEvent, msUntilMidnight);\n } else {\n // Tab became visible - cancel the midnight timer\n if (midnightTimeoutId) {\n clearTimeout(midnightTimeoutId);\n midnightTimeoutId = null;\n }\n }\n };\n\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n return () => {\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n if (midnightTimeoutId) {\n clearTimeout(midnightTimeoutId);\n }\n };\n }, []);\n\n const intentRequest = useCallback(\n (\n request: { query?: string; intentId?: string },\n options?: { engagementTrigger?: EngagementTrigger }\n ) => {\n dispatch({\n query: request.query,\n intentId: request.intentId,\n type: \"set-query\",\n });\n\n run(() =>\n api.intentRequest(request).then((intentResponse) => {\n setResponse(intentResponse);\n dispatch({\n type: \"set-response\",\n response: intentResponse,\n query: request.query,\n intentId: request.intentId,\n });\n\n // Initialize event tracker when form is loaded\n const formDisplay = intentResponse?.displays?.find((d) => {\n const display = d as unknown as { type?: string };\n return display?.type === \"FORM\";\n }) as FormDisplay | undefined;\n if (formDisplay) {\n formDisplayRef.current = formDisplay;\n // The visit's session: the one the load event already reported\n const { sessionId } = api.visitSession();\n const formId = (formDisplay as { name?: string }).name || \"unknown\";\n formIdRef.current = formId;\n // A later FORM display - a chip click, say - is the same visit, so the\n // replacement inherits when it started and whether anyone has touched it.\n // Without that, every event after the first chip click loses its dwell.\n const previousTracker = eventTracker.current;\n eventTracker.current = new EventTrackingService(api, sessionId, formId);\n eventTracker.current.adoptVisitFrom(previousTracker);\n\n // Track form_open event once per mounted widget instance - the first\n // genuine surfacing of the form (docked render, trigger-activated open,\n // or manual open). A later intentRequest resolving to a FORM display\n // again (e.g. a chip click) is not a new surfacing and must not re-fire\n // WIDGET_FORM_OPEN. See `engaged` for genuine user intent.\n if (!formOpenSentRef.current) {\n formOpenSentRef.current = true;\n const totalSteps = formDisplay.steps?.length || 1;\n const firstStepName = formDisplay.steps?.[0]?.name;\n eventTracker.current.trackFormOpen({\n formName: formId,\n totalSteps,\n firstStepName,\n lastStepIndex: 0,\n });\n }\n\n if (options?.engagementTrigger) {\n trackEngagement(options.engagementTrigger);\n }\n }\n })\n );\n },\n [api, dispatch, run, trackEngagement]\n );\n\n const channelActionRequest = useCallback(\n (data: any, action: string): Promise<void> => {\n const dispatchOnce = () =>\n api.channelActionRequest(data, action).then((response) => {\n log(\n `ACTION Request (${action}). Data: ${JSON.stringify(\n data\n )} Response: ${JSON.stringify(response)}`\n );\n\n // A submit suppressed because the session already saw a final one\n // never reached the server. That is usually correct duplicate\n // protection, but it is also how a wrongly-latched session loses a\n // lead in silence, so say so rather than logging it as a success.\n if (wasDroppedAfterFinal(response)) {\n err(\n `ACTION Request (${action}) was suppressed: this session already sent a final submit.`\n );\n }\n\n if (response.outputSpeech || response.displays) {\n dispatch({\n type: \"set-response\",\n response,\n query: \"\",\n });\n }\n\n // FormDisplay awaits the FORM_SUBMIT dispatch, but only to learn\n // whether it failed -- it still advances on click and does not read\n // a return value. So a FORM_STEP_UPDATE in the response -- e.g. a\n // booking-widget handoff step's externalWidget.config -- is surfaced\n // back to FormDisplay via this prop rather than by threading a\n // return value through onActionResponse.\n if (action === \"FORM_SUBMIT\" && response.displays) {\n const update = (response.displays as unknown as FormStepUpdateDisplay[]).find(\n (display) => display?.type === \"FORM_STEP_UPDATE\"\n );\n if (update) {\n setStepUpdate(update);\n }\n }\n\n // Server side context (usually session params)\n if (response.context?.active && response.context.active.length > 0) {\n const context = response.context.active[0].parameters || {};\n\n dispatch({\n type: \"set-context\",\n context,\n });\n }\n\n if (!!data.autoClose) {\n setwaitingOnAudioToFinish(AUDIO_WAIT_CLOSE);\n } else if (!!data.autoMinimize) {\n setwaitingOnAudioToFinish(AUDIO_WAIT_MINIMIZE);\n } else {\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n }\n });\n\n if (action === \"FORM_SUBMIT\") {\n // Rejects once the retries are exhausted. FormDisplay awaits this and\n // turns a rejection into a visible error the user can retry from --\n // before, it was an unhandled rejection and the lead just vanished.\n return run(() => dispatchWithRetry(dispatchOnce, SUBMIT_RETRY_DELAYS_MS));\n }\n\n // Every other action stays fire-and-forget, but is no longer allowed to\n // become an unhandled rejection.\n return run(dispatchOnce).catch((error) => {\n err(`ACTION Request (${action}) failed: ${error}`);\n });\n },\n [api, dispatch, run]\n );\n\n useEffect(() => {\n // if we need to send, it is active and we have an autoGreeting or intentId\n //\n // The dockedRequestSent guard is load-bearing. This effect dispatches set-modal-state\n // below, which flips `active` false -> true, and `active` is in the dep array — so the\n // effect re-runs. The non-docked branch is protected because that same dispatch sets\n // sendRequest to false, but `docked` short-circuits the condition, so a docked widget\n // fired intentRequest (and therefore trackFormOpen) twice on every mount.\n if (\n (docked && !dockedRequestSent.current) ||\n (sendRequest && active && (config.autoGreeting || config.intentId))\n ) {\n if (docked) {\n dockedRequestSent.current = true;\n }\n api.resetSession();\n // Docked auto-mount and proactive auto-open triggers are impressions,\n // not user intent - only a genuine, non-auto-triggered activation counts\n // as a manual open for the `engaged` signal.\n const engagementTrigger: EngagementTrigger | undefined =\n !docked && !openedByTrigger ? \"manual_open\" : undefined;\n intentRequest(\n { query: config.autoGreeting, intentId: config.intentId },\n { engagementTrigger }\n );\n dispatch({\n type: \"set-modal-state\",\n active: true,\n minimized: false,\n sendRequest: false,\n });\n }\n }, [\n docked,\n openedByTrigger,\n sendRequest,\n active,\n intentRequest,\n dispatch,\n config.autoGreeting,\n api,\n config.intentId,\n ]);\n\n useEffect(() => {\n if (!audioOn) {\n if (waitingOnAudioToFinish === AUDIO_WAIT_CLOSE) {\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: false,\n sendRequest: false,\n });\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n } else if (waitingOnAudioToFinish === AUDIO_WAIT_MINIMIZE) {\n setResponse(undefined);\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: true,\n sendRequest: false,\n });\n setwaitingOnAudioToFinish(AUDIO_WAIT_NOTHING);\n }\n }\n }, [audioOn, dispatch, waitingOnAudioToFinish]);\n\n const handleActionClick = useCallback(\n (item: SuggestionTypes) => {\n const text = getActionLabel(item);\n // A chip click is always a genuine user action, whether or not the\n // form was originally opened manually.\n intentRequest({ query: text }, { engagementTrigger: \"chip_click\" });\n },\n [intentRequest]\n );\n\n // Auto-select a chip based on preselectChipLabel when response has suggestions\n useEffect(() => {\n if (!preselectChipLabel || !response) {\n return;\n }\n\n // Look for suggestions in the response - outputSpeech can be string or ResponseOutput\n const outputSpeech = response.outputSpeech;\n const suggestions =\n typeof outputSpeech === \"object\" && outputSpeech !== null\n ? outputSpeech.suggestions\n : undefined;\n if (!suggestions || suggestions.length === 0) {\n return;\n }\n\n // Find a chip matching the preselectChipLabel\n const matchingChip = suggestions.find(\n (chip) => getActionLabel(chip).toLowerCase() === preselectChipLabel.toLowerCase()\n );\n\n if (matchingChip) {\n log(`Auto-selecting chip: ${getActionLabel(matchingChip)}`);\n // Small delay to ensure UI is rendered before clicking\n setTimeout(() => {\n handleActionClick(matchingChip);\n }, 100);\n }\n\n // Clear the preselect label so we don't re-trigger\n if (onPreselectChipUsed) {\n onPreselectChipUsed();\n }\n }, [response, preselectChipLabel, handleActionClick, onPreselectChipUsed]);\n\n const handleActionResponse = useCallback(\n (data: unknown, action: string) => {\n if (!action) {\n action = (data as any).action;\n }\n // Tell the server the visitors TZ offset\n (data as any).timezoneOffset = new Date().getTimezoneOffset();\n\n if (action === \"FORM_SUBMIT\") {\n const trustedFormData = getTrustedFormData();\n if (trustedFormData && (data as any).result) {\n (data as any).result = { ...(data as any).result, ...trustedFormData };\n }\n // Carry the shared event id + Meta cookies so the backend can send\n // a deduplicated, high-match Conversions API Lead event.\n const eventId = getSubmitEventId();\n // GA4 goes out from the browser only when the customer's Google tag\n // is loaded; otherwise ga4ClientFired stays unset and the backend's\n // Measurement Protocol integration sends it instead (see utils/ga4).\n if (\n !config.api.demoMode &&\n !ga4FiredEventIdsRef.current.has(eventId) &&\n sendGa4LeadEvent(config.ga4MeasurementId, eventId, \"form-widget\")\n ) {\n ga4FiredEventIdsRef.current.add(eventId);\n }\n (data as any).extras = {\n ...(data as any).extras,\n eventId,\n ...getMetaCookies(),\n ...getGa4LeadExtras(config.ga4MeasurementId, ga4FiredEventIdsRef.current.has(eventId)),\n };\n }\n\n // Returned so FormDisplay can await the FORM_SUBMIT dispatch and surface a\n // failure rather than losing the lead silently (issue #1373).\n return channelActionRequest(data, action);\n },\n [channelActionRequest, getTrustedFormData, getSubmitEventId, config.api.demoMode, config.ga4MeasurementId]\n );\n\n const handleFormNext = useCallback(\n (data: FormNextData) => {\n return api.channelActionRequest(data, \"FORM_NEXT\");\n },\n [api]\n );\n\n const handleAudioChange = (isOn: boolean) => {\n setAudioOn(isOn);\n };\n\n // Tracking callbacks\n // Note: We intentionally fire BOTH specific events (next_step/previous_step) AND generic events (step_change).\n // - next_step/previous_step: Rich context for specific navigation analytics\n // - step_change: Unified view of all navigation for funnel analysis\n // This dual-event pattern is per the Widget Events API spec. May consolidate later based on analytics needs.\n const handleTrackInitialStep = useCallback((stepIndex: number) => {\n // The form opened straight on this step, so it is where the visitor\n // actually is. currentStepRef is otherwise only written by the\n // next/previous handlers, which need an explicit navigation to fire --\n // leaving it on 0 for a form opened via initialStep, and under-reporting\n // lastStepIndex and completionPercentage on every abandonment path.\n //\n // Deliberately not trackEngagement: nobody engaged with anything by\n // being shown a step.\n currentStepRef.current = stepIndex;\n }, []);\n\n const handleTrackNextStep = useCallback(\n (\n stepName: string,\n stepIndex: number,\n stepData: Record<string, unknown>,\n isLastStep: boolean\n ) => {\n // Update form data ref and reset current step data for the new step\n formData.current = { ...formData.current, ...stepData };\n currentStepDataRef.current = {}; // Reset live data for new step\n currentStepRef.current = stepIndex + 1; // Moving to next step\n\n // Completing a step is a genuine user action, whether or not the\n // form was originally opened manually.\n trackEngagement(\"step_transition\");\n\n if (eventTracker.current) {\n const form = formDisplayRef.current;\n const nextStepName = form?.steps?.[stepIndex + 1]?.name;\n const totalSteps = form?.steps?.length || 1;\n\n // Track next_step event (specific forward navigation with step data)\n eventTracker.current.trackNextStep({\n completedStepName: stepName,\n completedStepIndex: stepIndex,\n nextStepName,\n stepData,\n isLastStep,\n });\n\n // Track step_change event (generic navigation for unified funnel view)\n if (nextStepName) {\n eventTracker.current.trackStepChange({\n fromStepName: stepName,\n fromStepIndex: stepIndex,\n toStepName: nextStepName,\n toStepIndex: stepIndex + 1,\n direction: \"forward\",\n lastStepIndex: stepIndex + 1,\n totalSteps,\n });\n }\n }\n },\n [trackEngagement]\n );\n\n const handleTrackPreviousStep = useCallback(\n (fromStepName: string, fromStepIndex: number, toStepName: string, toStepIndex: number) => {\n // Update current step ref and reset current step data for the new step\n currentStepDataRef.current = {}; // Reset live data for new step\n currentStepRef.current = toStepIndex;\n\n if (eventTracker.current) {\n const totalSteps = formDisplayRef.current?.steps?.length || 1;\n\n // Track previous_step event (specific backward navigation)\n eventTracker.current.trackPreviousStep({\n fromStepName,\n fromStepIndex,\n toStepName,\n toStepIndex,\n lastStepIndex: toStepIndex,\n totalSteps,\n });\n\n // Track step_change event (generic navigation for unified funnel view)\n eventTracker.current.trackStepChange({\n fromStepName,\n fromStepIndex,\n toStepName,\n toStepIndex,\n direction: \"backward\",\n lastStepIndex: toStepIndex,\n totalSteps,\n });\n }\n },\n []\n );\n\n const handleTrackSubmit = useCallback(\n (\n stepName: string,\n stepIndex: number,\n completedData: Record<string, unknown>,\n totalSteps: number\n ) => {\n // Guard against double-firing the submit event: a double-click before the\n // \"submitting\" UI state flushes, a re-render, or a retry can invoke this\n // callback more than once for the same submission. Only the first call\n // should ever track/notify.\n if (formSubmittedRef.current) {\n return;\n }\n formSubmittedRef.current = true;\n\n // Include TrustedForm cert URL in submit event if available\n const trustedFormData = getTrustedFormData();\n const dataWithTrustedForm = trustedFormData\n ? { ...completedData, ...trustedFormData }\n : completedData;\n\n formData.current = dataWithTrustedForm;\n\n if (eventTracker.current) {\n eventTracker.current.trackSubmit({\n finalStepName: stepName,\n finalStepIndex: stepIndex,\n completedData: dataWithTrustedForm,\n totalSteps,\n });\n }\n\n // Notify the embedding page that a submit happened (e.g. to fire\n // external conversion tracking). Deliberately passes no data: the\n // submitted payload contains PII (and the TrustedForm cert URL) and\n // must not be handed to third-party trackers.\n // ...unless this is a preview. onSubmit exists so the host can\n // fire external conversion tracking — a Meta Pixel Lead event, per\n // its own doc comment. That reaches a third-party ad platform, so\n // it is the most consequential signal demo mode has to suppress:\n // it is driven purely by UI completion and would otherwise fire for\n // a session that never touched the backend.\n if (onSubmit && !config.api.demoMode) {\n try {\n onSubmit(getSubmitEventId());\n } catch (error) {\n err(\"[FormWidget] onSubmit callback threw:\", error);\n }\n }\n },\n [getTrustedFormData, onSubmit, getSubmitEventId, config.api.demoMode]\n );\n\n // The FORM_SUBMIT dispatch failed after its retries, so the lead was not created.\n // handleTrackSubmit above has already recorded the submit; this is the counter-signal\n // that keeps that from reading as a success (issue #1373). The formSubmittedRef guard\n // is deliberately not consulted -- the submit event it gated has already gone out,\n // and this event is what corrects it.\n const handleTrackSubmitFailure = useCallback(\n (stepName: string, stepIndex: number, totalSteps: number, reason: string) => {\n eventTracker.current?.trackSubmitFailure({\n finalStepName: stepName,\n finalStepIndex: stepIndex,\n totalSteps,\n reason,\n });\n },\n []\n );\n\n // Booking-widget handoff step tracking. formName/sessionId are carried on\n // every event via eventTracker's own metadata (see EventTrackingService),\n // matching how the other track* handlers above don't pass them explicitly.\n const handleTrackHandoffRendered = useCallback((stepName: string, provider: string) => {\n eventTracker.current?.trackHandoffRendered({ stepName, provider });\n }, []);\n\n const handleTrackHandoffNoRender = useCallback((stepName: string, provider: string) => {\n eventTracker.current?.trackHandoffNoRender({ stepName, provider });\n }, []);\n\n const handleTrackHandoffScheduled = useCallback((stepName: string, provider: string, payload?: unknown) => {\n eventTracker.current?.trackHandoffScheduled({ stepName, provider, payload });\n }, []);\n\n const handleTrackHandoffError = useCallback((stepName: string, provider: string) => {\n eventTracker.current?.trackHandoffError({ stepName, provider });\n }, []);\n\n const displayContainer: boolean = !!query || !!response;\n\n if (docked) {\n // we might want to put a wrapper around this for docked mode\n return (\n <div\n className={`${styles.xapp_form_widget} ${embedded ? styles.embedded : \"\"} ${\n loading ? styles.loading : \"\"\n }`}>\n <div\n className={`${styles[\"xapp_form_widget__content\"]} ${\n loading ? styles.loading : \"\"\n }`}\n >\n {response ? (\n <FormResponse\n response={response}\n className={styles[\"xapp_form_widget__response\"]}\n onActionClick={handleActionClick}\n onActionResponse={handleActionResponse}\n onAudioChange={handleAudioChange}\n loading={loading}\n onTrackNextStep={handleTrackNextStep}\n onTrackPreviousStep={handleTrackPreviousStep}\n onTrackSubmit={handleTrackSubmit}\n onTrackSubmitFailure={handleTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={handleTrackInitialStep}\n onFormNext={handleFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={handleTrackHandoffRendered}\n onTrackHandoffNoRender={handleTrackHandoffNoRender}\n onTrackHandoffScheduled={handleTrackHandoffScheduled}\n onTrackHandoffError={handleTrackHandoffError}\n />\n ) : (\n <div className={styles[\"xapp_form_widget__spinner\"]}>\n <SpinnerIcon />\n </div>\n )}\n </div>\n </div>\n );\n }\n\n return (\n <div\n className={`${styles.xapp_form_widget} ${embedded ? styles.embedded : \"\"} ${\n loading && !response ? styles.loading : \"\"\n }`}>\n {displayContainer && (\n <div\n className={`${styles[\"xapp_form_widget__content\"]} ${\n loading && !response ? styles.loading : \"\"\n }`}\n >\n {!response && loading && (\n <div className={styles[\"xapp_form_widget__spinner\"]}>\n <SpinnerIcon />\n </div>\n )}\n\n {response && (\n <FormResponse\n response={response}\n className={styles[\"xapp_form_widget__response\"]}\n onActionClick={handleActionClick}\n onActionResponse={handleActionResponse}\n onAudioChange={handleAudioChange}\n loading={loading}\n onTrackNextStep={handleTrackNextStep}\n onTrackPreviousStep={handleTrackPreviousStep}\n onTrackSubmit={handleTrackSubmit}\n onTrackSubmitFailure={handleTrackSubmitFailure}\n currentStepDataRef={currentStepDataRef}\n initialStep={initialStep}\n preselectFirstAvailableDate={preselectFirstAvailableDate}\n onTrackInitialStep={handleTrackInitialStep}\n onFormNext={handleFormNext}\n stepUpdate={stepUpdate}\n onTrackHandoffRendered={handleTrackHandoffRendered}\n onTrackHandoffNoRender={handleTrackHandoffNoRender}\n onTrackHandoffScheduled={handleTrackHandoffScheduled}\n onTrackHandoffError={handleTrackHandoffError}\n />\n )}\n </div>\n )}\n\n {response && !!handleCancel && (\n <div className={styles[\"xapp_form_widget__close\"]} onClick={handleClose}>\n {\"\\u2715\"}\n </div>\n )}\n </div>\n );\n};\n","import React, { FC } from \"react\";\nimport {\n FormWidgetDropdownTheme,\n FormWidgetFontTheme,\n FormWidgetTextTheme,\n FormWidgetButtonTheme,\n FormWidgetStepTitleTheme,\n FormWidgetTheme,\n FormWidgetCardTheme,\n FormWidgetCheckboxTheme,\n FormWidgetChipsTheme,\n FormWidgetDateTheme,\n FormWidgetSideButtonTheme,\n FormWidgetExternalWidgetTheme,\n} from \"@xapp/stentor-form-widget-channel\";\n\nimport { err } from \"../../utils\";\n\nexport interface WidgetStylesheetProps {\n readonly theme?: FormWidgetTheme;\n}\n\n/**\n * Injects the styles\n *\n * @param props\n * @returns\n */\nexport const WidgetStylesheet: FC<WidgetStylesheetProps> = (props) => {\n const { theme } = props;\n\n // Load external font if specified\n React.useEffect(() => {\n const currentFontLink = theme?.font?.link;\n\n if (currentFontLink) {\n loadExternalFont(currentFontLink);\n }\n\n // Cleanup function to remove font link when component unmounts or font changes\n return () => {\n if (currentFontLink) {\n const linkId = \"xapp-form-widget-font\";\n const existingLink = document.getElementById(linkId);\n // Only remove if it's the font we loaded in this effect\n if (existingLink && existingLink.getAttribute(\"href\") === currentFontLink) {\n existingLink.remove();\n }\n }\n };\n }, [theme?.font?.link]);\n\n // Apply the theme as CSS custom properties on :root via the CSSOM instead of\n // injecting a <style> tag: setProperty() is not governed by CSP style-src, so\n // the widget themes correctly under a strict policy (style-src 'self', no\n // 'unsafe-inline') without needing a nonce.\n const entriesKey = JSON.stringify(buildStyleVariables(theme));\n React.useLayoutEffect(() => {\n const entries = JSON.parse(entriesKey) as Array<[string, string]>;\n applyThemeVariables(entries);\n return () => removeThemeVariables(entries);\n }, [entriesKey]);\n\n return null;\n};\n\n/**\n * Loads an external font by injecting a link tag into the document head\n * Automatically adds font-display=swap optimization for Google Fonts\n */\nexport function loadExternalFont(fontUrl: string): void {\n // Validate URL format and security\n try {\n const url = new URL(fontUrl);\n if (url.protocol !== \"https:\") {\n console.warn(\"Only HTTPS font URLs are allowed:\", fontUrl);\n return;\n }\n\n // Optional: Restrict to trusted font providers\n const trustedDomains = [\n \"fonts.googleapis.com\",\n \"fonts.gstatic.com\",\n \"use.typekit.net\",\n \"use.fontawesome.com\",\n \"cdn.jsdelivr.net\",\n \"unpkg.com\",\n \"cdnjs.cloudflare.com\",\n ];\n\n if (!trustedDomains.includes(url.hostname)) {\n console.warn(\"Font URL from untrusted domain:\", url.hostname);\n // Still proceed but warn - in production you might want to block this\n }\n\n // Add font-display=swap for Google Fonts if not already present\n if (url.hostname === \"fonts.googleapis.com\" && !url.searchParams.has(\"display\")) {\n url.searchParams.set(\"display\", \"swap\");\n fontUrl = url.toString();\n }\n } catch (error) {\n console.error(\"Invalid font URL:\", fontUrl, error);\n return;\n }\n\n const linkId = \"xapp-form-widget-font\";\n\n // Remove existing font link if present\n const existingLink = document.getElementById(linkId);\n if (existingLink) {\n existingLink.remove();\n }\n\n // Create and inject new font link\n const link = document.createElement(\"link\");\n link.id = linkId;\n link.rel = \"stylesheet\";\n link.href = fontUrl;\n link.crossOrigin = \"anonymous\"; // Add security attribute\n document.head.appendChild(link);\n}\n\n// All instances apply their theme variables to the same target (:root), so a\n// per-variable ref-count ensures an unmounting instance only removes a variable\n// when no other mounted instance still relies on it.\nconst appliedVariableCounts = new Map<string, number>();\n\nfunction applyThemeVariables(entries: Array<[string, string]>): void {\n const root = document.documentElement;\n for (const [key, value] of entries) {\n root.style.setProperty(key, value);\n appliedVariableCounts.set(key, (appliedVariableCounts.get(key) ?? 0) + 1);\n }\n}\n\nfunction removeThemeVariables(entries: Array<[string, string]>): void {\n const root = document.documentElement;\n for (const [key] of entries) {\n const remaining = (appliedVariableCounts.get(key) ?? 1) - 1;\n if (remaining <= 0) {\n appliedVariableCounts.delete(key);\n root.style.removeProperty(key);\n } else {\n appliedVariableCounts.set(key, remaining);\n }\n }\n}\n\n/**\n * Generates the [cssVariableName, value] pairs for a form-widget theme, e.g.\n * [\"--xapp-form-widget-background-color\", \"#ffffff\"].\n */\nfunction themeVariables(widgetTheme?: FormWidgetTheme): StyleGenerator {\n const theme: FormWidgetTheme = widgetTheme || {};\n return withPrefix(\n \"--xapp-form-widget-\",\n union(\n single(\"background-color\", theme?.backgroundColor),\n single(\"header-background-color\", theme?.headerBackgroundColor),\n single(\"header-text-color\", theme?.headerTextColor),\n single(\"primary-button-color\", theme?.primaryButtonColor),\n single(\"primary-button-text-color\", theme?.primaryButtonTextColor),\n single(\"secondary-button-color\", theme?.secondaryButtonColor),\n single(\"secondary-button-text-color\", theme?.secondaryButtonTextColor),\n single(\"border-color\", theme?.borderColor),\n // The stylesheet reads two steps of the radius scale and nothing emitted\n // either, so neither could be set at all. One theme value drives both.\n single(\"border-radius-md\", theme?.borderRadius),\n single(\"border-radius-xl\", theme?.borderRadius),\n withPrefix(\"font-\", union(getFontStyle(theme?.font))),\n withPrefix(\"text-\", union(getTextStyle(theme?.text))),\n withPrefix(\"back-button-\", union(getBackButtonStyle(theme))),\n withPrefix(\"button-\", union(getButtonStyle(theme?.button))),\n withPrefix(\"step-title-\", union(getStepTitleStyle(theme?.stepTitle))),\n withPrefix(\"final-button-\", union(getFinalButtonStyle(theme))),\n withPrefix(\"dropdown-\", union(getDropdownStyle(theme?.dropdown))),\n withPrefix(\"checkbox-\", union(getCheckboxStyle(theme?.checkbox))),\n withPrefix(\"chips-\", union(getChipsStyle(theme?.chips))),\n withPrefix(\"date-\", union(getDateStyle(theme?.date))),\n withPrefix(\"card-\", union(getCardStyle(theme?.card))),\n withPrefix(\"side-button-\", union(getSideButtonStyle(theme?.sideButton))),\n withPrefix(\"external-widget-\", union(getExternalWidgetStyle(theme?.externalWidget)))\n )\n );\n}\n\n/**\n * Collects the defined theme CSS variables as [name, value] entries, skipping\n * empty values.\n */\nexport function buildStyleVariables(theme?: FormWidgetTheme): Array<[string, string]> {\n const entries: Array<[string, string]> = [];\n const gen = themeVariables(theme);\n let result = gen.next();\n while (result.done === false) {\n const [key, value] = result.value;\n if (value !== undefined && value !== null && value !== \"\") {\n entries.push([key, value]);\n }\n result = gen.next();\n }\n return entries;\n}\n\nexport function buildStyleContent(widgetTheme?: FormWidgetTheme): string {\n const body = buildStyleVariables(widgetTheme)\n .map(([key, value]) => `\\t${key}: ${value};`)\n .join(\"\\n\");\n return `\\n:root {\\n${body}\\n}\\n`;\n}\n\nfunction* getFontStyle(style?: FormWidgetFontTheme): StyleGenerator {\n if (style) {\n yield [\"family\", style.fontFamily];\n }\n}\n\nfunction* getSideButtonStyle(style?: FormWidgetSideButtonTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-dark\", darken(style.backgroundColor, 10)];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n yield [\"top\", style.top];\n yield [\"min-length\", style.minLength];\n }\n}\n\n/**\n * The back control, including which of its two shapes to draw.\n *\n * The variant is emitted as display toggles rather than threaded to the component as a prop:\n * the theme reaches FormStepDisplay only as CSS variables, and the alternative was passing it\n * through Form -> FormDisplay -> FormStepDisplay purely so a button could pick a shape.\n * The component renders both a label and an arrow; exactly one of them is ever displayed.\n */\n/** A step's opening heading. Absent leaves it left-aligned body text, as today. */\nfunction* getStepTitleStyle(style?: FormWidgetStepTitleTheme): StyleGenerator {\n if (style) {\n yield [\"align\", style.align];\n yield [\"font-size\", style.fontSize];\n yield [\"font-weight\", style.fontWeight];\n yield [\"color\", style.color];\n }\n}\n\n/**\n * Final-step layout. `\"above\"` is emitted as nothing at all -- the scss defaults ARE that\n * layout -- so only `\"inline\"` produces variables.\n */\nfunction* getFinalButtonStyle(theme?: FormWidgetTheme): StyleGenerator {\n if (theme?.finalButtonPlacement === \"inline\") {\n // row-reverse: the submit button comes first in the DOM, so reversing puts the back\n // control on the left and submit beside it, on one line.\n yield [\"direction\", \"row-reverse\"];\n yield [\"gap\", \"24px\"];\n yield [\"nav-flex\", \"0 0 auto\"];\n yield [\"nav-align\", \"center\"];\n yield [\"container-padding\", \"20px 0\"];\n yield [\"nav-padding\", \"20px 0\"];\n }\n}\n\n/** Shape and type of the advance buttons. Absent leaves MUI's own metrics in place. */\nfunction* getButtonStyle(style?: FormWidgetButtonTheme): StyleGenerator {\n if (style) {\n yield [\"font-size\", style.fontSize];\n yield [\"font-weight\", style.fontWeight];\n yield [\"padding\", style.padding];\n yield [\"radius\", style.borderRadius];\n yield [\"shadow\", style.boxShadow];\n }\n}\n\nfunction* getBackButtonStyle(theme?: FormWidgetTheme): StyleGenerator {\n const icon = theme?.backButtonVariant === \"icon\";\n const back = theme?.backButton;\n\n // Defaults reproduce the labelled filled button every existing form has.\n yield [\"label-display\", icon ? \"none\" : \"inline\"];\n yield [\"icon-display\", icon ? \"inline-flex\" : \"none\"];\n\n if (icon) {\n const color = back?.color;\n yield [\"background\", \"transparent\"];\n yield [\"border\", `${back?.borderWidth || \"1px\"} solid ${back?.borderColor || color || \"currentColor\"}`];\n // The arrow is a text glyph, and glyph weight depends on the font -- Poppins barely\n // thickens it. A stroke thickens it the same in any font.\n yield [\"icon-stroke\", back?.iconStroke];\n yield [\"radius\", \"50%\"];\n // The default is now MUI's elevation (so the labelled button keeps it); a ring doesn't\n // want one.\n yield [\"shadow\", \"none\"];\n yield [\"size\", \"44px\"];\n yield [\"padding\", \"0\"];\n // Always emitted for the icon. The scss fallback is the BUTTON TEXT colour, which is right\n // for the labelled variant (it sits on the primary fill) and wrong here: the icon has no\n // fill, so a usually-white text colour made the arrow and its ring vanish on a light page.\n // `currentColor`, which takes the page's own text colour -- legible on the page by\n // definition. NOT `inherit`: that is a CSS-wide keyword, so `--x: inherit` makes the\n // custom property itself inherit (from nothing, on :root) rather than holding the word,\n // and var() falls straight through to the white default. `currentColor` is an ordinary\n // value, substitutes cleanly, and `color: currentColor` computes as inherit.\n yield [\"color\", color || \"currentColor\"];\n yield [\"color-hover\", back?.colorHover || color || \"currentColor\"];\n }\n}\n\nfunction* getTextStyle(style?: FormWidgetTextTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-dark\", darken(style.backgroundColor, 3)];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n // Absent leaves the field borderless, which is what every form that never set these\n // already looks like -- the scss defaults are a zero width and a transparent colour.\n yield [\"border-color\", style.borderColor];\n yield [\"border-width\", style.borderWidth];\n yield [\"border-color-focus\", style.borderColorFocus || style.borderColor];\n // MUI's filled input draws its own underline as a ::before/::after on the root. It is a\n // straight 1px line across the full width, so on a field that now has a rounded border\n // it reads as a darker bar running past the corners. A themed border replaces it;\n // without one it is still the field's only affordance, so it stays.\n yield [\"underline-display\", style.borderWidth ? \"none\" : undefined];\n // With no underline to meet, the bottom corners round like the top ones again.\n yield [\"bottom-radius\", style.borderWidth ? \"var(--xapp-form-widget-border-radius-sm, 8px)\" : undefined];\n // The address autocomplete paints its box on the ROOT, which also holds the dropdown\n // adornment. Only when a border is themed -- otherwise these stay unset and the root\n // keeps MUI's own filled look, which is what every other form has.\n if (style.borderWidth) {\n yield [\"root-background\", style.backgroundColor];\n yield [\"root-border\", `${style.borderWidth} solid ${style.borderColor || \"transparent\"}`];\n yield [\"root-radius\", \"var(--xapp-form-widget-border-radius-sm, 8px)\"];\n yield [\"input-background\", \"transparent\"];\n }\n }\n}\n\nfunction* getDropdownStyle(style?: FormWidgetDropdownTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getCheckboxStyle(style?: FormWidgetCheckboxTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getChipsStyle(style?: FormWidgetChipsTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-selected\", style.backgroundColorSelected];\n yield [\"background-color-dark\", darken(style.backgroundColor, 20)];\n yield [\"color\", style.color];\n yield [\"color-selected\", style.colorSelected];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getDateStyle(style?: FormWidgetDateTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"background-color-selected\", style.backgroundColorSelected];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getCardStyle(style?: FormWidgetCardTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"color\", style.color];\n yield [\"font-size\", style.fontSize];\n yield [\"font-family\", style.fontFamily];\n }\n}\n\nfunction* getExternalWidgetStyle(style?: FormWidgetExternalWidgetTheme): StyleGenerator {\n if (style) {\n yield [\"background-color\", style.backgroundColor];\n yield [\"padding\", style.padding];\n yield [\"min-height\", style.minHeight];\n }\n}\n\ndeclare type StyleGenerator = Generator<[string, string | undefined], void, never>;\n\n// function* empty(): StyleGenerator {}\n\nfunction* withPrefix(prefix: string, gen: StyleGenerator): StyleGenerator {\n let result = gen.next();\n while (!result.done) {\n yield [`${prefix}${result.value[0]}`, result.value[1]];\n result = gen.next();\n }\n}\n\nfunction* union(...children: StyleGenerator[]): StyleGenerator {\n for (const child of children) {\n let result = child.next();\n while (result.done === false) {\n yield result.value;\n result = child.next();\n }\n }\n}\n\nfunction* single(key: string, value: string | undefined): StyleGenerator {\n yield [key, value];\n}\n\nfunction darken(colorIn: string | undefined, amount: number) {\n if (!colorIn) {\n return colorIn;\n }\n\n let r: number | undefined, g: number | undefined, b: number | undefined, a: number | undefined;\n let colorOut;\n\n try {\n // Parse the color format\n if (colorIn.startsWith(\"#\")) {\n // Hex format\n const hexMatch = colorIn.match(/\\w\\w/g);\n if (hexMatch) {\n [r, g, b] = hexMatch.map((x) => parseInt(x, 16));\n }\n } else if (colorIn.startsWith(\"rgb\")) {\n // RGB or RGBA format\n const rgba = parseRgb(colorIn);\n if (rgba) {\n ({ r, g, b, a } = rgba);\n }\n }\n\n if (r === undefined || g === undefined || b === undefined) {\n err(`Darken: Unsupported color format: ${colorIn}`);\n return colorIn;\n }\n\n if (a !== undefined) {\n // Just darkened backdrop?\n if (r === 0 && g === 0 && b === 0) {\n a = a + amount / 100;\n } else {\n // Adjust luminance for RGBA\n const luminance = 0.3 * r + 0.59 * g + 0.11 * b;\n const newLuminance = luminance * (1 - amount / 100);\n const ratio = newLuminance / luminance;\n r = Math.round(r * ratio);\n g = Math.round(g * ratio);\n b = Math.round(b * ratio);\n }\n\n colorOut = `rgba(${r}, ${g}, ${b}, ${a})`;\n } else {\n // Darken the color for RGB or Hex\n r = Math.max(0, r - amount);\n g = Math.max(0, g - amount);\n b = Math.max(0, b - amount);\n\n colorOut = `#${r.toString(16).padStart(2, \"0\")}${g.toString(16).padStart(2, \"0\")}${b\n .toString(16)\n .padStart(2, \"0\")}`;\n }\n } catch (e) {\n err(`Darken: Unsupported color format: ${colorIn} - Error: ${e}`);\n }\n\n return colorOut;\n}\n\nfunction parseRgb(colorString: string): { r: number; g: number; b: number; a?: number } | null {\n const rgbaRegex = /^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+),\\s*([\\d.]+)\\)$/;\n const rgbRegex = /^rgb?\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/;\n\n let match: string[] | null;\n\n // eslint-disable-next-line no-cond-assign\n if ((match = colorString.match(rgbaRegex))) {\n const r = parseInt(match[1]);\n const g = parseInt(match[2]);\n const b = parseInt(match[3]);\n const a = parseFloat(match[4]);\n\n return { r, g, b, a };\n // eslint-disable-next-line no-cond-assign\n } else if ((match = colorString.match(rgbRegex))) {\n const r = parseInt(match[1]);\n const g = parseInt(match[2]);\n const b = parseInt(match[3]);\n\n return { r, g, b };\n } else {\n return null;\n }\n}\n","export enum classNames {\n XAPP_FORM_BUTTON = \"xapp-form-button\"\n}\n","import React, { FC } from \"react\";\n\nimport styles from \"./SideButton.module.scss\";\n\nexport interface SideButtonProps {\n readonly onClick?: () => void;\n readonly position?: string;\n readonly label?: string;\n /**\n * Keeps the button in the DOM but off screen, so host scripts that click it still work.\n */\n readonly hidden?: boolean;\n}\n\nexport const SideButton: FC<SideButtonProps> = (props) => {\n const { onClick, position, label, hidden } = props;\n\n const sideButtonPositionClass = position?.toLowerCase() === \"right\" ? styles.right : styles.left;\n\n return (\n <div\n onClick={onClick}\n className={`${styles.xapp_form_sticky_button} ${sideButtonPositionClass}`}\n data-xapp-form-side-button=\"true\"\n // Inline rather than the `hidden` attribute: the module class sets display and would win.\n style={hidden ? { display: \"none\" } : undefined}\n aria-hidden={hidden || undefined}>\n \n {/* <svg\n className={styles.xapp_form_sticky_button_left_img}\n width=\"69\"\n height=\"43\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n version=\"1.1\">\n <path\n d=\"M0 0v43h68.4a38 38 0 0 1-32.71-18.66l-3.36-5.68A38 38 0 0 0 0 0Z\"\n fill=\"#EF7E45\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n />\n </svg> */}\n\n <span>{label || \"Schedule Now\"}</span>\n\n {/* <svg\n className={styles.xapp_form_sticky_button_right_img}\n width=\"69\"\n height=\"43\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n version=\"1.1\"\n transform=\"matrix(1,0,0,-1,0,0)\">\n <path\n d=\"M0 0v43h68.4a38 38 0 0 1-32.71-18.66l-3.36-5.68A38 38 0 0 0 0 0Z\"\n fill=\"#EF7E45\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n />\n </svg> */}\n </div>\n );\n};\n\nexport default SideButton;\n","import { useEffect, useRef, useCallback, useMemo } from \"react\";\nimport { FormWidgetEnv } from \"@xapp/stentor-form-widget-channel\";\n\ntype AutoOpenConfig = FormWidgetEnv[\"autoOpen\"];\n\nexport interface UseAutoOpenTriggersOptions {\n config?: AutoOpenConfig;\n isActive: boolean;\n onOpen: () => void;\n hasInteracted: boolean;\n}\n\n/** Default sessionStorage key for tracking dismissed state */\nexport const DEFAULT_SESSION_KEY = \"xafw-auto-open-dismissed\";\nconst DEFAULT_EXIT_INTENT_THRESHOLD = 50;\nconst MIN_DELAY = 0;\nconst MAX_DELAY = 300000; // 5 minutes\nconst MIN_SCROLL_PERCENT = 0;\nconst MAX_SCROLL_PERCENT = 100;\n\n/**\n * Validates and clamps a delay/inactivity value to safe bounds\n */\nfunction validateDelay(value: number | undefined): number | undefined {\n if (typeof value !== \"number\" || value < MIN_DELAY) return undefined;\n return Math.min(value, MAX_DELAY);\n}\n\n/**\n * Validates and clamps scroll percentage to 0-100\n */\nfunction validateScrollPercent(value: number | undefined): number | undefined {\n if (typeof value !== \"number\") return undefined;\n return Math.max(MIN_SCROLL_PERCENT, Math.min(value, MAX_SCROLL_PERCENT));\n}\n\n/**\n * Validates exit intent threshold (must be positive)\n */\nfunction validateThreshold(value: number | undefined): number {\n if (typeof value !== \"number\" || value < 0) return DEFAULT_EXIT_INTENT_THRESHOLD;\n return value;\n}\n\n/**\n * Checks if the form was already dismissed this session\n */\nfunction isDismissed(sessionKey: string): boolean {\n try {\n return sessionStorage.getItem(sessionKey) === \"true\";\n } catch {\n // Private browsing or sessionStorage not available\n return false;\n }\n}\n\n/**\n * Returns true if any behavior-based auto-open trigger (delay, scrollPercent,\n * exitIntent, inactivity) is configured.\n *\n * Used to distinguish \"open immediately\" (`enabled` alone) from \"open once a\n * trigger condition is met\" (`enabled` + `triggers`).\n */\nexport function hasAutoOpenTriggers(config?: AutoOpenConfig): boolean {\n const triggers = config?.triggers;\n // Compare the *validated* values, not the raw config. The hook below arms its listeners\n // off the validated values too, so reading the raw ones here lets the two disagree: a\n // config like `{ delay: -1 }` would look like a configured trigger (so the form waits\n // instead of opening immediately) while the hook discards it (so no trigger ever fires)\n // -- and the form would silently never open at all.\n return (\n validateDelay(triggers?.delay) !== undefined ||\n validateScrollPercent(triggers?.scrollPercent) !== undefined ||\n !!triggers?.exitIntent ||\n validateDelay(triggers?.inactivity) !== undefined\n );\n}\n\n/**\n * Checks if current URL matches any of the provided patterns\n */\nfunction matchesUrlPatterns(patterns?: string[]): boolean {\n if (!patterns || patterns.length === 0) {\n return true;\n }\n const currentUrl = window.location.href;\n return patterns.some((pattern) => currentUrl.includes(pattern));\n}\n\n/**\n * Checks if viewport width meets minimum requirement\n */\nfunction meetsMinimumWidth(minimumWidth?: number): boolean {\n if (typeof minimumWidth !== \"number\") {\n return true;\n }\n return window.innerWidth >= minimumWidth;\n}\n\n/**\n * Checks if device supports touch (for disabling exit intent on touch devices)\n */\nfunction isTouchDevice(): boolean {\n return \"ontouchstart\" in window || navigator.maxTouchPoints > 0;\n}\n\n/**\n * Hook for auto-opening the form widget based on configurable triggers.\n *\n * Supports:\n * - delay: Timer-based trigger (milliseconds)\n * - scrollPercent: Scroll-based trigger (0-100)\n * - exitIntent: Mouse leaving viewport trigger\n * - inactivity: User idle trigger (milliseconds)\n *\n * Modes:\n * - 'any' (default): First trigger that fires opens the form\n * - 'all': All configured triggers must fire before opening\n */\nexport function useAutoOpenTriggers({\n config,\n isActive,\n onOpen,\n hasInteracted,\n}: UseAutoOpenTriggersOptions): void {\n const triggersRef = useRef<Set<string>>(new Set());\n const hasOpenedRef = useRef(false);\n const inactivityTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n const sessionKey = config?.sessionKey || DEFAULT_SESSION_KEY;\n const mode = config?.mode || \"any\";\n const triggers = config?.triggers;\n\n // Extract and validate primitive values to use as stable dependencies\n const delay = validateDelay(triggers?.delay);\n const scrollPercent = validateScrollPercent(triggers?.scrollPercent);\n const exitIntent = triggers?.exitIntent;\n const exitIntentThreshold = validateThreshold(triggers?.exitIntentThreshold);\n const inactivity = validateDelay(triggers?.inactivity);\n const patterns = config?.patterns;\n const minimumWidth = config?.minimumWidth;\n\n // Serialize patterns array to create a stable dependency\n // This prevents effect re-runs when array reference changes but contents are identical\n const patternsKey = useMemo(() => JSON.stringify(patterns ?? []), [patterns]);\n\n // Calculate which triggers are configured\n const configuredTriggers = useRef<string[]>([]);\n\n // Get list of configured triggers\n const getConfiguredTriggers = useCallback((): string[] => {\n const list: string[] = [];\n if (triggers?.delay !== undefined) list.push(\"delay\");\n if (triggers?.scrollPercent !== undefined) list.push(\"scrollPercent\");\n if (triggers?.exitIntent) list.push(\"exitIntent\");\n if (triggers?.inactivity !== undefined) list.push(\"inactivity\");\n return list;\n }, [triggers?.delay, triggers?.scrollPercent, triggers?.exitIntent, triggers?.inactivity]);\n\n // Check if we should open based on mode and fired triggers\n const checkAndOpen = useCallback(\n (triggerName: string) => {\n if (hasOpenedRef.current) return;\n\n triggersRef.current.add(triggerName);\n\n if (mode === \"any\") {\n // Open on first trigger\n hasOpenedRef.current = true;\n onOpen();\n } else if (mode === \"all\") {\n // Check if all configured triggers have fired\n const configured = configuredTriggers.current;\n const allFired = configured.every((t) => triggersRef.current.has(t));\n if (allFired) {\n hasOpenedRef.current = true;\n onOpen();\n }\n }\n },\n [mode, onOpen]\n );\n\n useEffect(() => {\n // Reset state when config changes\n triggersRef.current = new Set();\n hasOpenedRef.current = false;\n configuredTriggers.current = getConfiguredTriggers();\n }, [getConfiguredTriggers]);\n\n useEffect(() => {\n // Guard conditions - skip if any are true\n const hasTriggers =\n delay !== undefined ||\n scrollPercent !== undefined ||\n exitIntent ||\n inactivity !== undefined;\n if (!hasTriggers) return;\n if (isActive) return;\n if (hasInteracted) return;\n if (isDismissed(sessionKey)) return;\n if (!matchesUrlPatterns(patterns)) return;\n if (!meetsMinimumWidth(minimumWidth)) return;\n\n const timers: NodeJS.Timeout[] = [];\n const listeners: Array<{\n target: EventTarget;\n event: string;\n handler: EventListener;\n options?: AddEventListenerOptions;\n }> = [];\n\n const addListener = (\n target: EventTarget,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions\n ) => {\n target.addEventListener(event, handler, options);\n listeners.push({ target, event, handler, options });\n };\n\n // Delay trigger\n if (typeof delay === \"number\" && delay > 0) {\n const timer = setTimeout(() => {\n checkAndOpen(\"delay\");\n }, delay);\n timers.push(timer);\n }\n\n // Scroll trigger (throttled with requestAnimationFrame for performance)\n if (typeof scrollPercent === \"number\") {\n const targetPercent = scrollPercent;\n let scrollTicking = false;\n\n const checkScrollPercent = () => {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const docHeight = document.documentElement.scrollHeight;\n const windowHeight = window.innerHeight;\n const scrollableHeight = docHeight - windowHeight;\n\n if (scrollableHeight <= 0) return;\n\n const currentPercent = (scrollTop / scrollableHeight) * 100;\n if (currentPercent >= targetPercent) {\n checkAndOpen(\"scrollPercent\");\n }\n scrollTicking = false;\n };\n\n const handleScroll = () => {\n if (!scrollTicking) {\n scrollTicking = true;\n // Use requestAnimationFrame for throttling if available, otherwise execute directly\n if (typeof requestAnimationFrame === \"function\") {\n requestAnimationFrame(checkScrollPercent);\n } else {\n checkScrollPercent();\n }\n }\n };\n\n addListener(window, \"scroll\", handleScroll, { passive: true });\n // Check immediately in case already scrolled\n checkScrollPercent();\n }\n\n // Exit intent trigger (skip on touch devices)\n if (exitIntent && !isTouchDevice()) {\n const threshold = exitIntentThreshold ?? DEFAULT_EXIT_INTENT_THRESHOLD;\n\n const handleMouseOut = (e: Event) => {\n const mouseEvent = e as MouseEvent;\n // Only trigger when mouse leaves through the top\n if (mouseEvent.clientY <= threshold) {\n checkAndOpen(\"exitIntent\");\n }\n };\n\n addListener(document, \"mouseout\", handleMouseOut);\n }\n\n // Inactivity trigger (uses separate ref to avoid array manipulation issues)\n if (typeof inactivity === \"number\" && inactivity > 0) {\n const resetInactivityTimer = () => {\n if (inactivityTimerRef.current) {\n clearTimeout(inactivityTimerRef.current);\n }\n inactivityTimerRef.current = setTimeout(() => {\n checkAndOpen(\"inactivity\");\n }, inactivity);\n };\n\n // Start the timer\n resetInactivityTimer();\n\n // Reset on user activity (passive listeners for better performance)\n const activityEvents = [\"mousemove\", \"keydown\", \"scroll\", \"click\", \"touchstart\"];\n activityEvents.forEach((event) => {\n addListener(document, event, resetInactivityTimer, { passive: true });\n });\n }\n\n // Cleanup\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n if (inactivityTimerRef.current) {\n clearTimeout(inactivityTimerRef.current);\n inactivityTimerRef.current = null;\n }\n listeners.forEach(({ target, event, handler, options }) => {\n target.removeEventListener(event, handler, options);\n });\n };\n }, [\n // Use primitive values as dependencies to avoid re-running on object reference changes\n delay,\n scrollPercent,\n exitIntent,\n exitIntentThreshold,\n inactivity,\n patternsKey, // Serialized patterns for stable comparison\n minimumWidth,\n isActive,\n hasInteracted,\n sessionKey,\n checkAndOpen,\n ]);\n}\n","/*! Copyright (c) 2026, XAPPmedia */\nimport { useEffect } from \"react\";\n\n/**\n * Body attribute a host page sets to declare \"a form widget already *is* this page\".\n *\n * The standalone contact/booking page (`@xapp/contact-app`, serving contact.xapp.ai,\n * book.xapp.ai and sche.dule.pro) renders a docked form as its whole content, then injects\n * the chat widget on top when the URL carries `?chatWidgetKey=`. That widget arrives with\n * the App's Studio-configured ActionBar, which offers a Contact button and a Book button\n * into the very form already filling the screen.\n *\n * The page has to say so, because nothing the widget can observe would tell it. A docked\n * form in the DOM is not the same claim - plenty of pages embed one *and* want a separate\n * one from the bar.\n *\n * The reader is `@xapp/chat-widget`'s `useIsFormPage`, and its stylesheet also keys the\n * form-widget side button off this. Those packages ship separately, so this string is the\n * contract between them - the same arrangement `[data-xapp-form-side-button]` already uses.\n * Do not rename it on one side only. XappMedia/chat-widget#1626.\n */\nexport const FORM_PAGE_ATTRIBUTE = \"data-xapp-form-page\";\n\n/**\n * Companion reference count, so two markers on one page do not clear each other on the way\n * out. Mirrors the `data-xapp-action-bar-count` the chat widget keeps for the same reason.\n */\nexport const FORM_PAGE_COUNT_ATTRIBUTE = \"data-xapp-form-page-count\";\n\nfunction readCount(): number {\n const raw = parseInt(document.body.getAttribute(FORM_PAGE_COUNT_ATTRIBUTE) || \"0\", 10);\n return Number.isNaN(raw) ? 0 : raw;\n}\n\n/**\n * Declares this page to be a form page, and returns the release for it.\n *\n * Imperative form of {@link useFormPageMarker}, for pages that are not React.\n */\nexport function markFormPage(): () => void {\n if (typeof document === \"undefined\" || !document.body) {\n return () => undefined;\n }\n\n document.body.setAttribute(FORM_PAGE_COUNT_ATTRIBUTE, String(readCount() + 1));\n document.body.setAttribute(FORM_PAGE_ATTRIBUTE, \"true\");\n\n let released = false;\n return () => {\n // Idempotent: a double release must not drop the count below what other markers hold.\n if (released) {\n return;\n }\n released = true;\n\n const remaining = Math.max(0, readCount() - 1);\n if (remaining === 0) {\n document.body.removeAttribute(FORM_PAGE_ATTRIBUTE);\n document.body.removeAttribute(FORM_PAGE_COUNT_ATTRIBUTE);\n } else {\n document.body.setAttribute(FORM_PAGE_COUNT_ATTRIBUTE, String(remaining));\n }\n };\n}\n\n/**\n * Declares this page to be a form page for as long as the component is mounted.\n *\n * @param enabled pass false to render without making the claim\n */\nexport function useFormPageMarker(enabled = true): void {\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n return markFormPage();\n }, [enabled]);\n}\n","/**\n * The div the widget renders into.\n *\n * App.tsx looks this up first and only appends its own if the host page did not already\n * provide one -- which is what makes embedding possible at all.\n */\nexport const APP_ELEMENT_ID = \"xapp-form-widget\";\n\n/**\n * Class the host page puts on its own `#xapp-form-widget` div to opt into inline rendering.\n *\n * ```html\n * <div id=\"xapp-form-widget\" class=\"embedded\" style=\"width: 400px; height: 600px;\"></div>\n * ```\n */\nexport const EMBEDDED_CLASS = \"embedded\";\n\n/**\n * Namespaced alias for {@link EMBEDDED_CLASS}.\n *\n * `embedded` is short enough that a host page's own CSS framework may already style it;\n * this gives those customers a class that cannot collide.\n */\nexport const XAPP_EMBEDDED_CLASS = \"xapp-embedded\";\n\n/**\n * Is the widget rendering inside a container the host page laid out and sized itself?\n *\n * Embedded, the customer's div is the frame: the widget must fill it rather than open a\n * fixed, full-viewport modal over the page.\n *\n * @param element - the container to inspect; defaults to looking up {@link APP_ELEMENT_ID}.\n */\nexport function isEmbedded(element?: Element | null): boolean {\n const host =\n element ??\n (typeof document !== \"undefined\" ? document.getElementById(APP_ELEMENT_ID) : null);\n\n if (!host) {\n return false;\n }\n\n // classList, not className.includes -- a customer class of `not-embedded-at-all` must\n // not opt them in.\n return host.classList.contains(EMBEDDED_CLASS) || host.classList.contains(XAPP_EMBEDDED_CLASS);\n}\n","/**\n * Remembers the last click on the page between the bundle running and the form mounting.\n *\n * The form mounts on window load, and only then knows its triggerSelector, so a visitor who\n * clicks the customer's \"Schedule\" button in that gap would otherwise get nothing and think the\n * button is dead. Form asks for that click on mount and opens if it matched.\n */\n\n// Long enough for a slow page's load event, short enough that a click the visitor has\n// forgotten about does not pop the form open later.\nexport const EARLY_CLICK_MAX_AGE_MS = 10000;\n\nlet lastClick: { readonly target: Element; readonly at: number } | undefined;\n\nlet recording = false;\n\nconst record = (event: MouseEvent) => {\n if (event.target instanceof Element) {\n lastClick = { target: event.target, at: Date.now() };\n }\n};\n\nexport function startRecordingEarlyClicks(): void {\n if (recording) {\n return;\n }\n recording = true;\n // Capture phase, so a host page handler that stops propagation cannot hide the click.\n document.addEventListener(\"click\", record, true);\n}\n\n/**\n * Stops recording and returns the last recorded click target, if it is recent enough.\n */\nexport function takeEarlyClick(): Element | undefined {\n document.removeEventListener(\"click\", record, true);\n recording = false;\n\n const click = lastClick;\n lastClick = undefined;\n\n if (!click || Date.now() - click.at > EARLY_CLICK_MAX_AGE_MS) {\n return undefined;\n }\n return click.target;\n}\n","import React, { FC, useCallback, useEffect, useMemo, useState } from \"react\";\nimport { FormWidgetTheme } from \"@xapp/stentor-form-widget-channel\";\n\nimport { FormWidgetConfig } from \"../../config\";\nimport { log, err } from \"../../utils\";\nimport { SearchStoreProvider, useSearchDispatch, useSearchState } from \"../../store\";\nimport { ModalDialog } from \"../ModalDialog\";\nimport { FormWidget } from \"../FormWidget\";\nimport { WidgetStylesheet } from \"../WidgetStylesheet\";\nimport { classNames } from \"../../constants/variables\";\nimport SideButton from \"../SideButton/SideButton\";\nimport { useAutoOpenTriggers, hasAutoOpenTriggers, DEFAULT_SESSION_KEY } from \"../../hooks\";\nimport { isEmbedded } from \"../../utils/isEmbedded\";\nimport { takeEarlyClick } from \"../../utils/earlyClicks\";\n\nimport { StentorApi } from \"../../api\";\n\nimport styles from \"./Form.module.scss\";\n\nexport interface FormProps {\n readonly config: FormWidgetConfig;\n readonly theme?: FormWidgetTheme;\n /**\n * Optional elements that will act as the button to enable the modal search.\n */\n readonly button?: JSX.Element | string;\n readonly buttonElementLookup?: () => Promise<HTMLElement>;\n}\n\n/**\n * FormContainer is the main entry point for the Form widget. It provides the context for the\n * form and handles the button click events.\n * It is a wrapper around the Form component.\n */\nexport const FormContainer: FC<FormProps> = (props) => {\n return (\n <SearchStoreProvider>\n <Form\n config={props.config}\n theme={props.theme}\n button={props.button}\n buttonElementLookup={props.buttonElementLookup}\n />\n </SearchStoreProvider>\n );\n};\n\n/**\n * Form is the main component for the Form widget. It provides the context for the\n * form and handles the button click events.\n */\n/**\n * Options that can be passed when programmatically opening the form\n */\nexport interface OpenFormOptions {\n /**\n * Label of a chip to auto-select after the form loads.\n * If the first step of the form contains chips, the form will\n * automatically click the chip matching this label.\n */\n preselectChipLabel?: string;\n}\n\nexport const Form: FC<FormProps> = (props) => {\n const { config, theme } = props;\n\n const dispatch = useSearchDispatch();\n\n const { active, minimized } = useSearchState();\n\n // Store preselectChipLabel when form is opened programmatically\n const [preselectChipLabel, setPreselectChipLabel] = useState<string | undefined>();\n\n // Track if user has interacted with the form (for auto-open triggers)\n const [hasInteracted, setHasInteracted] = useState(false);\n\n // Track if the form was opened by an auto-trigger (vs manually)\n const [openedByTrigger, setOpenedByTrigger] = useState(false);\n\n // The host page opts into inline rendering by pre-creating `#xapp-form-widget` with the\n // `embedded` class and sizing it itself; App.tsx's renderWidget then renders into that\n // div rather than appending a floating one.\n //\n // Read once at mount, not per render: renderWidget guarantees the element exists before\n // React mounts into it, so there is nothing to wait for, and re-querying the document on\n // every render would do it on every keystroke. It also pins the layout for the session --\n // a host page whose CSS framework or A/B tool churns classes cannot flip the widget\n // between an inline form and a full-screen modal mid-conversation.\n const [embedded] = useState(isEmbedded);\n\n // `autoOpen.enabled` with no behavior-based triggers configured means \"open\n // immediately on load\" (docked, no close button). If triggers ARE configured,\n // `enabled` only turns the feature on -- the widget must wait for a trigger\n // to fire (which sets `active` via handleAutoOpen) rather than bypassing it.\n const immediateAutoOpen = !!config.autoOpen?.enabled && !hasAutoOpenTriggers(config.autoOpen);\n\n // Open-only, never a toggle: a host page can wire its own buttons to our side button while\n // Studio also binds them via triggerSelector (squeaksservices.com did both), and a <button>\n // gets focus and click from one mouse press. Toggles from any two of those cancel out.\n const openModal = useCallback(\n (options?: OpenFormOptions) => {\n // Store the preselect label if provided\n if (options?.preselectChipLabel) {\n setPreselectChipLabel(options.preselectChipLabel);\n }\n dispatch({\n type: \"open-modal-state\",\n });\n },\n [dispatch]\n );\n\n // Event handler for DOM events (onclick, onfocus)\n const handleFocus = useCallback(() => {\n openModal();\n }, [openModal]);\n\n // API function that accepts options (for window.xafwControl.openForm)\n const openFormWithOptions = useCallback(\n (options?: OpenFormOptions) => {\n openModal(options);\n },\n [openModal]\n );\n\n const formStatus = useCallback(() => {\n return { active, minimized };\n }, [active, minimized]);\n\n const api = useMemo(() => {\n return StentorApi.getApi({\n key: config.api.key,\n url: config.api.url,\n // Must match the config FormWidget passes below: getApi caches per url+key+intentId, so\n // this and FormWidget's call share one instance only if their intentId agrees. Form also\n // sends FORM_CLOSE from here, which needs the right intentId for overrideKey.\n intentId: config.intentId,\n // Carried through so the preview guarantee lives in one place.\n demoMode: config.api.demoMode,\n // prefetchQuery: config.autoGreeting\n });\n }, [config]);\n\n const handleClose = useCallback(() => {\n // Clear preselectChipLabel when form closes\n setPreselectChipLabel(undefined);\n // Mark as interacted to prevent auto-open triggers from firing again\n setHasInteracted(true);\n // Only persist dismissal if the form was opened by an auto-trigger\n // This prevents manual opens from blocking future auto-triggers\n if (openedByTrigger) {\n try {\n const sessionKey = config.autoOpen?.sessionKey || DEFAULT_SESSION_KEY;\n sessionStorage.setItem(sessionKey, \"true\");\n } catch {\n // Private browsing or sessionStorage not available - ignore\n }\n setOpenedByTrigger(false);\n }\n dispatch({\n type: \"new-search\",\n });\n dispatch({\n type: \"set-modal-state\",\n active: false,\n minimized: false,\n sendRequest: false,\n });\n\n api.channelActionRequest({ data: { result: {}, step: \"\", form: \"\" } }, \"FORM_CLOSE\").then(\n (response) => {\n log(`ACTION Request (FORM_CLOSE). Data: Response: ${JSON.stringify(response)}`);\n }\n );\n }, [api, config.autoOpen?.sessionKey, dispatch, openedByTrigger]);\n\n // Callback for auto-open triggers\n const handleAutoOpen = useCallback(() => {\n setOpenedByTrigger(true);\n dispatch({\n type: \"set-modal-state\",\n active: true,\n minimized: false,\n sendRequest: true,\n });\n }, [dispatch]);\n\n // Set up auto-open triggers (delay, scroll, exit intent, inactivity)\n useAutoOpenTriggers({\n config: config.autoOpen,\n isActive: active,\n onOpen: handleAutoOpen,\n hasInteracted,\n });\n\n // This sets up the button\n useEffect(() => {\n const elements = document.getElementsByClassName(\n classNames.XAPP_FORM_BUTTON\n ) as HTMLCollectionOf<HTMLElement>;\n\n // we found the button by class\n if (elements.length) {\n log(`Assigning ${elements.length} button(s) by class: ${classNames.XAPP_FORM_BUTTON}`);\n\n Array.from(elements).forEach((element) => {\n element.onclick = handleFocus;\n element.onfocus = handleFocus;\n });\n } else {\n // we didn't find the button by class, let's try by id\n const el = document.getElementById(classNames.XAPP_FORM_BUTTON);\n if (el) {\n log(`Assigning one button by id: ${classNames.XAPP_FORM_BUTTON})}`);\n el.onclick = handleFocus;\n el.onfocus = handleFocus;\n } else {\n log(`Cannot assign buttons by class or id: ${classNames.XAPP_FORM_BUTTON})}`);\n }\n }\n\n window.xafwControl = { openForm: openFormWithOptions, formStatus };\n }, [formStatus, handleFocus, openFormWithOptions]);\n\n // Opens the form from existing elements on the customer's site matched by\n // config.triggerSelector (e.g. a dead CTA left over from a prior integration), so the widget\n // can be installed without the customer editing anything. Additive to (never replaces) the\n // xapp-form-button binding above.\n //\n // One capture-phase listener on the document rather than one per element: it covers\n // elements the page adds later, clicks on an element's children, and host handlers that\n // stop propagation, with nothing to watch or time out.\n useEffect(() => {\n const triggerSelector = config.triggerSelector;\n // Taken whether or not a selector is configured, which also stops the recorder.\n const earlyClick = takeEarlyClick();\n if (!triggerSelector) {\n return undefined;\n }\n\n try {\n document.querySelector(triggerSelector);\n } catch (e) {\n // An invalid selector can never become valid -- log once rather than on every click.\n err(`Invalid triggerSelector \"${triggerSelector}\": ${e}`);\n return undefined;\n }\n\n if (earlyClick?.closest(triggerSelector)) {\n log(`Opening for a triggerSelector \"${triggerSelector}\" click made before the form loaded`);\n handleFocus();\n }\n\n const onClick = (event: MouseEvent) => {\n const target = event.target instanceof Element ? event.target.closest(triggerSelector) : null;\n if (!target) {\n return;\n }\n // Only suppress navigation for a literal dead link (the common leftover-CTA\n // case) -- never stopPropagation, never overwrite an existing listener/onclick.\n if (\n target instanceof HTMLAnchorElement &&\n (target.getAttribute(\"href\") === \"#\" || target.getAttribute(\"href\") === \"\")\n ) {\n event.preventDefault();\n }\n handleFocus();\n };\n\n document.addEventListener(\"click\", onClick, true);\n\n return () => {\n document.removeEventListener(\"click\", onClick, true);\n };\n }, [config.triggerSelector, handleFocus]);\n\n let button: JSX.Element;\n\n // if the passed in a button, use it\n if (props.button) {\n if (typeof props.button === \"object\") {\n // If they provided a button, we add the onClick\n button = (\n <props.button.type\n {...props.button.props}\n onClick={handleFocus}\n onFocus={handleFocus}\n />\n );\n } else {\n // We are using an ID for the button, just put in a placeholder\n button = <></>;\n }\n } else {\n // no button prop provided so use default search container\n button = <></>;\n }\n\n return (\n <div className={styles.xapp_form}>\n <WidgetStylesheet theme={theme} />\n\n {/*\n Hidden when embedded: the side button is a `position: fixed` page-edge tab\n that opens the floating modal, so it would both escape the customer's\n container and offer a second way into a form already on the page.\n */}\n {config.sideButtonLabel && !immediateAutoOpen && !embedded && (\n <SideButton\n onClick={handleFocus}\n label={config.sideButtonLabel}\n position={theme?.sideButton?.position}\n hidden={config.hideSideButton}\n />\n )}\n\n {button}\n\n {(active || immediateAutoOpen) && (\n <ModalDialog\n disableBackdrop={immediateAutoOpen}\n embedded={embedded}\n onClose={handleClose}>\n <FormWidget\n docked={immediateAutoOpen}\n embedded={embedded}\n openedByTrigger={openedByTrigger}\n config={config}\n preselectChipLabel={preselectChipLabel}\n onPreselectChipUsed={() => setPreselectChipLabel(undefined)}\n />\n </ModalDialog>\n )}\n </div>\n );\n};\n","import { SearchDispatch } from \"./SearchDispatch\";\nimport { useSearchStore } from \"./useSearchStore\";\n\nexport function useSearchDispatch(): SearchDispatch {\n return useSearchStore()[1];\n}\n","\n\nexport function getBasePathFromWidgetSource(): { path: string, key?: string } {\n const xappScriptNode = document?.getElementById(\"xapp-form-js\") as HTMLScriptElement | undefined;\n const path = getBasePath(xappScriptNode?.src);\n return path;\n}\n\n// https://dev-widget.xapp.media/xapp-form-widget.js?key=f3af5f1f-cfc1-4ca7-a1e9-a411288d5190\n\nexport function getBasePath(path?: string): { path: string, key?: string } {\n if (!path) {\n return { path: \"\" };\n }\n const lastPathSep = path.lastIndexOf(\"/\");\n let result = \"\";\n if (lastPathSep >= 0) {\n result = path.substr(0, lastPathSep);\n }\n\n const url = new URL(path);\n const params = new URLSearchParams(url.search);\n const key = params.get(\"key\") || \"\";\n\n return { path: result, key };\n}","import { FormWidgetEnv, FormWidgetTheme } from \"@xapp/stentor-form-widget-channel\";\n\nimport { FormWidgetConfig, getBasePathFromWidgetSource } from \"../config\";\n\n/**\n * Parses the widget environment to extract the configuration and theme.\n *\n * @param env\n * @returns An array containing the configuration and theme, config in index 0 and theme in index 1.\n */\nexport function parseWidgetEnv(env: FormWidgetEnv): [FormWidgetConfig, FormWidgetTheme] {\n // Use accountKey if provided, otherwise try to get key from script tag URL\n const key = env.connection?.accountKey || getBasePathFromWidgetSource().key || \"\";\n\n const config: FormWidgetConfig = {\n api: {\n url: env.connection?.serverUrl || \"\",\n key,\n },\n\n suggestionsUrl: env.autocompleteSuggestionsUrl,\n autoGreeting: env.autoGreeting || \"contact us\",\n intentId: env.intentId,\n sideButtonLabel: env.sideButtonLabel,\n hideSideButton: env.hideSideButton,\n googleMapsApiKey: env.googleMapsApiKey,\n mapsBaseUrl: env.mapsBaseUrl,\n autoOpen: env.autoOpen,\n disabled: env.disabled,\n trustedForm: env.trustedForm,\n triggerSelector: env.triggerSelector,\n ga4MeasurementId: env.ga4MeasurementId,\n };\n\n const theme = env.theme;\n\n return [config, theme];\n}\n","import {\n FormWidgetTheme,\n PartnerFormFraming,\n PartnerFormStyle,\n} from \"@xapp/stentor-form-widget-channel\";\n\n/**\n * The reserved preset name that forces the partner style off for a single form,\n * whatever the partner record says. A permanent per-form exception.\n */\nexport const STYLE_PRESET_NONE = \"none\";\n\nexport interface FormStyleContext {\n /**\n * True only for the stand-alone booking page. A form embedded on the customer's\n * own website is the customer's own chrome -- the preset must never apply there,\n * or every embedded form belonging to a styled partner would silently change\n * appearance.\n */\n readonly standalone?: boolean;\n /**\n * The form's own tri-state preset -- see FormWidgetEnv.stylePreset.\n */\n readonly stylePreset?: string;\n /**\n * Canonical code of the partner the form belongs to.\n */\n readonly partnerCode?: string;\n /**\n * The customer's own theme, which the preset merges over.\n */\n readonly customerTheme?: FormWidgetTheme;\n /**\n * Looks a named style bundle up. API-served, with a code fallback.\n */\n readonly getPresetStyle?: (preset: string) => PartnerFormStyle | undefined;\n}\n\nexport interface ResolvedFormStyle {\n /**\n * The preset that applied, or undefined when the form is left alone.\n */\n readonly preset?: string;\n /**\n * The theme to hand the widget: the customer's, with the preset merged over it.\n */\n readonly theme?: FormWidgetTheme;\n /**\n * The partner chrome to draw around the form, if the preset defines any.\n */\n readonly framing?: PartnerFormFraming;\n}\n\n/**\n * Works out which named style bundle applies to a form, or undefined for none.\n *\n * `stylePreset` is tri-state and overrides the partner record either way:\n * absent inherits `formStyle.enabled`, a name forces on, \"none\" forces off.\n */\nexport function resolveStylePresetName(context: FormStyleContext): string | undefined {\n const { standalone, stylePreset, partnerCode, getPresetStyle } = context;\n\n if (!standalone) {\n return undefined;\n }\n\n if (stylePreset === STYLE_PRESET_NONE) {\n return undefined;\n }\n\n if (stylePreset) {\n return stylePreset;\n }\n\n if (!partnerCode) {\n return undefined;\n }\n\n return getPresetStyle?.(partnerCode)?.enabled ? partnerCode : undefined;\n}\n\n/**\n * Resolves the preset and applies it, returning the theme the widget should use and\n * the framing it should draw.\n */\nexport function resolveFormStyle(context: FormStyleContext): ResolvedFormStyle {\n const { customerTheme, getPresetStyle } = context;\n\n const preset = resolveStylePresetName(context);\n const style = preset ? getPresetStyle?.(preset) : undefined;\n\n if (!style) {\n return { theme: customerTheme };\n }\n\n return {\n preset,\n theme: mergeFormWidgetTheme(customerTheme, style.theme),\n framing: style.framing,\n };\n}\n\n/**\n * Merges a preset theme *over* a customer theme: the preset wins where it defines a\n * value, and the customer's values survive everywhere the preset is silent. Nested\n * groups (font, text, card, standAlone, ...) merge rather than replace, so a preset\n * that only sets `font.fontFamily` keeps the customer's `font.link`.\n */\nexport function mergeFormWidgetTheme(\n base?: FormWidgetTheme,\n override?: FormWidgetTheme\n): FormWidgetTheme | undefined {\n if (!override) {\n return base;\n }\n\n if (!base) {\n return override;\n }\n\n return deepMerge(\n base as unknown as PlainObject,\n override as unknown as PlainObject\n ) as FormWidgetTheme;\n}\n\ntype PlainObject = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction deepMerge(base: PlainObject, override: PlainObject): PlainObject {\n const merged: PlainObject = { ...base };\n\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined) {\n continue;\n }\n\n const existing = merged[key];\n merged[key] =\n isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;\n }\n\n return merged;\n}\n","import { PartnerFormStyle } from \"@xapp/stentor-form-widget-channel\";\n\n/**\n * CostGuide's approved form look, as a named style bundle.\n *\n * ONE definition, exported so every consumer reads the same values: the code\n * fallback in contact-app's partner registry, and the Storybook story that shows\n * the look. Duplicating it drifts -- the story and the registry had already\n * diverged on the button colours, which is how a CostGuide-preset form ended up\n * rendering a stock magenta Continue button inside a teal frame.\n *\n * Once `public.partnerBranding.formStyle` ships (XappMedia/stentor-api#5753) the\n * API-served bundle wins and this is only reached when that fetch fails.\n *\n * Colour notes, all from the approved design:\n * - #1aacbe is the frame border, the buttons and the selected chip/date state.\n * - #22a2b4 is the tab -- deliberately a DIFFERENT teal from the border.\n * - #eef8fa is the card interior the framed step sits on.\n */\nexport const COST_GUIDE_FORM_STYLE: PartnerFormStyle = {\n enabled: true,\n theme: {\n // No visible container. The widget root paints a border in this colour, and with the\n // frame and tab gone it was the last box left around a form that should sit flat on the\n // page -- their own form has no outer border at all. Transparent rather than removing\n // the rule, so the layout keeps the same box metrics.\n borderColor: \"transparent\",\n // The approved design's inputs and buttons are slightly squarer than stock.\n // The frame's own card is square regardless of this -- see FormFrame.\n borderRadius: \"8px\",\n // White, not the pale teal card interior. That tint existed to separate the framed card\n // from the page behind it; with no frame it just makes the form look like a panel.\n backgroundColor: \"#ffffff\",\n // The step header was a teal bar with white text, which read as a tab even once the real\n // tab was gone. On white with dark text it reads as a heading, which is what it is.\n headerBackgroundColor: \"#ffffff\",\n headerTextColor: \"#1c3f47\",\n // CostGuide's own advance button is orange, not teal -- `.btn-orange {background:#fb9b26}`\n // in their main.css, which `.btn-next` uses. Teal was our reading of their older design.\n primaryButtonColor: \"#fb9b26\",\n primaryButtonTextColor: \"#ffffff\",\n // BOTH buttons, because a step that sets `nextLabel` routes to the SECONDARY one -- and\n // every step of the CostGuide form sets one (\"Next: Contact Info\", \"Next: book your\n // estimate\"). Setting only the primary leaves the button the visitor actually presses\n // its stock magenta.\n secondaryButtonColor: \"#fb9b26\",\n secondaryButtonTextColor: \"#ffffff\",\n text: {\n color: \"#1c3f47\",\n // The fill was never claimed here, so it fell through to the customer's own theme --\n // Erie ships `rgba(0, 0, 0, 0.06)`, a grey wash that reads as disabled next to\n // CostGuide's white fields. A pale tint of their own palette instead. The hover and\n // focus shades derive from this automatically (`darken(backgroundColor, 3)`).\n //\n // Not white: without a border on the input a white field is invisible on the white\n // form. Their fields are white WITH a 1px border, which we cannot match until the\n // input border is themable -- `border: 0 !important` is hardcoded in\n // FormFieldTextInput.module.scss.\n backgroundColor: \"#ffffff\",\n // Outlined fields, now that the border is themable. Their own:\n // `.main-form input:focus {border:2px solid #92dae1}`, and the resting border is the\n // same family a shade lighter. White fill is safe once there is a border to read.\n borderColor: \"#cfe3e7\",\n borderWidth: \"1px\",\n borderColorFocus: \"#92dae1\",\n },\n chips: {\n // Both states. Only the selected pair was set, so an UNSELECTED chip fell through to\n // the customer's own theme -- on book.xapp.ai that rendered American Dream's maroon\n // pills inside an otherwise entirely teal form. A chip spends most of its life\n // unselected, so it was the resting state that looked wrong.\n //\n // Same class as the stock magenta Continue button this file's header records: a\n // themable surface the preset does not claim is a surface the customer keeps.\n backgroundColor: \"#d6eef2\",\n color: \"#1c3f47\",\n backgroundColorSelected: \"#1aacbe\",\n colorSelected: \"#ffffff\",\n },\n date: {\n backgroundColorSelected: \"#1aacbe\",\n },\n // Their advance button is chunky: 20px bold on a 10px radius with a heavy drop shadow\n // (`.btn-next {padding:17px 25px; font-size:20px; font-weight:700; border-radius:10px;\n // box-shadow:0 4px 5px 4px rgba(0,0,0,.15)}`). Ours was a stock MUI button wearing\n // their orange -- right colour, half the presence.\n button: {\n fontSize: \"20px\",\n fontWeight: \"700\",\n padding: \"17px 25px\",\n borderRadius: \"10px\",\n boxShadow: \"0 4px 5px 4px rgba(0, 0, 0, 0.15)\",\n },\n\n // Back and submit on one row, as theirs are -- the circle on the left, the button beside\n // it -- rather than submit centred above with back stranded underneath.\n finalButtonPlacement: \"inline\",\n\n // Their step heading: centred, 24px, dark teal (`.main-form .ms-title {font-size:24px;\n // color:#174146}`). Ours was left-aligned body text, which read as a label.\n stepTitle: {\n align: \"center\",\n fontSize: \"24px\",\n fontWeight: \"700\",\n color: \"#174146\",\n },\n\n // An icon-only circle with an arrow, which is what their back control is --\n // `.btn-back svg {fill:#a0cdd3}`, hover `#174146` on both the ring and the arrow.\n backButtonVariant: \"icon\",\n backButton: {\n color: \"#a0cdd3\",\n borderColor: \"#a0cdd3\",\n colorHover: \"#174146\",\n // 1px read as hairline next to a 20px bold button beside it.\n borderWidth: \"2px\",\n iconStroke: \"0.8px\",\n },\n\n font: {\n // Poppins, which is what their own page loads: `family=Poppins:300,400,700` on\n // match.costguide.com. Montserrat came from their embed loader, which still requests\n // it -- but the page the visitor compares us against is set in Poppins.\n fontFamily: \"Poppins, Arial, Verdana, sans-serif\",\n link: \"https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;700&display=swap\",\n },\n standAlone: {\n backgroundColor: \"rgb(243, 248, 251)\",\n },\n externalWidget: {\n // Their booking embed is tall; without this the page jumps as it mounts.\n minHeight: \"600px\",\n },\n },\n // No framing. There was a \"BOOK YOUR ESTIMATE\" tab and a bordered card around every step,\n // matching CostGuide's design as it stood when this preset was written. Their own form no\n // longer has either (match.costguide.com, checked 2026-09-20): it is a plain card with the\n // fields on it. Ours read as a box inside a box -- the widget's own rounded container, then\n // the tab, then a second squared border inside that.\n //\n // FormDisplay renders `framing ? <FormFrame> : stepDisplay`, so leaving this off is what\n // removes the tab AND the inner card; there is no separate switch for either.\n};\n"],"names":["jsxRuntime","require$$0","react","require$$1","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","__generator","body","f","y","t","_","label","sent","trys","ops","g","Object","create","Iterator","prototype","verb","Symbol","iterator","this","n","v","op","TypeError","call","pop","length","push","__spreadArray","to","from","pack","ar","i","l","Array","slice","concat","SuppressedError","reduce","prev","cur","index","UTM_PARAMETERS","CLICK_ID_PARAMETERS","ATTRIBUTION_PARAMETERS","toolResultToValue","text","content","filter","part","type","map","join","isError","ok","message","JSON","parse","_a","HomeownerMcpClient","mcpUrl","fetchImpl","nextId","fetch","undefined","callTool","name","args","response","Error","method","headers","Accept","stringify","jsonrpc","id","params","arguments","status","json","error","code","INTERNAL_TRAFFIC_VALUE","COUNT_ATTRIBUTE$1","RESTORE_ATTRIBUTE","PINNED_PROPERTIES","readCount$1","count","Number","getAttribute","isFinite","lockBodyScroll","document","window","restorePoint","inlineStyles","styles","property","style","getPropertyValue","scrollY","pageYOffset","captureRestorePoint","setAttribute","position","top","left","right","width","overflow","String","released","remaining","removeAttribute","serialized","parsed","takeRestorePoint","forEach","setProperty","removeProperty","scrollTo","HEIGHT_PROPERTY","OFFSET_TOP_PROPERTY","KEYBOARD_INSET_PROPERTY","COUNT_ATTRIBUTE","readCount","root","publish","viewport","visualViewport","height","offsetTop","layoutHeight","innerHeight","rawInset","Math","max","inset","round","trackVisualViewport","documentElement","frame","onChange","requestAnimationFrame","addEventListener","removeEventListener","cancelAnimationFrame","clear","readInset","getComputedStyle","parseFloat","scrollIntoViewIfPossible","element","scrollIntoView","block","behavior","uuid","d","Date","getTime","replace","c","r","random","floor","toString","VISITOR_ID_STORAGE_KEY","VISIT_STORAGE_KEY","ID","fallback","w","__xappVisitIdentity","read","key","localStorage","getItem","write","setItem","asId","test","visitorId","stored","page","IconButton_1","props","Icon","icon","jsx","tabIndex","className","onClick","children","MessageBubble_1","SuggestionsGroupHeading_1","addTestLeadAttribute_1","attributes","sessionStorage","isTestLeadSession","readInternalTrafficMark_1","stripQueryString_1","url","URL","origin","pathname","useBodyScrollLock_1","enabled","useEffect","useScrollFocusedIntoView_1","lastInset","onFocusIn","event","target","onViewportChange","opened","activeElement","useVisualViewportProperties_1","uuid_1","visitIdentity_1","now","current","raw","visit","at","parseVisit","visitId","visitorId_1","DEFAULT_CONFIG","extractUtmParameters","extractClickIds","customParameterPrefix","persistToLocalStorage","persistenceDays","preferUrlParameters","storageKeyPrefix","scope","encodeURIComponent","isValidParameterValue","getStoredTrackingParameters","parameters","prefix","param","data","expires","removeItem","keys","storageKeys","startsWith","paramName","getAllTrackingParameters","config","location","href","finalConfig","__assign","urlParameters","urlObj","console","warn","searchParams","get","extractTrackingParametersFromUrl","storedParameters","expirationTime","entries","storeTrackingParameters","getCurrentDateString","toISOString","log","_i","xaLogLevel","err","isCarousel","display","isList","isForm","RootReducer","state","action","query","responseQuery","responseIntentId","intentId","context","active","minimized","sendRequest","x","throwBadKind","DEFAULT_SEARCH_STATE","DEFAULT_SEARCH_STORE","SearchStoreContext","React","createContext","SearchStoreProvider","reducer","useReducer","initialState","_jsx","Provider","useSearchStore","useContext","useSearchState","styleInject","css","ref","insertAt","head","getElementsByTagName","createElement","firstChild","insertBefore","appendChild","styleSheet","cssText","createTextNode","ModalDialog","embedded","useBodyScrollLock","useVisualViewportProperties","useScrollFocusedIntoView","_jsxs","disableBackdrop","onClose","DROPPED_AFTER_FINAL","API_INSTANCES","Map","DEMO_READ_REQUEST_TYPES","Set","StentorApi","sessionSent","prefetchSemaphore","responseCache","defineProperty","getCachedTrackingParameters","cachedTrackingParams","ts","trackingScope","getApi","cacheKey","demoMode","apiCacheKey","existing","api","set","prefetchQuery","prefetch","launchRequest","send","rawQuery","platform","channel","intentRequest","request","channelActionRequest","_this","isFinal","final","session","hadFinal","overrideKey","catch","trackEvent","eventType","trackingUrl","getTrackingUrl","requestBody","events","mode","statusText","processed","error_1","trackEventBeacon","widgetType","keepalive","parsedUrl","match","resetSession","visitSession","sessionId","userId","getCachedResponse","hit","_c","has","newSession","_b","host","toLowerCase","referrer","stripQueryString","rwgToken","merchantId","environment","enablePreferredTime","service","urlParams","URLSearchParams","search","placeId","trackingParams","assign","addTestLeadAttribute","isNewSession","Authorization","waitTimeInMs","setTimeout","resolver","currentTime","start","fetchResponse","_d","finally","getActionLabel","title","SearchWidgetConfigContext","suggestionsUrl","isVoiceEnabled","autoGreeting","useLoading","useState","setState","mounted","useRef","useCallback","run","shift","runCounter","delta","useMemo","loading","TRUSTED_FORM_CERT_FIELD","TRUSTED_FORM_PING_FIELD","useTrustedForm","scriptUrl","isValidTrustedFormUrl","querySelector","script","async","src","onerror","certInput","pingInput","getCookie","cookie","escaped","RegExp","decodeURIComponent","GA4_LEAD_EVENT_NAME","isValidGa4MeasurementId","trim","hasGlobalPrivacyControlOptOut","navigator","globalPrivacyControl","sendGa4LeadEvent","measurementId","eventId","leadSource","gtm","google_tag_manager","hasOwnProperty","isGa4TagLoaded","send_to","event_id","lead_source","gtag","isArray","dataLayer","_args","LeftAngleIcon","viewBox","xmlns","stroke","fill","strokeLinecap","RightAngleIcon","SearchIcon","version","SpinnerIcon","offset","stopOpacity","stopColor","strokeWidth","attributeName","repeatCount","dur","path","focusable","CheckIcon","CheckBoxIcon","CheckBoxOutlineIcon","RadioCheckedIcon","RadioUncheckedIcon","ArrowDropDownIcon","ChevronLeftIcon","ChevronRightIcon","SearchResponseBubble","MessageBubble","firstIndex","val","patterns","res","patterns_1","pattern","indexOf","domainEnds","portEnds","pathEnds","queryEnds","parsers","rest","charAt","ellipsis","reduceLink","maxLength","parts","parsers_1","parser","newIndex","substring","getText","overflows","tryReduce","allButPathLength","available","newPathStart","Card","item","imageUrl","image","alt","accessibilityText","description","CarouselItem","Carousel","list","listRef","scrollIterate","func","container","items","getElementsByClassName","containerRect","getBoundingClientRect","length_1","itemRect","size","scrollLeft","handlePrev","prevPos","handleNext","IconButton","SearchResponseCarouselDisplay","carousel","Cards","SearchResponseListDisplay","SuggestionsGroupHeading","_Fragment","addContextPrefix","input","ignore","functionNames","fn","TEMPLATE_REGEX","replaceValues","o","values","_match","trimmedKey","CALENDAR_DATE","CLOCK_TIME","toClock","exec","padStart","isBlockedTime","calendarDate","clock","date","blockedUntil","windowedChips","startTime","s","u","a","h","$","M","weekdays","split","months","ordinal","m","z","utcOffset","abs","year","month","clone","add","ceil","p","D","ms","Q","S","O","b","locale","$L","utc","$u","$x","$offset","$d","NaN","UTC","init","$y","getFullYear","$M","getMonth","$D","getDate","$W","getDay","$H","getHours","$m","getMinutes","$s","getSeconds","$ms","getMilliseconds","$utils","isValid","isSame","startOf","endOf","isAfter","isBefore","$g","unix","valueOf","toDate","$locale","weekStart","$set","min","daysInMonth","subtract","format","invalidDate","meridiem","monthsShort","weekdaysMin","weekdaysShort","getTimezoneOffset","diff","toJSON","toUTCString","Y","extend","$i","isDayjs","en","Ls","exports","day","hour","minute","second","timeZoneName","Intl","DateTimeFormat","hour12","timeZone","formatToParts","parseInt","tz","toLocaleString","$timezone","offsetName","guess","find","isNaN","resolvedOptions","setDefault","local","getUTCFullYear","getUTCMonth","getUTCDate","getUTCDay","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","$localOffset","isUTC","dayjs","utcPlugin","timezonePlugin","DEFAULT_SLOT_MINUTES","DEFAULT_HORIZON_DAYS","DEFAULT_DATE_FIELD_NAME","DEFAULT_DATE_TIME_FIELD_NAME","DEFAULT_TIME_ZONE_FIELD_NAME","FIXED_OFFSET","WEEKDAYS","clockToMinutes","hours","minutes","pad","minutesToClock","wrapped","toCalendarDate","TIMEZONE_NAME_STYLES","formatTimezoneLabel","timezone","TIMEZONE_NAME_STYLES_1","named","toOffsetIso","normalized","timeZoneOf","schedule","formatClock","hours24","formatOfferingLabel","offering","end","horizonDaysOf","horizon","horizonDays","isOffering","filterElapsed","offerings","lead","leadTimeMinutes","buffer","cutoff","zonedInstant","generateOfferings","offeringsByDate","exception","exceptions","findException","spans","weekday","weekdayOf","days","slotMinutes","duration","durationMinutes","spans_1","span","generateUnblockedOfferings","isDateSelectable","today","todayInZone","firstSelectableDate","isBusy","NO_MATCH_STEP_IDS","classifyAnchor","anchor","stepEls","querySelectorAll","hasLoading","SCRIPT_ORIGIN_ATTRIBUTE","useExternalWidget","externalWidget","options","onRendered","onNoRender","onError","onFallback","outcome","setOutcome","suppressedScheduledCount","setSuppressedScheduledCount","hasMountedRef","scheduledFiredRef","suppressedScheduledRef","outcomeSettledRef","optionsRef","provider","scriptSrc","hostname","getExternalWidgetProvider","globalConfig","successCallbackKey","successCallbackKey_1","payload","onScheduled","configGlobal","settle","nextOutcome","notify","fallbackStep","protocol","isValidScriptSrc","timeoutId","observer","getElementById","anchorId","timeoutMs","renderTimeoutMs","extensions","handleNoRender","evaluate","el","onTimeout","currentAnchor","MutationObserver","observe","childList","subtree","cacheBust","includes","clearTimeout","disconnect","FormFieldSelect","field","onFieldChange","errorMessage","selectValue","setSelectValue","radioValue","setRadioValue","onCheckboxChange","checked","prevOptions","option","onRadioChange","useId","titleId","helperId","invalid","radio","xapp_select_title_container","xapp_select_container","role","xapp_select_option","xapp_checkbox_select","xapp_checkbox_select_checked","xapp_select_input","xapp_select_icon","xapp_select_label","xapp_select_helper","VARIANT_ELEMENTS","h1","h2","h3","h4","h5","h6","subtitle1","subtitle2","body1","body2","inherit","button","caption","overline","PALETTE_COLORS","primary","secondary","warning","info","success","textPrimary","textSecondary","textDisabled","FormFieldCard","color","variant","Text","xapp_form_card","xapp_form_card_body","header","xapp_form_card_header","xapp_form_card_header_title","subheader","xapp_form_card_header_subheader","media","xapp_form_card_media","xapp_form_card_content","xapp_form_card_text","whiteSpace","textAlign","align","isSelectableItem","FormFieldChips","disabledItemIds","selectedFromProps","selected","selectedChips","setSelectedChips","disabledKey","disabled","chipId","flexDirection","alignContent","alignItems","_prevOptions","handleChipClick","isActionableItem","FORMAT_PROPS","PHONE","inputMode","autoComplete","EMAIL","ZIP_CODE","ADDRESS","DEFAULT_PROPS","NAME_AUTOCOMPLETE","fullname","yourname","customername","contactname","firstname","fname","givenname","lastname","lname","surname","familyname","email","emailaddress","phone","phonenumber","telephone","tel","mobile","mobilephone","cellphone","zip","zipcode","postalcode","postcode","address","streetaddress","street","city","town","province","company","companyname","organization","business","businessname","formatToInputProps","isLastField","mapped","enterKeyHint","autoCompleteFromName","FormFieldTextInput","required","setText","focused","setFocused","textareaRef","autosize","multiline","rows","useLayoutEffect","textarea","lineHeight","maxHeight","rowsMax","Infinity","scrollHeight","currentLength","isAtLimit","showCounter","inputHelpers","__rest","shrink","controlProps","xapp_text_input_control","placeholder","onFocus","onBlur","xapp_text_input_container","xapp_text_input_text","xapp_text_input_error","xapp_text_input_root","xapp_text_input_focused","xapp_text_input_multiline","htmlFor","xapp_text_input_label","xapp_text_input_asterisk","xapp_text_input_helper","xapp_text_input_counter","FormFieldDropdown","freeFormErrorMessage","freeFormId","freeFormHelperId","selectedItem","dropValue","setDropValue","freeFormValue","setFreeFormValue","freeFormInput","showFreeForm","setShowFreeForm","onFieldChangeRef","process","env","NODE_ENV","currentFreeFormFieldName","freeFormFieldName","prevSelectedItem","messageFieldName","classNames","names","Calendar","shouldDisableDate","minDate","maxDate","referenceDate","showDaysOutsideCurrentMonth","fixedWeekNumber","getDayClassName","classes","labelId","gridRef","focusOnRender","setMonth","focusedDay","setFocusedDay","valueKey","isOutOfRange","isDisabled","closestEnabled","clamped","candidate","tabbableDay","timestamp","focus","walked","monthJump","onDayKeyDown","edge","direction","scan","preventDefault","moveFocus","previousDisabled","nextDisabled","weeks","first","weeksInMonth","week","__","weeksOf","row","outside","isToday","daySelected","dayToday","onDayClick","onKeyDown","parseBusyDays","busyDays","entry","isBusyDay","dateString","dayString","some","busyDay","isMatch","str","regexPattern","escapeRegExp","isBusinessDay","availableDays","DEFAULT_BUSY_DAYS","blockWeekends","blockCurrentDay","blockNextBusinessDays","FormFieldDate","MAX_DATE","TODAY","blockedDate","dateTimeValue","setDateTimeValue","disabledDays","nextBusinessDay","guard","currentDayAvailableUntil","isDisabledByBusyDays","defaultBusyDays","isPast","isBeyondMaxDate","newValue","ISO_DATE","toInputDate","FormFieldDateRange","initialFrom","preselecteDates","initialTo","range","setRange","change","fromId","toId","TIMES_LABEL","TIMEZONE_NOTICE_PREFIX","offeringKey","FormFieldDateTime","nextBusinessDayBlock","preselectFirstAvailable","selectedDate","setSelectedDate","selectedKey","setSelectedKey","fieldValue","datetime","preselected","previousGroup","hasSchedule","scheduleTimezone","timezoneUsable","isUsableTimezone","notice","visitorTimezone","hostTimezone","visitorName","timezoneNotice","group","Fragment","highlight","isPlaceSuggestion","placePrediction","mapSuggestion","suggestion","structured_formatting","main_text","structuredFormat","mainText","secondary_text","secondaryText","main_text_matched_substrings","matches","startOffset","endOffset","AddressAutocompleteService","baseUrl","apiKey","getPlacePredictions","callback","components","regionCodes","includedRegionCodes","language","languageCode","lat","lng","locationBias","circle","center","latitude","longitude","radius","componentRestrictions","country","suggestions","getPlaceDetails","LocationOnIcon","FormFieldTextInputAddress","googleMapsApiKey","mapsBaseUrl","requireSelection","isFreeSolo","setAddress","setOptions","_e","open","setOpen","_f","_g","activeIndex","setActiveIndex","listboxId","optionId","listboxRef","textRef","onTextChange","autocompleteService","showGoogleAttribution","endsWith","wait","timeout","debounced","debounce","queryParams","mapsUrlQueryParams","results","visibleOptions","popupOpen","listbox","HTMLElement","scrollTop","offsetHeight","clientHeight","close","select","description_1","details","formattedAddress","activeOption","autoCapitalize","spellCheck","stopPropagation","chosen","onMouseDown","hidden","onMouseMove","fontWeight","isEmptyString","validateUSPhoneNumber","sanitizedNumber","isEmpty","obj","constructor","isFormStepExternalWidget","hasFieldValue","SCHEDULING_CHIPS_NAMES","isSchedulingField","leadFieldNamesOf","dateTimeField","dateFieldName","dateTimeFieldName","timeZoneFieldName","isGroupableFieldField","mandatoryGroup","FormStepDisplay","stepData","prefilledFields","hasNotifiedPrefill","prevFieldsRef","formStep","fields","fieldTests","mandatoryGroups","setMandatoryGroups","fieldConditions","setFieldConditions","fieldErrors","setFieldErrors","isSubmitting","setIsSubmitting","schedulingDisabled","flag","isSchedulingDisabled","rawOfferingsByDate","parseOfferingsByDate","rawNextBusinessDayBlock","parseNextBusinessDayBlock","pickedDate","setPickedDate","isHiddenSchedulingField","nextStep","onNextStep","prevStep","onPrevStep","handleData","handleDataWithLabels","onDataWithLabels","getData","getDataWithLabels","currentStepIndex","totalSteps","onTrackNextStep","currentStepDataRef","isActive","externalWidgetConfigPending","onTrackHandoffRendered","onTrackHandoffNoRender","onTrackHandoffScheduled","onTrackHandoffError","onExternalWidgetFallback","submitError","hideIntro","externalWidgetConfig","externalWidgetOutcome","externalWidgetContentShown","setExternalWidgetContentShown","childElementCount","checkConditions","newConditions","context_1","safeIncludes","searchElement","objA","objB","keysA","keysB","keysA_1","shallowEqualBooleanMap","groups","groupName","visibleStepValues","stepValues","visibleValues","chipsSelectedFromProps","condition","conditionWithThis","Function","validate","errors","corrections","valid","isFormDropdownInput","mandatory","mandatoryError","isFormDateRangeInput","isCompleteRange","isFormDateTimeInput","selection","isCompleteDateTime","isFormTextInput","validateZipCode","formattedZip","trimmed","toUpperCase","formatZipCode","validatePhoneNumber","formattedNumber","formatUSPhoneNumber","isFormChipsInput","isFormDateInput","isFormCheckInput","minRequired","maxAllowed","fieldNames","fieldError","errorMessage_1","obj1","obj2","keys1","keys2","keys1_1","attr1","attr2","fieldErrorsEqual","continueToNext","pushData","isLastStep","nextAction","pushedData","pushedLabels","clearedData","clearedLabels","name_1","augmentedData","dataWithLabels","applyTimes","fieldName","startTimes","endTimes","joinedStart","joinedEnd","ordinalSuffix","formField","valueLabels_1","startTimes_1","endTimes_1","chip","timedItem","endTime","arr","lastElement","joinWithAnd","word","number","getOrdinalSuffix","isNextDisabled","isFirst","delete","pickedCalendarDate","fullBleed","subtitle","warnBeforeUnloadMessage","backgroundColor","padding","marginBottom","borderRadius","border","gap","fontSize","iframe","frameBorder","allowFullScreen","stepFields","firstHiddenIndex","findIndex","windowed","every","fieldComponent","dropdownField","currentValue_1","freeFormError","_h","preselectFirstAvailableDate","_j","getFields","nextLabel","previousAction","previousLabel","FormFrame","framing","framed","tabLabel","introTitle","introSubtitle","introPlacement","intro","SimpleNavigationHeader","onHeaderClick","labelHeader","stepName","isShowCase","headerText","isInServiceArea","zipCodes","baseZip","supportedZip","extractZipFromAddress","before","FormDisplay","form","onActionResponse","onTrackPreviousStep","onTrackSubmit","onTrackSubmitFailure","initialStep","onTrackInitialStep","onFormNext","stepUpdate","currentStep","setCurrentStep","appliedInitialStep","stepOverrides","setStepOverrides","failedSubmitStep","setFailedSubmitStep","applyFormStepUpdate","handoffConfigSettledRef","awaitingHandoffConfig","setAwaitingHandoffConfig","externalWidgetWaitElapsed","setExternalWidgetWaitElapsed","activeStep","steps","timer","step_1","conditionWithThis_1","shouldWarnBeforeUnload","currentFormStep","warnBeforeUnload","handleBeforeUnload_1","returnValue","formData","formDataWithLabels","lastStepData","formSubmittedRef","submit","nextStepIndex","formStepItem","test_1","zip_code","currentStepDef","serverCallback","race","displays","onSubmitForm","fromStepIndex","fromStepName","step_2","test_2","submitStepIndex","safeStepIndex","stepIndex","reason","jumpToExternalWidgetFallback","activeStepHandsOff","activeStepFramed","hideLabelHeader","override","effectiveStep","staticExternalWidget","stepDisplay","onData","ResponseDisplay","SearchResponseHtml","html","dangerouslySetInnerHTML","__html","SearchResponseText","SearchResponseAudio","audio","onAudioChange","audioRef","audioElement","handleAudioEnd","handleAudioPlay","autoPlay","SearchResponseOutputSpeech","audioUrl","outputSpeech","displayText","ssml","mp3s","regex","parseAudio","isLinkoutSuggestion_1","isLinkoutSuggestion_2","isLinkoutSuggestion","Button","expand","SuggestedAction","handleClick","SuggestedActions","actions","onActionClick","xapp_search_suggested_actions","xapp_search_suggested_actions__actions","act","xapp_search_suggested_actions__item","SearchResponsePart","extraClass","modifier","xapp_search_response_part","FormResponse","noHeaderForm","SearchResponseDisplay","INTERACTION_EVENTS","EventTrackingService","formId","forVisit","trackFormOpen","metadata","buildMetadata","isOpen","watchForFirstInteraction","event_1","sendEvent","formName","trackEngaged","event_2","trigger","error_2","trackNextStep","event_3","completedStepName","error_3","trackPreviousStep","event_4","toStepName","error_4","trackStepChange","event_5","error_5","trackSubmit","event_6","finalStepName","error_6","trackSubmitFailure","event_7","error_7","trackClose","event_8","lastStepName","error_8","trackPartialData","event_9","abandonmentReason","error_9","trackHandoffRendered","event_10","error_10","trackHandoffNoRender","event_11","error_11","trackHandoffScheduled","event_12","error_12","trackHandoffError","event_13","error_13","trackLoad","loadMetadata","currentUrl","event_14","trackPartialDataBeacon","event_15","nowMs","openedAt","userAgent","internal","readInternalTrafficMark","msOnPage","firstInteractionAt","msToFirstInteraction","screenWidth","screen","screenHeight","viewportWidth","innerWidth","viewportHeight","visitIdentity","getTrackingParameters","dispose","stopWatchingForInteraction","adoptVisitFrom","previous","onInteraction_1","isTrusted","INTERACTION_EVENTS_2","INTERACTION_EVENTS_1","name_2","capture","passive","error_14","SUBMIT_RETRY_DELAYS_MS","FormWidget","FormWidgetRaw","docked","openedByTrigger","preselectChipLabel","onPreselectChipUsed","onSubmit","dispatch","setResponse","setStepUpdate","audioOn","setAudioOn","waitingOnAudioToFinish","setwaitingOnAudioToFinish","getTrustedFormData","trustedForm","eventTracker","currentStepRef","dockedRequestSent","submitEventIdRef","getSubmitEventId","ga4FiredEventIdsRef","formDisplayRef","formIdRef","abandonEventSentRef","formOpenSentRef","engagementSentRef","trackEngagement","firstStepName","handleCancel","handleClose","allFormData","hasData","lastStepIndex","totalStepsCompleted","partialData","closeResponse","trackingParameters","handleBeforeUnload","completionPercentage","midnightTimeoutId","sendTimeoutEvent","handleVisibilityChange","msUntilMidnight","midnight","setHours","intentResponse","formDisplay","previousTracker","engagementTrigger","dispatchOnce","wasDroppedAfterFinal","update","autoClose","autoMinimize","attempt","delays","lastError","dispatchWithRetry","handleActionClick","matchingChip","handleActionResponse","timezoneOffset","trustedFormData","ga4MeasurementId","extras","fbp","fbc","clientFired","ga4OptOut","gaClientId","clientId","parseGaClientId","gaSessionId","token","parseGaSessionId","ga4ClientFired","getGa4LeadExtras","handleFormNext","handleAudioChange","isOn","handleTrackInitialStep","handleTrackNextStep","nextStepName","completedStepIndex","toStepIndex","handleTrackPreviousStep","handleTrackSubmit","completedData","dataWithTrustedForm","finalStepIndex","handleTrackSubmitFailure","handleTrackHandoffRendered","handleTrackHandoffNoRender","handleTrackHandoffScheduled","handleTrackHandoffError","displayContainer","WidgetStylesheet","theme","currentFontLink","font","link","fontUrl","linkId","existingLink","remove","rel","crossOrigin","loadExternalFont","entriesKey","gen","widgetTheme","withPrefix","union","single","headerBackgroundColor","headerTextColor","primaryButtonColor","primaryButtonTextColor","secondaryButtonColor","secondaryButtonTextColor","borderColor","fontFamily","getFontStyle","darken","borderWidth","borderColorFocus","getTextStyle","backButtonVariant","back","backButton","iconStroke","colorHover","getBackButtonStyle","boxShadow","getButtonStyle","getStepTitleStyle","stepTitle","finalButtonPlacement","getFinalButtonStyle","getDropdownStyle","dropdown","getCheckboxStyle","checkbox","backgroundColorSelected","colorSelected","getChipsStyle","chips","getDateStyle","getCardStyle","card","minLength","getSideButtonStyle","sideButton","minHeight","getExternalWidgetStyle","themeVariables","buildStyleVariables","entries_1","appliedVariableCounts","applyThemeVariables","entries_2","removeThemeVariables","children_1","child","colorIn","amount","colorOut","colorString","rgbaRegex","rgbRegex","hexMatch","rgba","luminance","ratio","SideButton","sideButtonPositionClass","DEFAULT_SESSION_KEY","validateDelay","validateScrollPercent","useAutoOpenTriggers","onOpen","hasInteracted","triggersRef","hasOpenedRef","inactivityTimerRef","sessionKey","triggers","delay","scrollPercent","exitIntent","exitIntentThreshold","inactivity","minimumWidth","patternsKey","configuredTriggers","getConfiguredTriggers","checkAndOpen","triggerName","allFired","isDismissed","matchesUrlPatterns","meetsMinimumWidth","timers","listeners","addListener","handler","targetPercent_1","scrollTicking_1","checkScrollPercent_1","scrollableHeight","maxTouchPoints","threshold_1","clientY","resetInactivityTimer_1","FORM_PAGE_ATTRIBUTE","FORM_PAGE_COUNT_ATTRIBUTE","markFormPage","useFormPageMarker","isEmbedded","classList","contains","lastClick","record","Element","FormContainer","Form","buttonElementLookup","setPreselectChipLabel","setHasInteracted","setOpenedByTrigger","immediateAutoOpen","autoOpen","hasAutoOpenTriggers","openModal","handleFocus","openFormWithOptions","formStatus","handleAutoOpen","elements","XAPP_FORM_BUTTON","onclick","onfocus","xafwControl","openForm","triggerSelector","earlyClick","click","takeEarlyClick","closest","HTMLAnchorElement","sideButtonLabel","hideSideButton","getBasePathFromWidgetSource","xappScriptNode","lastPathSep","lastIndexOf","substr","getBasePath","parseWidgetEnv","connection","accountKey","serverUrl","autocompleteSuggestionsUrl","STYLE_PRESET_NONE","resolveStylePresetName","standalone","stylePreset","partnerCode","getPresetStyle","resolveFormStyle","customerTheme","preset","mergeFormWidgetTheme","base","deepMerge","isPlainObject","merged","COST_GUIDE_FORM_STYLE","standAlone"],"mappings":"+zEAEA,IAAIA,EAAaC,EACbC,EAAQC,EA6XZ,SAASC,EAAUC,EAASC,EAAYC,EAAGC,GAEvC,OAAO,IAAKD,IAAMA,EAAIE,UAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,GAAQ,CAAG,MAAOG,GAAKL,EAAOK,GAAK,CACzF,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,GAAQ,CAAG,MAAOG,GAAKL,EAAOK,GAAK,CAC5F,SAASF,EAAKI,GAJlB,IAAeL,EAIaK,EAAOC,KAAOT,EAAQQ,EAAOL,QAJ1CA,EAIyDK,EAAOL,MAJhDA,aAAiBN,EAAIM,EAAQ,IAAIN,EAAE,SAAUG,GAAWA,EAAQG,EAAO,IAIhBO,KAAKR,EAAWK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