@widgetic/embed-sdk 2.1.7 → 2.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/core.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/chunks/security.js +1 -1
- package/dist/browser/chunks/workflows.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/core.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/chunks/security.js +1 -1
- package/dist/esm/chunks/workflows.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/core/constants.d.ts +1 -1
- package/dist/esm/types/core/scroll-trigger.d.ts +8 -1
- package/dist/esm/types/core/show-rules.d.ts +58 -0
- package/dist/esm/types/core/trigger-defaults.d.ts +3 -0
- package/dist/esm/types/core/trigger-manager.d.ts +16 -0
- package/dist/esm/types/core/types.d.ts +8 -1
- package/dist/esm/types/core/version.d.ts +1 -1
- package/dist/esm/types/utils/published-host-display.d.ts +9 -0
- package/dist/esm/types/workflows/workflow-counts.d.ts +54 -5
- package/dist/esm/types/workflows/workflow-host.d.ts +12 -3
- package/dist/esm/types/workflows/workflow-stage.d.ts +22 -1
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk-workflows.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +1 -1
package/dist/esm/chunks/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as e,g as t,C as i,V as n,a as o,b as s,W as r,c as a,d,P as l,e as c,f as h,h as g,F as u,E as m,S as p,s as f,i as v,j as w,k as y,m as b,A as I}from"./core.js";import{r as S,w as E,a as C,b as M,c as T,s as W,d as x,e as A,g as D,f as k,W as O,I as L,C as R,h as z}from"./renderers.js";import{_ as P,a as H}from"./vendor.js";import{p as U,i as j,a as B,b as N,g as $,c as _,h as F,d as V,e as K,m as q,o as Y,D as G,f as Q,M as J,j as Z,k as X,l as ee,n as te}from"./scanner.js";import{g as ie,a as ne}from"./media.js";import{getMessenger as oe,WidgeticMessenger as se}from"./messaging.js";import{c as re,g as ae,a as de,b as le}from"./advanced.js";import{D as ce,g as he,a as ge,b as ue}from"./display.js";import{g as me,i as pe,a as fe,b as ve,c as we,d as ye}from"./performance.js";import{S as be}from"./security.js";class Ie{constructor(){this.deviceInfo=null}static getInstance(){return Ie.instance||(Ie.instance=new Ie),Ie.instance}getDeviceInfo(){return this.deviceInfo||(this.deviceInfo=this.detectDevice()),this.deviceInfo}getDeviceType(){return this.getDeviceInfo().type}isMobile(){return this.getDeviceInfo().isMobile}isTablet(){return this.getDeviceInfo().isTablet}isDesktop(){return this.getDeviceInfo().isDesktop}hasTouch(){return this.getDeviceInfo().hasTouch}detectDevice(){const t=navigator.userAgent||"",i=navigator.platform||"",n=navigator.vendor||"",o=navigator.maxTouchPoints||0,s=navigator.hardwareConcurrency||1,r=navigator.deviceMemory,a=this.detectTouchCapability(),d=this.determineDeviceType(t,i,a,o),l={type:d,isMobile:"mobile"===d,isTablet:"tablet"===d,isDesktop:"desktop"===d||"tablet"===d,hasTouch:a,userAgent:t,platform:i,vendor:n,maxTouchPoints:o,hardwareConcurrency:s,deviceMemory:r};return e.debug("Device detected",l),l}detectTouchCapability(){if("ontouchstart"in window)return!0;if(navigator.maxTouchPoints&&navigator.maxTouchPoints>0)return!0;if("onpointerdown"in window)return!0;try{if(void 0!==window.DocumentTouch&&document instanceof window.DocumentTouch)return!0}catch(e){}return!1}determineDeviceType(e,t,i,n){const o=e.toLowerCase(),s=t.toLowerCase();return[/android.*mobile/,/iphone/,/ipod/,/blackberry/,/bb10/,/windows phone/,/iemobile/,/mobile/,/phone/].some((e=>e.test(o)))?"mobile":[/ipad/,/android(?!.*mobile)/,/kindle/,/silk/,/playbook/,/tablet/].some((e=>e.test(o)))?"tablet":[/windows nt/,/macintosh/,/mac os x/,/linux/,/x11/,/cros/].some((e=>e.test(o)))?"desktop":/^(iphone|ipod|android)/.test(s)?"mobile":/^(ipad)/.test(s)?"tablet":/^(win|mac|linux)/.test(s)?"desktop":i?n>=5?"tablet":n<=2?"mobile":"tablet":"desktop"}checkDeviceRestrictions(t=!0,i=!0){const n=this.getDeviceInfo();return n.isMobile&&!t?(e.debug("Widget restricted on mobile device"),!1):!(n.isDesktop&&!i)||(e.debug("Widget restricted on desktop/tablet device"),!1)}getDeviceCapabilities(){const e={userAgent:navigator.userAgent,platform:navigator.platform,vendor:navigator.vendor,language:navigator.language,languages:navigator.languages,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,maxTouchPoints:navigator.maxTouchPoints,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,connection:navigator.connection,standalone:navigator.standalone,webdriver:navigator.webdriver};return e.screen={width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,colorDepth:screen.colorDepth,pixelDepth:screen.pixelDepth,orientation:screen.orientation},e.touch={hasTouch:this.hasTouch(),hasTouchEvents:"ontouchstart"in window,hasPointerEvents:"onpointerdown"in window,hasGestureEvents:"ongesturestart"in window},window.matchMedia&&(e.mediaQueries={hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":"coarse",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":"coarse"}),e}reset(){this.deviceInfo=null}}function Se(){return Ie.getInstance()}function Ee(e=!0,t=!0){return Se().checkDeviceRestrictions(e,t)}const Ce="data-widgetic-overlay",Me="data-device-restricted",Te=new WeakMap,We=new WeakMap,xe=new Map;function Ae(t,i,n){if(Te.has(t))return;const o=t.getAttribute("composition-id")||"widget",s=function(e,t){const i=We.get(e);if(i)return i;const n=(xe.get(t)||0)+1;xe.set(t,n);const o=1===n?t:`${t}-${n}`;return We.set(e,o),o}(t,o);let r=()=>{};if(n){const e=e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===s&&(r(),n())};document.addEventListener("widgetic:overlay-shown",e),r=()=>document.removeEventListener("widgetic:overlay-shown",e)}Promise.resolve().then((function(){return Ui})).then((({TriggerManager:n})=>{if(Te.has(t))return void r();const o=new n({widgetId:s,element:t,config:i,displayWhenShown:"block"});Te.set(t,o),t.hasAttribute(Ce)&&t.setAttribute(Ce,"armed"),e.debug("[published-host-display] Trigger manager armed",{widgetId:s,mode:i.mode,eventTrigger:i.eventTrigger})})).catch((t=>{r(),e.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:s,error:t})}))}const De="data-widgetic-workflow-stage",ke=2e3,Oe=150,Le=5,Re=300,ze=2e4,Pe=[250,1e3,2500],He=new Set(["TEXTAREA","INPUT","SELECT","IFRAME","VIDEO","AUDIO","CANVAS","OBJECT","EMBED"]);function Ue(e){return e.hasAttribute(De)}function je(e){return j(e)&&!Ue(e)&&!e.hasAttribute(Ce)}function Be(e,t,i){const n=e.getAttribute(t);if(null===n||!/^\d+$/.test(n.trim()))return null;const o=Number.parseInt(n.trim(),10);return Number.isFinite(o)?Math.min(o,i):null}function Ne(e,t,i=function(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(e){return!1}}()){var n,o,s,r,a;const d=null!==(n=Be(e,"autoscale-min-height",ze))&&void 0!==n?n:Math.max(0,Math.round(t)),l=null!==(o=Be(e,"autoscale-max-height",ze))&&void 0!==o?o:ke;return{floorHeight:d,maxHeight:Math.max(l,d),debounceDelay:null!==(s=Be(e,"autoscale-debounce",5e3))&&void 0!==s?s:Oe,threshold:null!==(r=Be(e,"autoscale-threshold",ze))&&void 0!==r?r:Le,animate:"false"!==e.getAttribute("autoscale-animate")&&!i,animationDuration:null!==(a=Be(e,"autoscale-animation-duration",5e3))&&void 0!==a?a:Re}}function $e(e,t){return Number.isNaN(e)?t.floorHeight:Math.max(t.floorHeight,Math.min(t.maxHeight,Math.ceil(e)))}function _e(e){const t=Number.parseFloat(null!=e?e:"");return Number.isFinite(t)?t:0}function Fe(e){const t=e.overflowY;return"auto"===t||"scroll"===t||"overlay"===t}function Ve(e,t,i){var n;if("fixed"===t.position)return!1;for(let t=e.parentElement;t&&t!==i;t=t.parentElement)if("fixed"===(null===(n=t.ownerDocument.defaultView)||void 0===n?void 0:n.getComputedStyle(t).position))return!1;if("absolute"===t.position){const t=e.parentElement;if(!t)return!1;return e.getBoundingClientRect().height>=t.getBoundingClientRect().height-2}return!0}function Ke(e){const t=e.getBoundingClientRect(),i=e.offsetHeight>0&&t.height>0?t.height/e.offsetHeight:1,n=e.scrollHeight-e.clientHeight,o=n>1?n:-function(e,t,i){const n=e.ownerDocument.defaultView;if(!n||e.clientHeight<=0)return 0;const o=n.getComputedStyle(e),s=t+e.clientTop*i;let r=s+_e(o.paddingTop)*i,a=0;for(const t of Array.from(e.children)){const e=n.getComputedStyle(t);if("none"===e.display||"absolute"===e.position||"fixed"===e.position)continue;const o=t.getBoundingClientRect();0===o.width&&0===o.height||o.bottom>r&&(r=o.bottom,a=_e(e.marginBottom)*i)}const d=(r+a-s+_e(o.paddingBottom)*i)/i;return Math.max(0,Math.floor(e.clientHeight-d))}(e,t.top,i);return{region:e,top:t.top,bottom:t.bottom,delta:o}}function qe(e){const t=[...e].sort(((e,t)=>e.top-t.top));let i=0,n=0,o=Number.NEGATIVE_INFINITY,s=!1;for(const e of t)s&&e.top<o-1?(n=Math.max(n,e.delta),o=Math.max(o,e.bottom)):(s&&(i+=n),n=e.delta,o=e.bottom,s=!0);return s&&(i+=n),i}function Ye(e,t,i,n,o){if(!Number.isFinite(i)||i<=0)return null;const s=function(e,t){const i=[];for(const n of Array.from(e.querySelectorAll("*"))){if(!(n instanceof HTMLElement))continue;if(He.has(n.tagName))continue;if(null==t?void 0:t.has(n))continue;const o=n.ownerDocument.defaultView;if(!o)continue;const s=o.getComputedStyle(n);Fe(s)&&(i.some((e=>e.contains(n)))||Ve(n,s,e)&&i.push(n))}return i}(e,o).map((e=>Ke(e)));if(0===s.length)return i;const r=Math.max(0,Math.ceil(i+qe(s))),a=$e(r,n);if(!Ge(i,a,n.threshold))return r;const d=function(e,t,i){const n=t.map((e=>e.clientHeight)),o=e.style.height,s=e.style.transition;try{return e.style.transition="none",e.style.height=`${i}px`,t.map(((e,t)=>{var i;return e.clientHeight-(null!==(i=n[t])&&void 0!==i?i:0)}))}finally{o?e.style.height=o:e.style.removeProperty("height"),e.offsetHeight,e.style.transition=s}}(t,s.map((e=>e.region)),a),l=s.map(((e,t)=>{var i;if(Math.abs(e.delta)<=1)return e;const n=null!==(i=d[t])&&void 0!==i?i:0;if(Math.abs(n)<1)return o.add(e.region),Object.assign(Object.assign({},e),{delta:0});const s=e.delta>0?Math.min(e.delta,Math.max(0,n)):Math.max(e.delta,Math.min(0,n));return Object.assign(Object.assign({},e),{delta:s})}));return Math.max(0,Math.ceil(i+qe(l)))}function Ge(e,t,i){return t!==e&&Math.abs(t-e)>=Math.max(1,i)}function Qe(t){const{host:i,box:n,compositionId:o,settings:s,startHeight:r,originalHeightCss:a}=t;let d=Math.round(r),l=!1,c=0;const h=(e,t)=>{c=t?Date.now()+s.animationDuration:0,n.style.transition=t?`height ${s.animationDuration}ms ease`:"none",e===Math.round(r)?a?n.style.height=a:n.style.removeProperty("height"):n.style.height=`${e}px`};return{currentHeight:()=>d,isAnimating:()=>Date.now()<c,follow(t){const n=$e(t,s);if(!Ge(d,n,s.threshold))return!1;const r=d;h(n,s.animate&&l),d=n,l=!0,E(o,n,s.floorHeight),e.debug("[autoscale] The embed follows its widget",{compositionId:o,previousHeight:r,nextHeight:n,naturalHeight:t});try{i.dispatchEvent(new CustomEvent("widgetic:autoscale",{bubbles:!0,composed:!0,detail:{compositionId:o,oldHeight:r,newHeight:n,contentHeight:Math.ceil(t)}}))}catch(e){}return!0},startAtStoredHeight(){const e=S(o);if(null===e)return!1;const t=$e(e,s);return!(!Ge(d,t,s.threshold)||t<=d)&&(h(t,!1),d=t,l=!0,!0)}}}const Je=new WeakMap;function Ze(e){var t;null===(t=Je.get(e))||void 0===t||t.stop(),Je.delete(e)}const Xe=/^[A-Za-z0-9_.-]{1,64}$/;function et(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function tt(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch(e){return null}}function it(e){const t=tt(e);if(!t)return null;const i=Object.keys(t);if(i.length>50)return null;if(et(t)>8192)return null;const n={};for(const e of i){if(!Xe.test(e))return null;const i=t[e];if("boolean"==typeof i)n[e]=i;else if("number"==typeof i){if(!Number.isFinite(i))return null;n[e]=i}else{if("string"!=typeof i)return null;if(i.length>2e3)return null;n[e]=i}}return n}function nt(e){if(!(null==e?void 0:e.trim()))return null;const t=e.trim();if(t.length>2048)return null;try{return"https:"!==new URL(t).protocol?null:t}catch(e){return null}}const ot=new WeakMap;function st(e){var t;const i=e.getAttribute("context"),n=function(e){const t=tt(e);if((null==e?void 0:e.trim())&&!t)return{value:null,invalid:!0};if(!t)return{value:null,invalid:!1};const i=Object.keys(t);if(i.length>20)return{value:null,invalid:!0};if(et(t)>2048)return{value:null,invalid:!0};const n={};for(const e of i){if(!Xe.test(e))return{value:null,invalid:!0};const i=t[e];if("number"==typeof i){if(!Number.isFinite(i))return{value:null,invalid:!0};n[e]=i}else{if("string"!=typeof i)return{value:null,invalid:!0};if(i.length>500)return{value:null,invalid:!0};n[e]=i}}return{value:n,invalid:!1}}(i);return n.invalid&&function(e,t){const i=null!=t?t:"";let n=ot.get(e);n||(n=new Set,ot.set(e,n)),n.has(i)||n.add(i)}(e,i),{context:n.invalid?null:n.value,contextInvalid:n.invalid,values:it(e.getAttribute("values")),mediaResolver:nt(null!==(t=e.getAttribute("media-resolver"))&&void 0!==t?t:e.getAttribute("mediaresolver"))}}function rt(e){return Object.assign(Object.assign({},e.entries?{entries:e.entries}:{}),e.adapters?{adapters:e.adapters}:{})}function at(e,t,i){return Object.assign(Object.assign({type:"widgetic:host",version:1,compositionId:e,context:t.context,values:t.values,mediaResolver:t.mediaResolver},(null==i?void 0:i.entries)?{entries:i.entries}:{}),(null==i?void 0:i.adapters)?{adapters:i.adapters}:{})}const dt=1e4;function lt(e,t){const i=(null!=e?e:"").trim().toLowerCase();if(""===i)return t;const n=/^(\d+(?:\.\d+)?)(?:px)?$/.exec(i);if(!n)return null;const o=Number.parseFloat(n[1]);return o>0?o:null}const ct="data-widgetic-mobile",ht=new WeakMap;function gt(t){var i,n;const{host:o,box:s,widthCss:r,widthPixels:a,heightPixels:d}=t;!function(e){const t=ht.get(e);ht.delete(e),null==t||t()}(o);const l=()=>{};try{if(!function(e){return!Ue(e)&&!e.hasAttribute(Ce)&&void 0===B(e)}(o))return l;const t=function(e){var t;const i=(null!==(t=e.getAttribute("resize"))&&void 0!==t?t:"").trim().toLowerCase();return"fill-width"===i?"fill-width":"responsive"===i?"responsive":"fixed"}(o),c=null!==(i=function(e){const t=e.getAttribute("adaptive");if(null===t||!/^\d+$/.test(t.trim()))return null;const i=Number.parseInt(t.trim(),10);return i<1?null:Math.min(i,dt)}(o))&&void 0!==i?i:"responsive"===t?480:null;if("fixed"===t&&null===c)return l;const h=[],g=(t,i)=>{try{h.push(i())}catch(i){e.debug(`[resize] ${t} could not be followed`,{error:i})}};if("fixed"!==t){s.style.setProperty("width","100%"),"responsive"===t&&s.style.setProperty("max-width",r);je(o)||null===a||null===d||g("The width of the space",(()=>function(e,t,i,n,o){let s=0;const r=e=>{if(!(e>0)||e===s)return;s=e;const r="responsive"===i?Math.min(e,n):e,a=Math.max(1,Math.round(r*o/n));t.style.setProperty("height",`${a}px`)};if("function"==typeof ResizeObserver){const t=new ResizeObserver((t=>{const i=t[t.length-1];r(i?i.contentRect.width:e.clientWidth)}));return t.observe(e),()=>t.disconnect()}const a=()=>r(e.clientWidth);return window.addEventListener("resize",a),a(),()=>window.removeEventListener("resize",a)}(o,s,t,a,d)))}null!==c&&g("The breakpoint",(()=>function(t,i){var n;if("function"!=typeof window.matchMedia)return e.debug("[resize] The window cannot be measured against the breakpoint here",{breakpointPixels:i}),()=>{};const o=null!==(n=t.getAttribute("composition-id"))&&void 0!==n?n:"",s=window.matchMedia(`(max-width: ${i}px)`),r=n=>{t.setAttribute(ct,n?"true":"false"),e.debug("[resize] The window is against the breakpoint of the embed",{compositionId:o,breakpointPixels:i,isMobile:n});try{t.dispatchEvent(new CustomEvent("widgetic:adaptive",{bubbles:!0,composed:!0,detail:{compositionId:o,isMobile:n,breakpoint:i}}))}catch(e){}};r(s.matches);const a=e=>r(e.matches);return"function"==typeof s.addEventListener?s.addEventListener("change",a):"function"==typeof s.addListener&&s.addListener(a),()=>{"function"==typeof s.removeEventListener?s.removeEventListener("change",a):"function"==typeof s.removeListener&&s.removeListener(a),t.removeAttribute(ct)}}(o,c))),e.debug("[resize] The embed follows the Resize Mode of its tag",{compositionId:null!==(n=o.getAttribute("composition-id"))&&void 0!==n?n:"",resizeMode:t,breakpointPixels:c});const u=()=>{for(const e of h)try{e()}catch(e){}};return ht.set(o,u),u}catch(t){return e.debug("[resize] The box could not be sized from its tag; it keeps the size of its tag",{error:t}),l}}const ut="data-widgetic-context-invalid";const mt=new Set;let pt=0;function ft(e){return P(this,void 0,void 0,(function*(){pt+=1;try{const i=yield(t=e,import(t));return i&&!0!==i.acceptsHostProps&&mt.add(e),i}finally{pt-=1,0===pt&&null===St&&Ct()}var t}))}function vt(e){try{return ft(e).then((()=>!0),(()=>!1))}catch(e){return Promise.resolve(!1)}}const wt=new WeakMap,yt=new Set,bt=new Map;function It(e,t){const i=bt.get(e);i&&(i.delete(t),0===i.size&&bt.delete(e))}let St=null;const Et={context:null,values:null,mediaResolver:null,contextInvalid:!1};function Ct(){if("undefined"==typeof window)return;const e=new Set;let t=!1;for(const i of yt)i.payload.compositionId?e.add(i.payload.compositionId):t=!0;const i=!t&&1===e.size?Array.from(e)[0]:null;try{if(i&&1===mt.size&&0===pt){const e=Array.from(yt).find((e=>e.payload.compositionId===i)),t=e?rt(e.payload):{};if(e&&(t.entries||t.adapters)){const n=st(e.host);return window.postMessage(at(i,n,t),window.location.origin),void(St=i)}}null!==St&&i!==St&&(window.postMessage(at(St,Et),window.location.origin),St=null)}catch(e){}}function Mt(e,t){t.instance.update(At(e,t.payload)),t.listensOnWindow&&Ct()}const Tt=new WeakMap;function Wt(e,t){t?Tt.set(e,t):Tt.delete(e);const i=wt.get(e);if(i)try{Mt(e,i)}catch(e){}}function xt(e){const t=wt.get(e);if(t){wt.delete(e);try{t.instance.destroy()}catch(e){}t.stop(),null!==t.moduleSlot&&It(t.moduleUrl,t.moduleSlot),yt.delete(t)&&Ct()}for(const t of Array.from(e.querySelectorAll("[data-widgetic-direct]")))t.remove()}function At(e,t){const i=st(e);i.contextInvalid?e.setAttribute(ut,""):e.removeAttribute(ut);const n=_(e,t),o=Object.assign(Object.assign(Object.assign({},t.content||{}),n.content),i.values||{}),s=Object.assign(Object.assign({},t.design||{}),n.design),r=n.contentItems&&n.contentItems.length>0?n.contentItems:t.contentItems||[],a=Tt.get(e);return Object.assign(Object.assign(Object.assign(Object.assign({design:s,content:o,contentItems:r,context:i.context,mediaResolver:i.mediaResolver},t.compositionId?{compositionId:t.compositionId}:{}),t.entries?{entries:t.entries}:{}),t.adapters?{adapters:t.adapters}:{}),a?{workflow:a}:{})}const Dt=400,kt=300,Ot=/^\d+(?:\.\d+)?(?:px|%|em|rem|vh|vw|vmin|vmax|ch|cm|mm|in|pt|pc)?$/i,Lt=/^\d+(?:\.\d+)?$/;function Rt(e,t){const i=(null!=e?e:"").trim();return Ot.test(i)?Lt.test(i)?`${i}px`:i:`${t}px`}function zt(e,t){const i=(null!=e?e:"").trim().toLowerCase(),n=/^(\d+(?:\.\d+)?)(?:px)?$/.exec(i);return n?Number.parseFloat(n[1]):t}function Pt(t,i,n,o){return P(this,void 0,void 0,(function*(){N(t);const s=$(t)||"",r=i.direct;if(!r||2!==r.contractVersion||!r.moduleUrl)return!1;let a;try{a=yield ft(r.moduleUrl)}catch(e){return!1}if(!t.isConnected||($(t)||"")!==s)return!1;if(2!==a.contractVersion)return!1;xt(t);let d=null;if(!0===a.acceptsHostProps&&(d=function(e){var t;const i=null!==(t=bt.get(e))&&void 0!==t?t:new Set;let n=1;for(;i.has(n);)n+=1;return i.add(n),bt.set(e,i),n}(r.moduleUrl),d>1)){try{a=yield ft(function(e,t){if(1===t)return e;try{const i=new URL(e);return i.hash=String(t),i.toString()}catch(i){return`${e}#${t}`}}(r.moduleUrl,d))}catch(e){return It(r.moduleUrl,d),!1}if(!t.isConnected||($(t)||"")!==s||2!==a.contractVersion)return It(r.moduleUrl,d),!1}const l=document.createElement("div");l.setAttribute("data-widgetic-direct","1"),l.setAttribute("width",n||t.getAttribute("width")||"400");const c=t.getAttribute("height");c&&l.setAttribute("height",c);const h=Ue(t);h||function(e,t,i){e.style.display="block",e.style.boxSizing="border-box",e.style.width=Rt(t,Dt),e.style.height=Rt(i,kt),e.style.maxWidth="100%",e.style.overflow="hidden"}(l,n||t.getAttribute("width"),c);const g=l.attachShadow({mode:"open"}),u=document.createElement("style");u.textContent=(h?"":".widgetic-direct-target { width: 100%; height: 100%; }\n.widgetic-direct-target > :first-child { width: 100%; height: 100%; min-width: 0; min-height: 0; }\n")+a.getStyles();const m=document.createElement("div");m.className="widgetic-direct-target",g.append(u,m);const p={host:t,compositionId:s,payload:i,instance:null,stop:()=>{},listensOnWindow:!0!==a.acceptsHostProps,moduleUrl:r.moduleUrl,moduleSlot:d};let f;p.listensOnWindow&&(yt.add(p),Ct());try{f=a.mount(m,At(t,p.payload))}catch(e){throw null!==d&&It(r.moduleUrl,d),yt.delete(p)&&Ct(),e}p.instance=f;const v=function(e,t){const i="undefined"!=typeof MutationObserver?MutationObserver:null;if(!i)return()=>{};let n;try{n=new i((e=>{F(e)&&t()}))}catch(e){return()=>{}}return n.observe(e,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),()=>n.disconnect()}(t,(()=>Mt(t,p))),w=["play","pause","ended","seeking","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"],y=["position","navigate","complete","reset","metadata"],b=[];let I=!1,S=0;for(const e of w){const i=`widgetic:media:${e}`,n=t=>{if(I)return;const i=t,n=i.detail&&"object"==typeof i.detail?i.detail:{};try{ne().handleMediaEvent({type:e,compositionId:s,config:{persistState:!0,autoResume:!0},data:n})}catch(e){}};m.addEventListener(i,n),t.addEventListener(i,n),b.push((()=>{m.removeEventListener(i,n),t.removeEventListener(i,n)}))}const E=["play","pause","timeupdate","seeking","volumechange","ended"];for(const e of E){const t=t=>{if(I)return;const i=t.target;if(!i||"AUDIO"!==i.tagName&&"VIDEO"!==i.tagName)return;if("pause"===e&&i.ended)return;if("timeupdate"===e){const e=Date.now();if(e-S<750)return;S=e}const n="VIDEO"===i.tagName?"video":"audio";try{ne().handleMediaEvent({type:e,compositionId:s,config:{mediaType:n,persistState:!0,autoResume:!0},data:{mediaType:n,position:i.currentTime||0,duration:Number.isFinite(i.duration)?i.duration:void 0,volume:i.muted?0:i.volume,playing:!i.paused}})}catch(e){}};m.addEventListener(e,t,!0),b.push((()=>{m.removeEventListener(e,t,!0)}))}const C=e=>{const t=e.detail;if(!t||"object"!=typeof t)return;const i=Array.from(m.querySelectorAll("audio, video")),n=i.find((e=>!e.paused))||i[0]||null;I=!0;try{if("pause"===t.command)for(const e of i){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{e.currentTime=t.position}catch(e){}try{e.pause()}catch(e){}}else if("play"===t.command){if(n){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{n.currentTime=t.position}catch(e){}try{const e=n.play();e&&"function"==typeof e.catch&&e.catch((()=>{}))}catch(e){}}}else if("restore"===t.command&&t.state){if(n&&("number"==typeof t.state.volume&&(n.volume=Math.max(0,Math.min(1,t.state.volume))),"number"==typeof t.state.position&&!Number.isNaN(t.state.position)&&t.state.position>=0))try{n.currentTime=t.state.position}catch(e){}}else if("setVolume"===t.command&&"number"==typeof t.volume){const e=Math.max(0,Math.min(1,t.volume));for(const t of i)t.volume=e}}finally{setTimeout((()=>{I=!1}),150)}};m.addEventListener("widgetic:media:command",C),b.push((()=>{m.removeEventListener("widgetic:media:command",C)}));for(const e of y){const i=`widgetic:content:${e}`,n=t=>{const i=t,n=i.detail&&"object"==typeof i.detail?i.detail:{};try{ie().handleContentPositionEvent({type:e,compositionId:s,config:{contentType:"custom",persistState:!0,autoResume:!0},data:n})}catch(e){}};m.addEventListener(i,n),t.addEventListener(i,n),b.push((()=>{m.removeEventListener(i,n),t.removeEventListener(i,n)}))}p.stop=()=>{v();for(const e of b)e()},wt.set(t,p),t.appendChild(l),o(t);const M=n||t.getAttribute("width");if(b.push(gt({host:t,box:l,widthCss:Rt(M,Dt),widthPixels:lt(M,Dt),heightPixels:lt(c,kt)})),je(t))try{const i=function(t){var i,n;const{host:o,box:s,shadowRoot:r,compositionId:a}=t,d=s.offsetHeight>0?s.offsetHeight:t.fallbackHeightPixels,l=Ne(o,d),c=Qe({host:o,box:s,compositionId:a,settings:l,startHeight:d,originalHeightCss:s.style.height});c.startAtStoredHeight();let h=!1,g=null;const u=[],m=new WeakSet,p=()=>{if(!h)if(c.isAnimating())f();else try{const e=Ye(r,s,s.offsetHeight,l,m);null!==e&&c.follow(e)}catch(t){e.debug("[autoscale] The widget could not be measured",{compositionId:a,error:t})}},f=()=>{h||null!==g||(g=setTimeout((()=>{g=null,p()}),l.debounceDelay))};let v=null;try{"undefined"!=typeof MutationObserver&&(v=new MutationObserver(f),v.observe(r,{subtree:!0,childList:!0,characterData:!0,attributes:!0}))}catch(t){e.debug("[autoscale] The widget's changes cannot be watched",{compositionId:a,error:t})}let w=null;try{"undefined"!=typeof ResizeObserver&&(w=new ResizeObserver(f),w.observe(s))}catch(t){e.debug("[autoscale] The size of the widget's box cannot be watched",{compositionId:a,error:t})}const y=["load","transitionend","animationend"];for(const e of y)r.addEventListener(e,f,!0);try{null===(n=null===(i=document.fonts)||void 0===i?void 0:i.ready)||void 0===n||n.then(f,(()=>{}))}catch(e){}u.push(setTimeout(p,0));for(const e of Pe)u.push(setTimeout(f,e));return{refresh:f,stop(){if(!h){h=!0,null!==g&&clearTimeout(g),g=null;for(const e of u)clearTimeout(e);null==v||v.disconnect(),null==w||w.disconnect();for(const e of y)r.removeEventListener(e,f,!0)}}}}({host:t,box:l,shadowRoot:g,compositionId:s,fallbackHeightPixels:zt(c,kt)});b.push((()=>i.stop()))}catch(e){}try{ie().resumeWidgetPosition(s)}catch(e){}try{ne().resumeWidget(s)}catch(e){}return t.dispatchEvent(new CustomEvent("widgetic:ready",{bubbles:!0,composed:!0,detail:{compositionId:s}})),!0}))}const Ht=new WeakMap;function Ut(e,t){jt(e),Ht.set(e,t)}function jt(t){const i=Ht.get(t);if(!i)return!1;Ht.delete(t);try{i.stop()}catch(t){e.debug("[workflows] A workflow failed while it was being stopped",{error:t})}return!0}const Bt="data-widgetic-refused",Nt="data-widgetic-context-invalid",$t="data-widgetic-composition-tracked";function _t(e,t){const i=e.getAttribute($t);if(i&&i!==t){jt(e),function(e){e.removeAttribute("data-widgetic-mounting"),e.removeAttribute("data-widgetic-mounted"),e.removeAttribute(Me),e.removeAttribute(Bt),e.removeAttribute(Nt)}(e),xt(e),Ze(e);for(const t of Array.from(e.querySelectorAll("iframe")))t.remove();e.style.display="",e.removeAttribute("data-widgetic-overlay")}e.setAttribute($t,t)}const Ft=/^[a-z][a-z0-9_]{0,62}$/,Vt=/^[a-z][a-z0-9_]{0,39}$/;function Kt(e){if(e.length>200)return null;const t=e.indexOf("@");if(-1===t)return/^[a-z][a-z0-9_]{0,31}$/.test(e)?{metric:e,selector:null}:null;const i=e.slice(0,t),n=e.slice(t+1);return/^[a-z][a-z0-9_]{0,31}$/.test(i)&&""!==n&&n===n.trim()?{metric:i,selector:n}:null}function qt(e){if(e.length>200)return!1;const t=e.indexOf("@"),i=-1===t?e:e.slice(0,t);return!!Vt.test(i)&&(-1===t||""!==e.slice(t+1))}function Yt(e){const t=[],i=[],n=[],o=e=>{t.length<20&&Ft.test(e)&&!t.includes(e)&&t.push(e)};for(const t of e.inputTables)o(t);for(const t of e.inputColumns){if(i.length>=50)break;Ft.test(t.table)&&Ft.test(t.column)&&(i.some((e=>e.table===t.table&&e.column===t.column))||(i.push({table:t.table,column:t.column}),o(t.table)))}for(const t of e.actionIds){if(n.length>=20)break;qt(t)&&!n.includes(t)&&n.push(t)}return{tables:t,fields:i,goals:n}}function Gt(e,t){const i=[];for(const e of t.goals){const t=Kt(e);t&&i.push({id:e,metric:t.metric,goalTarget:t.selector})}return{compositionId:e,tables:t.tables,fields:t.fields,goals:i}}const Qt=["context","values","media-resolver"],Jt=new Set(["widgetic:ready","widgetic:error","widgetic:submitted","widgetic:resize","widgetic:data","widgetic:interaction","widgetic:form-submit","widgetic:goal"]),Zt={play:!0,pause:!0,stop:!0,ended:!0,seeking:!0,seeked:!0,timeupdate:!0,progress:!0,durationchange:!0,loadedmetadata:!0,volumechange:!0,trackchange:!0,playlistchange:!0},Xt={position:!0,navigate:!0,complete:!0,reset:!0,metadata:!0};const ei="goal-reporter";const ti=new WeakMap;class ii{constructor(e,t,i,n,o){this.host=e,this.iframe=t,this.gatewayOrigin=i,this.compositionId=n,this.services=o,this.readyDispatched=!1,this.pendingWidgetUpdate=null,this.latestAbGoal=null,this.latestWorkflowWatch=null,this.attributeFlushScheduled=!1,this.attributeObserver=null,N(this.host),this.onWindowMessage=e=>this.handleWrapperMessage(e),window.addEventListener("message",this.onWindowMessage),this.iframe.addEventListener("load",(()=>{this.postHostSnapshot(),this.flushPendingWidgetUpdate()})),this.observeHostAttributes()}observeHostAttributes(){const e="undefined"!=typeof MutationObserver?MutationObserver:null;if(!e)return;let t;try{t=new e((e=>{e.some((e=>"attributes"===e.type&&e.attributeName&&Qt.includes(e.attributeName)))&&this.scheduleHostSnapshot()}))}catch(e){return}t.observe(this.host,{attributes:!0,attributeFilter:[...Qt]}),this.attributeObserver=t}scheduleHostSnapshot(){this.attributeFlushScheduled||(this.attributeFlushScheduled=!0,queueMicrotask((()=>{this.attributeFlushScheduled=!1,this.postHostSnapshot()})))}postHostSnapshot(){try{const e=st(this.host);e.contextInvalid?this.host.setAttribute(Nt,"1"):this.host.removeAttribute(Nt);const t=this.iframe.contentWindow;if(!t)return;if(!this.frameCanReceive())return;const i=at(this.compositionId,e,this.services);t.postMessage(i,this.gatewayOrigin),this.postAbGoal(),this.postWorkflowWatch()}catch(e){}}sendAbGoal(e){this.latestAbGoal=e,this.postAbGoal()}postAbGoal(){if(this.latestAbGoal)try{const e=this.iframe.contentWindow;if(!e||!this.frameCanReceive())return;e.postMessage({type:"widgetic:ab-goal",compositionId:this.compositionId,metric:this.latestAbGoal.metric,goalTarget:this.latestAbGoal.goalTarget},this.gatewayOrigin)}catch(e){}}sendWorkflowWatch(e){this.latestWorkflowWatch=e,this.postWorkflowWatch()}postWorkflowWatch(){var e,t;if(this.latestWorkflowWatch)try{const i=this.iframe.contentWindow;if(!i||!this.frameCanReceive())return;i.postMessage((e=this.compositionId,t=this.latestWorkflowWatch,{type:"widgetic:workflow-watch",version:1,compositionId:e,tables:t.tables,fields:t.fields,goals:t.goals}),this.gatewayOrigin)}catch(e){}}sendWidgetUpdate(e){try{const t=this.iframe.contentWindow;if(!t)return;if(!this.frameCanReceive())return void(this.pendingWidgetUpdate=e);t.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update",compositionId:this.compositionId},e.design?{design:e.design}:{}),e.content?{content:e.content}:{}),e.contentItems?{contentItems:e.contentItems}:{}),this.gatewayOrigin)}catch(e){}}flushPendingWidgetUpdate(){const e=this.pendingWidgetUpdate;e&&(this.pendingWidgetUpdate=null,this.sendWidgetUpdate(e))}frameCanReceive(){return!function(e){var t;try{return"about:blank"===(null===(t=e.contentWindow)||void 0===t?void 0:t.location.href)}catch(e){return!1}}(this.iframe)}handleWrapperMessage(e){var t,i;if(e.source!==this.iframe.contentWindow)return;if(e.origin!==this.gatewayOrigin)return;const n=e.data;if(!n||"object"!=typeof n||Array.isArray(n))return;const o=n.type;if("string"!=typeof o)return;const s=n.compositionId;if("string"==typeof s&&s!==this.compositionId)return;let r=null!==(i=null!==(t=n.detail)&&void 0!==t?t:n.payload)&&void 0!==i?i:n.data;if(void 0===r){const e={};for(const t of Object.keys(n))"type"!==t&&"compositionId"!==t&&(e[t]=n[t]);Object.keys(e).length>0&&(r=e)}const a=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length>8192?{}:e}catch(e){return{}}}(r),d=Object.assign({compositionId:this.compositionId},a);if(o.startsWith("widgetic:media:")){const e=o.replace("widgetic:media:","");if(l=e,Object.prototype.hasOwnProperty.call(Zt,l))try{ne().handleMediaEvent({type:e,compositionId:this.compositionId,config:{persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else{var l;if(o.startsWith("widgetic:content:")){const e=o.replace("widgetic:content:","");if(function(e){return Object.prototype.hasOwnProperty.call(Xt,e)}(e))try{ie().handleContentPositionEvent({type:e,compositionId:this.compositionId,config:{contentType:"custom",persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(Jt.has(o))if("widgetic:ready"!==o)this.dispatchHostEvent(o,d);else{try{ie().resumeWidgetPosition(this.compositionId)}catch(e){}try{ne().resumeWidget(this.compositionId)}catch(e){}if(this.readyDispatched)return;this.readyDispatched=!0,this.postHostSnapshot(),this.flushPendingWidgetUpdate();const e=function(e){const t=e.capabilities;return Array.isArray(t)?t.filter((e=>"string"==typeof e&&e.length<=40)).slice(0,32):[]}(a);this.dispatchHostEvent("widgetic:ready",Object.assign({compositionId:this.compositionId},e.length>0?{capabilities:e}:{}))}}}dispatchHostEvent(e,t){this.host.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}destroy(){var e;window.removeEventListener("message",this.onWindowMessage),null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null}}function ni(e){return ti.get(e)}function oi(e,t,i){e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{compositionId:t,code:i},bubbles:!0,composed:!0}))}const si="widgetic:workflow-event",ri="widgetic:workflow-step",ai=/^[A-Za-z0-9_.:-]{1,64}$/,di=new Set(["__proto__","constructor","prototype"]);function li(e){return"string"==typeof e?e.length>200?e.slice(0,200):e:"number"==typeof e?Number.isFinite(e)?e:void 0:"boolean"==typeof e?e:void 0}function ci(e){if("object"!=typeof e||null===e||Array.isArray(e))return null;const{name:t,values:i}=e;if("string"!=typeof t||!ai.test(t))return null;const n={};if("object"==typeof i&&null!==i&&!Array.isArray(i)){let e=0;for(const t of Object.keys(i)){if(e>=12)break;if(di.has(t)||!ai.test(t))continue;const o=li(i[t]);void 0!==o&&(n[t]=o,e+=1)}}return{name:t,values:n}}function hi(t,i,n){if(!t||"function"!=typeof t.dispatchEvent)return!1;const o=ci({name:i,values:n});return o?(t.dispatchEvent(new CustomEvent(si,{detail:o})),!0):(e.warn("[workflows] The page event was not sent: its name is not one a workflow can wait for",{name:i}),!1)}class gi{constructor(){this.events=[]}add(e){this.events.push(e),this.events.length>20&&this.events.shift()}take(){const e=this.events;return this.events=[],e}clear(){this.events=[]}}function ui(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(Ce)||(e.style.display="block")}function mi(t,i,n,o,s){ui(t);const r=$(t),a=q(t,n),d=x(i,o||t.getAttribute("width")||"400",t.getAttribute("height")||"300",r||void 0,a);t.appendChild(d);const l=o||t.getAttribute("width");if(gt({host:t,box:d,widthCss:Rt(l,Dt),widthPixels:lt(l,Dt),heightPixels:lt(t.getAttribute("height"),kt)}),je(t))try{!function(e){const{host:t,iframe:i,compositionId:n}=e;Ze(t);const o=i.offsetHeight>0?i.offsetHeight:e.fallbackHeightPixels,s=Ne(t,o),r=Qe({host:t,box:i,compositionId:n,settings:s,startHeight:o,originalHeightCss:""});r.startAtStoredHeight();let a=!1,d=null,l=null;const c=()=>{l=null,a||null===d||r.follow(d)},h=e=>{var t;const i=null===(t=e.detail)||void 0===t?void 0:t.height;"number"!=typeof i||!Number.isFinite(i)||i<=0||(d=i,null===l&&(l=setTimeout(c,s.debounceDelay)))};t.addEventListener("widgetic:resize",h);const g={refresh:c,stop(){a||(a=!0,null!==l&&clearTimeout(l),l=null,t.removeEventListener("widgetic:resize",h))}};Je.set(t,g)}({host:t,iframe:d,compositionId:r||"",fallbackHeightPixels:zt(t.getAttribute("height"),300)})}catch(t){e.debug("[autoscale] The frame could not be followed",{instanceId:r,error:t})}if(r)try{!function(e,t,i,n,o){let s;try{s=new URL(i).origin}catch(e){return}const r=ti.get(e);r&&r.destroy();const a=new ii(e,t,s,n,o);ti.set(e,a),a.postHostSnapshot()}(t,d,i,r,s)}catch(e){}try{Y(t,n,(e=>{const i=ni(t);if(i)i.sendWidgetUpdate({design:e.design,content:e.content,contentItems:e.contentItems});else if(d.contentWindow)try{d.contentWindow.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update"},e.design?{design:e.design}:{}),e.content?{content:e.content}:{}),e.contentItems?{contentItems:e.contentItems}:{}),"*")}catch(e){}}))}catch(e){}}function pi(t,i,n){var o;const s=$(t)||"",r=q(t,i);"iframe"!==t.getAttribute("render-mode")&&"true"!==t.getAttribute("use-iframe")&&(null===(o=r.direct)||void 0===o?void 0:o.moduleUrl)||!r.embedUrl?function(t,i,n){return P(this,void 0,void 0,(function*(){try{return yield Pt(t,i,n,ui)}catch(i){return e.warn("[mount] The widget threw while it was mounted in the page, so it is shown in its frame",{instanceId:$(t),error:i}),!1}}))}(t,r,n).then((i=>{if(!i&&t.isConnected&&($(t)||"")===s&&!t.getAttribute("data-widgetic-mounted"))return r.embedUrl?(e.debug("[mount] The widget cannot be mounted in the page, so it is shown in its frame",{instanceId:s}),void mi(t,r.embedUrl,r,n,rt(r))):void wi(t,s,"NOT_FOUND","not_found")})):mi(t,r.embedUrl,r,n,rt(r))}function fi(t){if(!t.hasAttribute("workflow-id"))return null;try{return import("./workflows.js").catch((t=>(e.warn("[workflows] The workflow code could not be loaded, so the tag is embedded as it is",{error:t}),null)))}catch(t){return e.warn("[workflows] The workflow code could not be loaded, so the tag is embedded as it is",{error:t}),Promise.resolve(null)}}function vi(t,i,n,o){n?n.then((n=>{var s;if(!t.isConnected||t.getAttribute("data-widgetic-mounted"))return;let r=null;try{r=null!==(s=null==n?void 0:n.startWorkflowEmbed(t,Object.assign({hydrate:e=>{yi(e)},markMounted:ui},o?{width:o}:{})))&&void 0!==s?s:null}catch(t){e.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{error:t})}r||pi(t,i,o)})):pi(t,i,o)}function wi(e,t,i,n){e.removeAttribute("data-widgetic-mounting"),e.setAttribute(Bt,i),oi(e,t,n)}function yi(t){var i;N(t);const n=V(t),o=null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null;if(K(t),o&&_t(t,o),t.getAttribute("data-widgetic-mounted")||t.getAttribute("data-widgetic-mounting")||t.getAttribute(Me)||t.getAttribute(Bt))return!0;const s=t.getAttribute("src");if(s)return mi(t,s),!0;if(!n||!o)return!1;const r=t.hasAttribute(Me),a=function(t){var i,n,o,s,r;let a;try{a=U(t)}catch(t){return e.warn("[published-host-display] Could not read the embed's display settings",{error:t}),{suppressed:!1}}return Ee(null===(n=null===(i=a.device)||void 0===i?void 0:i.mobileEnabled)||void 0===n||n,null===(s=null===(o=a.device)||void 0===o?void 0:o.desktopEnabled)||void 0===s||s)?("overlay"===(null===(r=a.triggers)||void 0===r?void 0:r.mode)&&(t.style.display="none",t.setAttribute(Ce,"pending")),{suppressed:!1,triggers:a.triggers}):(t.style.display="none",t.setAttribute(Me,"true"),e.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:a.compositionId,device:a.device}),{suppressed:!0})}(t);if(a.suppressed)return r||oi(t,o,"device_restricted"),!0;t.setAttribute("data-widgetic-mounting","1");const d="composition"===n.kind?fi(t):null;return("widget"===n.kind?C(o):M(o)).then((e=>{var i;if(t.getAttribute("data-widgetic-mounted"))return;if("refused"===e.status)return t.removeAttribute("data-widgetic-mounting"),t.setAttribute(Bt,e.refusal.code),T(o,e.refusal),void oi(t,o,W(e.refusal.code)||"domain_not_allowed");if("failed"===e.status)return void wi(t,o,e.failure.gatewayCode,e.failure.stateCode);const n="found"===e.status?e.payload:null;if(!(null==n?void 0:n.embedUrl))return t.removeAttribute("data-widgetic-mounting"),void wi(t,o,"NOT_FOUND","not_found");const{triggers:s}=a;if("overlay"!==(null==s?void 0:s.mode))vi(t,n,d),s&&Ae(t,s);else{const e=(null===(i=s.overlay)||void 0===i?void 0:i.fullWidth)?"100%":void 0;Ae(t,s,(()=>vi(t,n,d,e)))}})),!0}function bi(e=document){const t=e.querySelectorAll("widgetic, widgetic-embed");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&yi(e)&&(i+=1);return i}const Ii={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class Si{constructor(e={}){this.compositionCache=new Map,this.widgetCache=new Map,this.pendingCompositionRequests=new Map,this.pendingWidgetRequests=new Map,this.compositionResolvers=new Map,this.widgetResolvers=new Map,this.compositionBatchQueue=[],this.widgetBatchQueue=[],this.compositionBatchTimer=null,this.widgetBatchTimer=null,this.lastBatchError=null,this.config=Object.assign(Object.assign({},Ii),e)}getCompositions(e){return P(this,void 0,void 0,(function*(){"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-start");try{const t=[],i=[];for(const n of e){const e=this.getCachedComposition(n);if(e){t.push(e);continue}const o=this.pendingCompositionRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchCompositions(i);t.push(...e)}return Object.defineProperty(t,"compositions",{get(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(t,"success",{value:!this.lastBatchError,enumerable:!1,configurable:!0}),Object.defineProperty(t,"error",{value:this.lastBatchError||void 0,enumerable:!1,configurable:!0}),t}finally{"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-end")}}))}getWidgets(e){return P(this,void 0,void 0,(function*(){const t=[],i=[];for(const n of e){const e=this.getCachedWidget(n);if(e){t.push(e);continue}const o=this.pendingWidgetRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchWidgets(i);t.push(...e)}return t}))}getComposition(e){return P(this,void 0,void 0,(function*(){const t=yield this.getCompositions([e]);if(0===t.length)throw new Error(`Composition not found: ${e}`);return t[0]}))}getWidget(e){return P(this,void 0,void 0,(function*(){const t=yield this.getWidgets([e]);if(0===t.length)throw new Error(`Widget not found: ${e}`);return t[0]}))}batchCompositions(e){return P(this,void 0,void 0,(function*(){var t;const i=[];for(const t of e)if(this.pendingCompositionRequests.has(t))i.push(this.pendingCompositionRequests.get(t));else{const e=new Promise(((e,i)=>{this.compositionBatchQueue.push(t),this.scheduleCompositionBatch(),this.compositionResolvers.set(t,{resolve:e,reject:i})}));this.pendingCompositionRequests.set(t,e),i.push(e)}const n=yield Promise.allSettled(i),o=n.find((e=>"rejected"===e.status));return this.lastBatchError=o?(null===(t=o.reason)||void 0===t?void 0:t.message)||String(o.reason):null,n.filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}batchWidgets(e){return P(this,void 0,void 0,(function*(){const t=[];for(const i of e)if(this.pendingWidgetRequests.has(i))t.push(this.pendingWidgetRequests.get(i));else{const e=new Promise(((e,t)=>{this.widgetBatchQueue.push(i),this.scheduleWidgetBatch(),this.widgetResolvers.set(i,{resolve:e,reject:t})}));this.pendingWidgetRequests.set(i,e),t.push(e)}return(yield Promise.allSettled(t)).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}scheduleCompositionBatch(){this.compositionBatchTimer||(this.compositionBatchTimer=window.setTimeout((()=>{this.executeCompositionBatch()}),this.config.debounceDelay))}scheduleWidgetBatch(){this.widgetBatchTimer||(this.widgetBatchTimer=window.setTimeout((()=>{this.executeWidgetBatch()}),this.config.debounceDelay))}executeCompositionBatch(){return P(this,void 0,void 0,(function*(){const e=[...this.compositionBatchQueue];if(this.compositionBatchQueue=[],this.compositionBatchTimer=null,0!==e.length)try{const t=yield this.fetchCompositionsBatch(e);for(const e of t.compositions){this.cacheComposition(e);const t=this.compositionResolvers.get(e.id);t&&(t.resolve(e),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.compositionResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}for(const t of e){const e=this.compositionResolvers.get(t);e&&(e.reject(new Error(`Composition not found in batch response: ${t}`)),this.compositionResolvers.delete(t)),this.pendingCompositionRequests.delete(t)}}catch(t){for(const i of e){const e=this.compositionResolvers.get(i);e&&(e.reject(t),this.compositionResolvers.delete(i)),this.pendingCompositionRequests.delete(i)}}}))}executeWidgetBatch(){return P(this,void 0,void 0,(function*(){const e=[...this.widgetBatchQueue];if(this.widgetBatchQueue=[],this.widgetBatchTimer=null,0!==e.length)try{const t=yield this.fetchWidgetsBatch(e);for(const e of t.widgets){this.cacheWidget(e);const t=this.widgetResolvers.get(e.id);t&&(t.resolve(e),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.widgetResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}for(const t of e){const e=this.widgetResolvers.get(t);e&&(e.reject(new Error(`Widget not found in batch response: ${t}`)),this.widgetResolvers.delete(t)),this.pendingWidgetRequests.delete(t)}}catch(t){for(const i of e){const e=this.widgetResolvers.get(i);e&&(e.reject(t),this.widgetResolvers.delete(i)),this.pendingWidgetRequests.delete(i)}}}))}fetchCompositionsBatch(e){return P(this,arguments,void 0,(function*(e,r=1){var a,d,l;try{const r=yield t(),d=new i({basePath:o(),apiKey:()=>P(this,void 0,void 0,(function*(){return r})),headers:{"X-SDK-Version":`embed-sdk/${n}`}}),l=new s(d),c=yield l.getCompositionsBatch({getCompositionsBatchRequest:{compositionIds:e}}),h=c.compositions||[];return{compositions:h.map((e=>{if(!e||"object"!=typeof e)return e;const{internalConfig:t,adminNotes:i}=e;return H(e,["internalConfig","adminNotes"])})),errors:null===(a=c.errors)||void 0===a?void 0:a.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(r<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,r-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchCompositionsBatch(e,r+1)}const i=null===(d=null==t?void 0:t.response)||void 0===d?void 0:d.status,n=null===(l=null==t?void 0:t.response)||void 0===l?void 0:l.statusText;if("number"==typeof i){let e=`HTTP ${i}: ${n||"Request failed"}`;switch(i){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these compositions";break;case 404:e="Composition not found: One or more compositions do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}fetchWidgetsBatch(e){return P(this,arguments,void 0,(function*(e,s=1){var a,d,l;try{const s=yield t(),d=new i({basePath:o(),apiKey:()=>P(this,void 0,void 0,(function*(){return s})),headers:{"X-SDK-Version":`embed-sdk/${n}`}}),l=new r(d),c=yield l.getWidgetsBatch({getWidgetsBatchRequest:{widgetIds:e}});return{widgets:c.widgets||[],errors:null===(a=c.errors)||void 0===a?void 0:a.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(s<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,s-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchWidgetsBatch(e,s+1)}const i=null===(d=null==t?void 0:t.response)||void 0===d?void 0:d.status,n=null===(l=null==t?void 0:t.response)||void 0===l?void 0:l.statusText;if("number"==typeof i){let e=`HTTP ${i}: ${n||"Request failed"}`;switch(i){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these widgets";break;case 404:e="Widget not found: One or more widgets do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}getCachedComposition(e){const t=this.compositionCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.compositionCache.delete(e),null):t.data}getCachedWidget(e){const t=this.widgetCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.widgetCache.delete(e),null):t.data}cacheComposition(e){this.compositionCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}cacheWidget(e){this.widgetCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}clearCache(){this.compositionCache.clear(),this.widgetCache.clear()}getCacheStats(){return{compositions:{size:this.compositionCache.size,entries:Array.from(this.compositionCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},widgets:{size:this.widgetCache.size,entries:Array.from(this.widgetCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},pending:{compositions:this.pendingCompositionRequests.size,widgets:this.pendingWidgetRequests.size},queues:{compositions:this.compositionBatchQueue.length,widgets:this.widgetBatchQueue.length}}}}let Ei=null;function Ci(){return Ei||(Ei=new Si),Ei}function Mi(){Ei=null}var Ti=Object.freeze({__proto__:null,BatchApiClient:Si,getBatchClient:Ci,resetBatchClient:Mi});const Wi={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:a()};class xi{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},Wi),e)}loadModule(e){return P(this,arguments,void 0,(function*(e,t={}){const i=this.getModuleKey(e.id,t.version||e.version),n=this.loadingPromises.get(i);if(n&&!t.force)return n;if(!t.force){const e=this.getCachedModule(i);if(e)return{module:e.module,url:e.url,loadTime:0,cached:!0}}const o=this.doLoadModule(e,t);this.loadingPromises.set(i,o);try{const e=yield o;return this.loadingPromises.delete(i),e}catch(e){throw this.loadingPromises.delete(i),e}}))}loadModules(e){return P(this,arguments,void 0,(function*(e,t={}){const i=new Map,n=new Map;for(const t of e)if(n.set(t.id,t),t.dependencies){this.dependencyGraph.set(t.id,new Set(t.dependencies));for(const e of t.dependencies)i.set(e,t)}const o=this.resolveDependencyOrder(e),s=[];for(const e of o)try{const i=yield this.loadModule(e,t);s.push(i)}catch(e){}return s}))}getLatestVersion(e){return P(this,void 0,void 0,(function*(){try{const t=`${this.config.cdnBaseUrl}/${e}/latest`,i=yield this.fetchWithHttp3(t,{timeout:5e3});if(i.ok){return(yield i.json()).version}}catch(e){}return null}))}preloadModules(e){return P(this,void 0,void 0,(function*(){const t=e.map((e=>this.loadModule(e,{timeout:3e4}).catch((e=>{}))));yield Promise.allSettled(t)}))}invalidateModule(e,t){if(t){const i=this.getModuleKey(e,t);this.moduleCache.delete(i)}else{Array.from(this.moduleCache.keys()).filter((t=>t.startsWith(`${e}@`))).forEach((e=>this.moduleCache.delete(e)))}}clearCache(){this.moduleCache.clear(),this.loadingPromises.clear()}getCacheStats(){return{size:this.moduleCache.size,entries:Array.from(this.moduleCache.entries()).map((([e,t])=>({key:e,version:t.version,age:Date.now()-t.timestamp,ttl:t.ttl,url:t.url}))),loading:this.loadingPromises.size,http3Supported:this.http3Supported}}doLoadModule(e,t){return P(this,void 0,void 0,(function*(){const i=Date.now(),n=t.version||e.version,o=this.resolveModuleUrl(e,n);try{e.dependencies&&e.dependencies.length>0&&(yield this.loadDependencies(e.dependencies));const s=yield this.loadModuleFromUrl(o,{timeout:t.timeout||this.config.loadTimeout,retries:t.retries||this.config.maxRetries});if(!this.validateModule(s))throw new Error(`Invalid module structure for ${e.id}`);const r=this.getModuleKey(e.id,n);return this.cacheModule(r,{module:s,url:o,timestamp:Date.now(),version:n,ttl:this.config.cacheTTL}),{module:s,url:o,loadTime:Date.now()-i,cached:!1}}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load module ${e.id}@${n}: ${i}`)}}))}loadModuleFromUrl(e,t){return P(this,void 0,void 0,(function*(){let i=null;for(let n=1;n<=t.retries;n++)try{if(e.endsWith(".mjs")||e.includes("type=module")){const i=yield this.loadEsModule(e,t.timeout);return this.extractWidgetFromEsModule(i)}const i=yield this.fetchModuleText(e,t.timeout);return this.evaluateUmdModule(i,e)}catch(e){if(i=e instanceof Error?e:new Error(String(e)),n<t.retries){const e=this.config.retryDelay*Math.pow(2,n-1);yield new Promise((t=>setTimeout(t,e)))}}throw i||new Error("Module loading failed")}))}loadEsModule(e,t){return P(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{const o=setTimeout((()=>{n(new Error(`Module load timeout: ${e}`))}),t);import(e).then((e=>{clearTimeout(o),i(e)})).catch((e=>{clearTimeout(o),n(e)}))}))}))}fetchModuleText(e,t){return P(this,void 0,void 0,(function*(){const i=yield this.fetchWithHttp3(e,{timeout:t});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return yield i.text()}))}fetchWithHttp3(e,t){return P(this,void 0,void 0,(function*(){null===this.http3Supported&&(this.http3Supported=yield this.detectHttp3Support());const i={signal:AbortSignal.timeout(t.timeout)};return fetch(e,i)}))}detectHttp3Support(){return P(this,void 0,void 0,(function*(){var e;try{if("connection"in navigator&&"effectiveType"in navigator.connection){const e=navigator.connection;return"4g"===e.effectiveType||"5g"===e.effectiveType}const t=`${this.config.cdnBaseUrl}/test-http3`,i=yield fetch(t,{method:"HEAD",signal:AbortSignal.timeout(2e3)}).catch((()=>null));return(null===(e=null==i?void 0:i.headers.get("alt-svc"))||void 0===e?void 0:e.includes("h3"))||!1}catch(e){return!1}}))}extractWidgetFromEsModule(e){const t=e.default||e.Widget||e.widget||e;if(!t)throw new Error("No widget found in module exports");return{id:t.id||"unknown",version:t.version||"1.0.0",component:t.component||t,metadata:t.metadata,dependencies:t.dependencies}}evaluateUmdModule(e,t){const i={window:"undefined"!=typeof window?window:{},document:"undefined"!=typeof document?document:{},console:console,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval},n=new Function("window","document","console","setTimeout","clearTimeout","setInterval","clearInterval",`\n let module = { exports: {} };\n let exports = module.exports;\n \n ${e}\n \n return module.exports.default || module.exports;\n `)(i.window,i.document,i.console,i.setTimeout,i.clearTimeout,i.setInterval,i.clearInterval);if(!n)throw new Error(`Module evaluation failed: ${t}`);return{id:n.id||"unknown",version:n.version||"1.0.0",component:n.component||n,metadata:n.metadata,dependencies:n.dependencies}}loadDependencies(e){return P(this,void 0,void 0,(function*(){const t=e.map((e=>P(this,void 0,void 0,(function*(){try{if("undefined"!=typeof window&&window[e])return}catch(e){}}))));yield Promise.allSettled(t)}))}resolveDependencyOrder(e){const t=new Set,i=new Set,n=[],o=new Map(e.map((e=>[e.id,e]))),s=e=>{if(i.has(e.id))throw new Error(`Circular dependency detected: ${e.id}`);if(!t.has(e.id)){if(i.add(e.id),e.dependencies)for(const t of e.dependencies){const e=o.get(t);e&&s(e)}i.delete(e.id),t.add(e.id),n.push(e)}};for(const i of e)t.has(i.id)||s(i);return n}resolveModuleUrl(e,t){return e.moduleUrl?e.moduleUrl.replace("{{version}}",t):`${this.config.cdnBaseUrl}/${e.id}/${t}/widget.mjs`}validateModule(e){return!!(e&&e.id&&e.version&&e.component)}getModuleKey(e,t){return`${e}@${t}`}getCachedModule(e){const t=this.moduleCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.moduleCache.delete(e),null):t}cacheModule(e,t){this.moduleCache.set(e,t)}}let Ai=null;function Di(){return Ai||(Ai=new xi),Ai}function ki(){Ai=null}var Oi=Object.freeze({__proto__:null,ModuleLoader:xi,getModuleLoader:Di,resetModuleLoader:ki});class Li{constructor(e){this.intersectionObserver=null,this.isInViewport=!0,this.hasBeenInViewport=!1,this.scrollListener=null,this.lastScrollY=0,this.scrollDistance=0,this.isTriggered=!1,this.debounceTimer=null,this.rafId=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,totalScrollDistance:0,viewportChanges:0},this.widgetId=e.widgetId,this.element=e.element,this.type=e.type,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,threshold:.1,distance:100,direction:"down",debounce:100}}initialize(){this.config.enabled&&(e.debug("Initializing ScrollTrigger",{widgetId:this.widgetId,type:this.type,config:this.config}),this.lastScrollY=window.scrollY,"viewport"===this.type?this.initializeViewportDetection():"distance"===this.type&&this.initializeScrollDistance())}initializeViewportDetection(){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:this.config.threshold||.1,rootMargin:"0px"}),this.intersectionObserver.observe(this.element),e.debug("Viewport detection initialized",{widgetId:this.widgetId,threshold:this.config.threshold})}initializeScrollDistance(){this.scrollListener=this.debounce(this.handleScrollDistance.bind(this),this.config.debounce||100),window.addEventListener("scroll",this.scrollListener,{passive:!0}),e.debug("Scroll distance tracking initialized",{widgetId:this.widgetId,distance:this.config.distance})}handleIntersection(t){if(this.isDestroyed)return;const i=t[t.length-1];if(!i)return;const n=this.isInViewport;if(this.isInViewport=i.isIntersecting,i.isIntersecting&&(this.hasBeenInViewport=!0),this.stats.viewportChanges++,e.debug("Viewport intersection changed",{widgetId:this.widgetId,isIntersecting:this.isInViewport,intersectionRatio:i.intersectionRatio}),n&&!this.isInViewport){if(!this.hasBeenInViewport)return;this.triggerActivated("scroll-out-of-view",{intersectionRatio:i.intersectionRatio,boundingClientRect:i.boundingClientRect})}else!n&&this.isInViewport&&this.triggerDeactivated("scroll-back-in-view",{intersectionRatio:i.intersectionRatio,boundingClientRect:i.boundingClientRect})}observeElement(t){!this.isDestroyed&&"viewport"===this.type&&this.intersectionObserver&&t!==this.element&&(this.intersectionObserver.unobserve(this.element),this.element=t,this.intersectionObserver.observe(t),e.debug("ScrollTrigger now watching another element",{widgetId:this.widgetId}))}handleScrollDistance(){this.isDestroyed||(this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame((()=>{const t=window.scrollY,i=t-this.lastScrollY;this.stats.totalScrollDistance+=Math.abs(i);const n=i>0,o=i<0;"down"===this.config.direction&&n?this.scrollDistance+=i:("up"===this.config.direction&&o||"any"===this.config.direction)&&(this.scrollDistance+=Math.abs(i));const s=this.config.distance||100;!this.isTriggered&&this.scrollDistance>=s&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{scrollDistance:this.scrollDistance,direction:n?"down":"up",scrollY:t})),this.lastScrollY=t,e.debug("Scroll distance updated",{widgetId:this.widgetId,scrollDistance:this.scrollDistance,requiredDistance:s,isTriggered:this.isTriggered})})))}triggerActivated(t,i){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const n=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:t,triggerData:i}});document.dispatchEvent(n),e.debug("Scroll trigger activated",{widgetId:this.widgetId,triggerType:t,triggerData:i})}triggerDeactivated(t,i){const n=new CustomEvent("widgetic:trigger-deactivated",{detail:{widgetId:this.widgetId,triggerType:t,triggerData:i}});document.dispatchEvent(n),e.debug("Scroll trigger deactivated",{widgetId:this.widgetId,triggerType:t,triggerData:i})}debounce(e,t){return i=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e()}),t)}}updateConfig(t){if(this.isDestroyed)return;const i=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),t),void 0!==t.threshold&&"viewport"===this.type&&(this.destroy(),this.isDestroyed=!1,this.initializeViewportDetection()),void 0!==t.distance&&"distance"===this.type&&(this.scrollDistance=0,this.isTriggered=!1),e.debug("ScrollTrigger config updated",{widgetId:this.widgetId,oldConfig:i,newConfig:this.config})}reset(){this.isDestroyed||(this.scrollDistance=0,this.isTriggered=!1,this.lastScrollY=window.scrollY,e.debug("ScrollTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{type:this.type,isInViewport:this.isInViewport,scrollDistance:this.scrollDistance,isTriggered:this.isTriggered,currentScrollY:window.scrollY})}isActive(){return"viewport"===this.type?!this.isInViewport:"distance"===this.type&&this.isTriggered}forceActivate(){"viewport"===this.type?this.triggerActivated("scroll-out-of-view",{manual:!0}):"distance"===this.type&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{manual:!0}))}forceDeactivate(){"viewport"===this.type&&this.triggerDeactivated("scroll-back-in-view",{manual:!0})}destroy(){this.isDestroyed||(this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.scrollListener&&(window.removeEventListener("scroll",this.scrollListener),this.scrollListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.isDestroyed=!0,e.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class Ri{constructor(e){this.mouseLeaveListener=null,this.lastMouseY=0,this.isTriggered=!1,this.scrollUpListener=null,this.visibilityChangeListener=null,this.backButtonListener=null,this.touchStartListener=null,this.touchEndListener=null,this.lastScrollY=0,this.scrollUpDistance=0,this.touchStartY=0,this.touchStartTime=0,this.isScrollingUp=!1,this.debounceTimer=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,desktopTriggers:0,mobileTriggers:0,backButtonTriggers:0,scrollUpTriggers:0,tabSwitchTriggers:0},this.widgetId=e.widgetId,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}}}initialize(){var t,i;this.config.enabled&&(e.debug("Initializing ExitIntentTrigger",{widgetId:this.widgetId,config:this.config}),this.lastScrollY=window.scrollY,(null===(t=this.config.desktop)||void 0===t?void 0:t.enabled)&&this.isDesktop()&&this.initializeDesktopTriggers(),(null===(i=this.config.mobile)||void 0===i?void 0:i.enabled)&&this.isMobile()&&this.initializeMobileTriggers())}isDesktop(){return!("ontouchstart"in window)&&!navigator.maxTouchPoints}isMobile(){return"ontouchstart"in window||navigator.maxTouchPoints>0}initializeDesktopTriggers(){var t,i;this.mouseLeaveListener=this.debounce(this.handleMouseLeave.bind(this),(null===(t=this.config.desktop)||void 0===t?void 0:t.delay)||100),this.mouseLeaveListener&&(document.addEventListener("mouseleave",this.mouseLeaveListener),document.addEventListener("mouseout",this.mouseLeaveListener)),e.debug("Desktop exit intent triggers initialized",{widgetId:this.widgetId,sensitivity:null===(i=this.config.desktop)||void 0===i?void 0:i.sensitivity})}initializeMobileTriggers(){const t=this.config.mobile;t.backButton&&(this.backButtonListener=this.handleBackButton.bind(this),window.addEventListener("popstate",this.backButtonListener),history.pushState({widgeticExitIntent:!0},"",window.location.href)),t.scrollUp&&(this.scrollUpListener=this.debounce(this.handleScrollUp.bind(this),50),this.scrollUpListener&&window.addEventListener("scroll",this.scrollUpListener,{passive:!0}),this.touchStartListener=this.handleTouchStart.bind(this),this.touchEndListener=this.handleTouchEnd.bind(this),document.addEventListener("touchstart",this.touchStartListener,{passive:!0}),document.addEventListener("touchend",this.touchEndListener,{passive:!0})),t.tabSwitch&&(this.visibilityChangeListener=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeListener)),e.debug("Mobile exit intent triggers initialized",{widgetId:this.widgetId,backButton:t.backButton,scrollUp:t.scrollUp,tabSwitch:t.tabSwitch})}handleMouseLeave(e){var t;if(this.isDestroyed||this.isTriggered)return;const i=(null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity)||10;e.clientY<=i&&null===e.relatedTarget&&(this.isTriggered=!0,this.stats.desktopTriggers++,this.triggerActivated("exit-intent",{source:"desktop",method:"mouse-leave",mouseY:e.clientY,sensitivity:i}))}handleBackButton(e){var t;this.isDestroyed||(null===(t=e.state)||void 0===t?void 0:t.widgeticExitIntent)&&(this.stats.backButtonTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"back-button"}),history.pushState({widgeticExitIntent:!0},"",window.location.href))}handleScrollUp(){var e;if(this.isDestroyed)return;const t=window.scrollY,i=t-this.lastScrollY;if(i<0){this.scrollUpDistance+=Math.abs(i),this.isScrollingUp=!0;const n=(null===(e=this.config.mobile)||void 0===e?void 0:e.sensitivity)||50;this.scrollUpDistance>=n&&t<=100&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"scroll-up",scrollUpDistance:this.scrollUpDistance,currentScrollY:t,sensitivity:n}),this.scrollUpDistance=0)}else this.scrollUpDistance=0,this.isScrollingUp=!1;this.lastScrollY=t}handleTouchStart(e){if(this.isDestroyed||1!==e.touches.length)return;const t=e.touches[0];this.touchStartY=t.clientY,this.touchStartTime=Date.now()}handleTouchEnd(e){if(this.isDestroyed||1!==e.changedTouches.length)return;const t=e.changedTouches[0].clientY,i=Date.now()-this.touchStartTime,n=t-this.touchStartY;n>100&&i<300&&window.scrollY<=50&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"swipe-up",swipeDistance:n,touchDuration:i,scrollY:window.scrollY}))}handleVisibilityChange(){this.isDestroyed||document.hidden&&(this.stats.tabSwitchTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"tab-switch",visibilityState:document.visibilityState}))}triggerActivated(t,i){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const n=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:t,triggerData:i}});document.dispatchEvent(n),e.debug("Exit intent trigger activated",{widgetId:this.widgetId,triggerType:t,triggerData:i})}debounce(e,t){return(...i)=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e.apply(this,i)}),t)}}updateConfig(t){var i,n;if(this.isDestroyed)return;const o=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),t),void 0===t.enabled&&void 0===(null===(i=t.desktop)||void 0===i?void 0:i.enabled)&&void 0===(null===(n=t.mobile)||void 0===n?void 0:n.enabled)||(this.destroy(),this.isDestroyed=!1,this.initialize()),e.debug("ExitIntentTrigger config updated",{widgetId:this.widgetId,oldConfig:o,newConfig:this.config})}reset(){this.isDestroyed||(this.isTriggered=!1,this.scrollUpDistance=0,this.isScrollingUp=!1,this.lastScrollY=window.scrollY,e.debug("ExitIntentTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{isTriggered:this.isTriggered,scrollUpDistance:this.scrollUpDistance,isScrollingUp:this.isScrollingUp,currentScrollY:window.scrollY,isDesktop:this.isDesktop(),isMobile:this.isMobile()})}isActive(){return this.isTriggered}forceActivate(e="desktop"){this.triggerActivated("exit-intent",{source:e,method:"manual",manual:!0})}destroy(){this.isDestroyed||(this.mouseLeaveListener&&(document.removeEventListener("mouseleave",this.mouseLeaveListener),document.removeEventListener("mouseout",this.mouseLeaveListener),this.mouseLeaveListener=null),this.backButtonListener&&(window.removeEventListener("popstate",this.backButtonListener),this.backButtonListener=null),this.scrollUpListener&&(window.removeEventListener("scroll",this.scrollUpListener),this.scrollUpListener=null),this.visibilityChangeListener&&(document.removeEventListener("visibilitychange",this.visibilityChangeListener),this.visibilityChangeListener=null),this.touchStartListener&&(document.removeEventListener("touchstart",this.touchStartListener),this.touchStartListener=null),this.touchEndListener&&(document.removeEventListener("touchend",this.touchEndListener),this.touchEndListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.isDestroyed=!0,e.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const zi={"top-left":["top","left"],"top-center":["top","center"],"top-right":["top","right"],"center-left":["center","left"],center:["center","center"],"center-center":["center","center"],"center-right":["center","right"],"bottom-left":["bottom","left"],"bottom-center":["bottom","center"],"bottom-right":["bottom","right"]};class Pi{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return Pi.instance||(Pi.instance=new Pi),Pi.instance}canShowOverlay(t,i){if(!(null==i?void 0:i.enabled))return!0;const n=this.getViewHistory(t,i),o=Date.now(),s=60*i.timePeriodHours*60*1e3,r=n.filter((e=>o-e.timestamp<=s)),a=r.length<i.maxViews;return e.debug(`[RecurrenceManager] Recurrence check for ${t}`,{maxViews:i.maxViews,timePeriodHours:i.timePeriodHours,recentViews:r.length,canShow:a}),a}recordView(t,i){if(!(null==i?void 0:i.enabled))return;const n={timestamp:Date.now(),widgetId:t},o=this.getViewHistory(t,i);o.push(n);const s=60*i.timePeriodHours*60*1e3,r=Date.now(),a=o.filter((e=>r-e.timestamp<=s));this.saveViewHistory(t,i,a),e.debug(`[RecurrenceManager] Recorded view for ${t}`,{totalViews:a.length,timePeriodHours:i.timePeriodHours})}getViewHistory(t,i){if(!this.isLocalStorageAvailable())return[];try{const e=this.getStorageKey(t,i),n=localStorage.getItem(e);if(!n)return[];const o=JSON.parse(n);return o.version!==this.storageVersion?[]:Array.isArray(o.views)?o.views:[]}catch(i){return e.warn(`[RecurrenceManager] Failed to load view history for ${t}`,{error:i}),[]}}saveViewHistory(t,i,n){if(this.isLocalStorageAvailable())try{const e=this.getStorageKey(t,i),o={version:this.storageVersion,widgetId:t,views:n,lastUpdated:Date.now()};localStorage.setItem(e,JSON.stringify(o))}catch(i){e.warn(`[RecurrenceManager] Failed to save view history for ${t}`,{error:i})}}getStorageKey(e,t){const i=(null==t?void 0:t.storageKeySuffix)?`-${t.storageKeySuffix}`:"";return`${this.storageKey}-${e}${i}`}isLocalStorageAvailable(){try{const e="__localStorage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}getStats(e,t){if(!(null==t?void 0:t.enabled))return null;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o));return{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,remainingViews:Math.max(0,t.maxViews-s.length),canShow:s.length<t.maxViews,lastView:s.length>0?s[s.length-1].timestamp:null,viewHistory:s.map((e=>e.timestamp))}}clearHistory(t,i){if(!(null==i?void 0:i.enabled)||!this.isLocalStorageAvailable())return;const n=this.getStorageKey(t,i);localStorage.removeItem(n),e.debug(`[RecurrenceManager] Cleared view history for ${t}`)}cleanup(){if(!this.isLocalStorageAvailable())return;const t=[];for(let e=0;e<localStorage.length;e++){const i=localStorage.key(e);if(null==i?void 0:i.startsWith(this.storageKey))try{const e=JSON.parse(localStorage.getItem(i)||"{}"),n=Date.now()-864e5;e.lastUpdated<n&&t.push(i)}catch(e){t.push(i)}}t.forEach((e=>localStorage.removeItem(e))),t.length>0&&e.debug(`[RecurrenceManager] Cleaned up ${t.length} old view records`)}}class Hi{constructor(e){var t;this.scrollTrigger=null,this.exitIntentTrigger=null,this.portal=null,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,this.placeholder=null,this.isInOverlay=!1,this.isDestroyed=!1,this.triggerInstances=new Map,this.keydownListener=null,this.recurrenceManager=Pi.getInstance(),this.delayTimer=null,this.domReadyListener=null,this.fullWidthRestore=null,this.onTriggerActivated=e=>this.handleTriggerActivated(e),this.onTriggerDeactivated=e=>this.handleTriggerDeactivated(e),this.onOverlayClose=e=>this.handleOverlayClose(e),this.widgetId=e.widgetId,this.element=e.element,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.mode=this.config.mode||"site",this.displayWhenShown=null!==(t=e.displayWhenShown)&&void 0!==t?t:"",this.originalParent=this.element.parentElement,this.originalNextSibling=this.element.nextSibling,this.initialize()}getDefaultConfig(){return{mode:"site",scroll:{enabled:!0,threshold:.1,distance:100,direction:"down"},exitIntent:{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}},overlay:{position:"bottom-right",offset:{x:20,y:20},className:"",style:"",closeButton:!0,backdrop:!1,animation:"slide",background:{enabled:!0,color:"#000",opacity:.5}},recurrence:{enabled:!1,maxViews:1,timePeriodHours:24}}}initialize(){switch(e.debug("Initializing TriggerManager",{widgetId:this.widgetId,mode:this.mode,config:this.config}),this.mode){case"site":break;case"mixed":this.initializeScrollTrigger("viewport");break;case"overlay":this.hideWidget(),this.armOverlayEventTrigger()}this.bindEvents()}armOverlayEventTrigger(){switch(this.config.eventTrigger){case"pageLoad":this.showOnLoad();break;case"delay":this.showAfterDelay();break;case"scroll":this.initializeScrollTrigger("distance");break;default:this.initializeScrollTrigger("distance"),this.initializeExitIntentTrigger()}}whenDomReady(e){this.isDestroyed||("loading"===document.readyState?(this.domReadyListener=()=>{this.domReadyListener=null,this.isDestroyed||e()},document.addEventListener("DOMContentLoaded",this.domReadyListener,{once:!0})):e())}showOnLoad(){this.whenDomReady((()=>this.showOverlay()))}showAfterDelay(){var t,i;if(!1===(null===(t=this.config.delay)||void 0===t?void 0:t.enabled))return;const n=null===(i=this.config.delay)||void 0===i?void 0:i.delayMs,o="number"==typeof n&&Number.isFinite(n)&&n>=0?n:G;this.whenDomReady((()=>{null===this.delayTimer&&(this.delayTimer=setTimeout((()=>{this.delayTimer=null,this.showOverlay()}),o),e.debug("Delay trigger armed",{widgetId:this.widgetId,delayMs:o}))}))}initializeScrollTrigger(e){var t;(null===(t=this.config.scroll)||void 0===t?void 0:t.enabled)&&(this.scrollTrigger=new Li({widgetId:this.widgetId,element:this.element,type:e,config:this.config.scroll}),this.triggerInstances.set("scroll",this.scrollTrigger))}initializeExitIntentTrigger(){var e;(null===(e=this.config.exitIntent)||void 0===e?void 0:e.enabled)&&(this.exitIntentTrigger=new Ri({widgetId:this.widgetId,config:this.config.exitIntent}),this.triggerInstances.set("exitIntent",this.exitIntentTrigger))}bindEvents(){document.addEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.addEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.addEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener=this.handleEscapeKey.bind(this),document.addEventListener("keydown",this.keydownListener)}handleTriggerActivated(t){const i=t;if(i.detail.widgetId!==this.widgetId)return;if("trigger-manager"===i.detail.source)return;const{triggerType:n,triggerData:o}=i.detail;e.debug("Trigger activated",{widgetId:this.widgetId,triggerType:n,triggerData:o}),"mixed"===this.mode&&"scroll-out-of-view"===n?this.showOverlay():"overlay"!==this.mode||"scroll-distance"!==n&&"exit-intent"!==n||this.showOverlay(),this.dispatchTriggerEvent("activated",n,o)}handleTriggerDeactivated(t){const i=t;if(i.detail.widgetId!==this.widgetId)return;if("trigger-manager"===i.detail.source)return;const{triggerType:n,triggerData:o}=i.detail;e.debug("Trigger deactivated",{widgetId:this.widgetId,triggerType:n,triggerData:o}),"mixed"===this.mode&&"scroll-back-in-view"===n&&this.hideOverlay(),this.dispatchTriggerEvent("deactivated",n,o)}handleOverlayClose(e){var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===this.widgetId&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}handleEscapeKey(e){"Escape"===e.key&&this.isInOverlay&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}showOverlay(){var t,i,n,o,s;if(!this.isInOverlay&&!this.isDestroyed){if("overlay"===this.mode&&(null===(t=this.config.recurrence)||void 0===t?void 0:t.enabled)){if(!this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence))return e.debug("Overlay blocked by recurrence limits",{widgetId:this.widgetId,recurrenceConfig:this.config.recurrence}),void this.dispatchEvent("overlay-blocked",{reason:"recurrence-limit",recurrenceStats:this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)})}this.portal||(this.portal=re({target:"widgetic-trigger-portal",className:(null===(i=this.config.overlay)||void 0===i?void 0:i.className)||"",style:(null===(n=this.config.overlay)||void 0===n?void 0:n.style)||"",zIndex:this.getOverlayZIndex(),clickThrough:!this.hasOverlayBackground()})),this.overlayContainer=this.createOverlayContainer(),this.portal.mount(this.overlayContainer),this.leavePlaceholder(),this.overlayContainer.appendChild(this.element),this.element.style.display=this.displayWhenShown,this.applyFullWidthSizing(),this.isInOverlay=!0,"overlay"===this.mode&&(null===(o=this.config.recurrence)||void 0===o?void 0:o.enabled)&&this.recurrenceManager.recordView(this.widgetId,this.config.recurrence),e.debug("Widget moved to overlay",{widgetId:this.widgetId}),this.dispatchEvent("overlay-shown",{mode:this.mode,position:null===(s=this.config.overlay)||void 0===s?void 0:s.position})}}leavePlaceholder(){var e;if("mixed"!==this.mode||this.placeholder)return;const t=this.element.parentNode;if(!t)return;const{width:i,height:n}=this.element.getBoundingClientRect(),o=document.createElement("div");o.setAttribute("data-widgetic-placeholder",this.widgetId),o.setAttribute("aria-hidden","true"),o.style.cssText=`display:block;visibility:hidden;pointer-events:none;width:${i}px;height:${n}px;`,t.insertBefore(o,this.element),this.placeholder=o,null===(e=this.scrollTrigger)||void 0===e||e.observeElement(o)}returnToPlaceholder(){const e=this.placeholder;return!!e&&(this.placeholder=null,!!e.parentNode&&(e.parentNode.replaceChild(this.element,e),!0))}hideOverlay(){var t;this.isInOverlay&&!this.isDestroyed&&(this.restoreFullWidthSizing(),!this.returnToPlaceholder()&&this.originalParent&&(this.originalNextSibling?this.originalParent.insertBefore(this.element,this.originalNextSibling):this.originalParent.appendChild(this.element)),"mixed"===this.mode&&(null===(t=this.scrollTrigger)||void 0===t||t.observeElement(this.element)),this.portal&&this.portal.unmount(),this.overlayContainer=null,this.isInOverlay=!1,e.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,o;const s=document.createElement("div");s.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),l=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),c=this.getOverlayStyles(r,a,this.getOverlayZIndex(),l);if(s.style.cssText=c,d&&this.applyBackgroundStyling(s),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,l);s.appendChild(e)}return(null===(o=this.config.overlay)||void 0===o?void 0:o.animation)&&s.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(s),s}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,o=(null==n?void 0:n.color)||"#000000",s=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${o};\n opacity: ${s};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?Q:Math.min(Math.floor(t),J)}getOverlayStyles(e,t,i,n){const[o,s]=zi[e]||zi["bottom-right"];let r=`\n position: fixed;\n z-index: ${i};\n pointer-events: auto;\n max-height: 90vh;\n `;return n?r+="left: 0; right: 0; width: 100%; max-width: 100vw;":(r+="max-width: 90vw;",r+="left"===s?`left: ${t.x}px;`:"right"===s?`right: ${t.x}px;`:"left: 0; right: 0; margin-left: auto; margin-right: auto; width: -moz-fit-content; width: fit-content;"),r+="top"===o?`top: ${n?0:t.y}px;`:"bottom"===o?`bottom: ${n?0:t.y}px;`:"top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; height: -moz-fit-content; height: fit-content;",r}applyFullWidthSizing(){var e;if(!(null===(e=this.config.overlay)||void 0===e?void 0:e.fullWidth)||this.fullWidthRestore)return;const t=Array.from(this.element.querySelectorAll("iframe"));this.fullWidthRestore={elementWidth:this.element.style.width,iframes:t.map((e=>({iframe:e,width:e.style.width})))},this.element.style.width="100%",t.forEach((e=>{e.style.width="100%"}))}restoreFullWidthSizing(){this.fullWidthRestore&&(this.element.style.width=this.fullWidthRestore.elementWidth,this.fullWidthRestore.iframes.forEach((({iframe:e,width:t})=>{e.style.width=t})),this.fullWidthRestore=null)}createCloseButton(e,t=!1){const i=document.createElement("button");i.className="widgetic-trigger-overlay-close",i.setAttribute("aria-label",A("closeOverlay")),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const o=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=o+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(t){this.isDestroyed||(this.config=Object.assign(Object.assign({},this.config),t),this.triggerInstances.forEach(((e,t)=>{"scroll"===t&&this.config.scroll?e.updateConfig(this.config.scroll):"exitIntent"===t&&this.config.exitIntent&&e.updateConfig(this.config.exitIntent)})),e.debug("TriggerManager config updated",{widgetId:this.widgetId,config:this.config}))}getStats(){var e;const t={widgetId:this.widgetId,mode:this.mode,isInOverlay:this.isInOverlay,isDestroyed:this.isDestroyed,triggerInstances:Array.from(this.triggerInstances.keys())};return this.triggerInstances.forEach(((e,i)=>{"function"==typeof e.getStats&&(t[`${i}Stats`]=e.getStats())})),(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(t.recurrenceStats=this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)),t}forceShowOverlay(){this.showOverlay()}forceHideOverlay(){this.hideOverlay()}getRecurrenceStats(){var e;return(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)?this.recurrenceManager.getStats(this.widgetId,this.config.recurrence):null}clearRecurrenceHistory(){var t;(null===(t=this.config.recurrence)||void 0===t?void 0:t.enabled)&&(this.recurrenceManager.clearHistory(this.widgetId,this.config.recurrence),e.debug("Recurrence history cleared",{widgetId:this.widgetId}))}canShowOverlay(){var e;return"overlay"!==this.mode||!(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)||this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence)}destroy(){this.isDestroyed||(null!==this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.domReadyListener&&(document.removeEventListener("DOMContentLoaded",this.domReadyListener),this.domReadyListener=null),this.isInOverlay&&this.hideOverlay(),this.placeholder&&(this.placeholder.remove(),this.placeholder=null),this.triggerInstances.forEach((e=>{"function"==typeof e.destroy&&e.destroy()})),this.triggerInstances.clear(),this.portal&&(this.portal.destroy(),this.portal=null),document.removeEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.removeEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.removeEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.recurrenceManager.cleanup(),this.isDestroyed=!0,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,e.debug("TriggerManager destroyed",{widgetId:this.widgetId}))}applyOverlayWidgetStyling(e){var t;if(!("mixed"===this.mode))return;if(!1!==(null===(t=this.config.overlay)||void 0===t?void 0:t.keepDimensions))return;const i=this.config.overlay;if(i){if(i.overlayWidth){const t="number"==typeof i.overlayWidth?`${i.overlayWidth}px`:i.overlayWidth;e.style.width=t,e.style.maxWidth=t}if(i.overlayHeight){const t="number"==typeof i.overlayHeight?`${i.overlayHeight}px`:i.overlayHeight;e.style.height=t,e.style.maxHeight=t}i.overlayResize&&this.applyOverlayResizeMode(e,i.overlayResize)}}applyOverlayResizeMode(e,t){switch(t){case"fill-width":e.style.width="90vw",e.style.height="auto",e.style.maxWidth="90vw";break;case"fill-height":e.style.height="90vh",e.style.width="auto",e.style.maxHeight="90vh";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="90vw",e.style.maxWidth="90vw";break;case"fixed-width":e.style.height="90vh",e.style.maxHeight="90vh";break;case"allow-scale-down":e.style.maxWidth="90vw",e.style.maxHeight="90vh";break;case"fill":e.style.width="90vw",e.style.height="90vh",e.style.maxWidth="90vw",e.style.maxHeight="90vh"}}}var Ui=Object.freeze({__proto__:null,TriggerManager:Hi});function ji(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=Math.floor(16*Math.random());return("x"===e?t:3&t|8).toString(16)}))}function Bi(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ni(e){return P(this,void 0,void 0,(function*(){try{const t=yield e.json();return Bi(t)?function(e){const t=e.data;return Bi(t)?t:e}(t):{}}catch(e){return{}}}))}class $i{constructor(t={}){var n,o;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},t),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},t.security)}),this.apiConfig=new i(Object.assign(Object.assign({basePath:this.config.apiBaseUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:3000")},this.config.apiKey&&{apiKey:this.config.apiKey}),this.config.accessToken&&{accessToken:this.config.accessToken})),this.widgetsApi=new r(this.apiConfig),this.compositionsApi=new s(this.apiConfig),this.securityManager=be.getInstance(this.config.security||{}),this.displayManager=new ce,this.performanceMonitor=me(),this.setupResponsiveTracking(),this.setupEventListeners(),e.info("[WidgetManager] Initialized with config:",{securityEnabled:!!(null===(n=t.security)||void 0===n?void 0:n.enableSanitization),performanceEnabled:!!(null===(o=t.performance)||void 0===o?void 0:o.enabled)})}static getInstance(e){return $i.instance||($i.instance=new $i(e)),$i.instance}initialize(){return P(this,void 0,void 0,(function*(){if(this.isInitialized)e.warn("[WidgetManager] Already initialized");else try{this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),e.info("[WidgetManager] Successfully initialized")}catch(t){throw e.error("[WidgetManager] Initialization failed:",t),this.emitError({code:"INIT_FAILED",message:"Widget manager initialization failed",widgetId:"system",timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}}),t}}))}registerWidget(t,i,n){return P(this,void 0,void 0,(function*(){try{const o=yield this.validateWidgetConfig(i);if(!o.allowed)throw new Error(`Widget validation failed: ${o.reason}`);const s={id:t,config:i,element:n,state:{ready:!1,error:null,width:i.width,height:i.height},displayState:{mode:i.displayMode,isFullscreen:!1,isOverlay:!1,isPopup:!1},updateHandlers:new Map,lastUpdate:Date.now()},r=this.displayManager.initializeWidget(t,i,n);if(s.displayState=r,i.triggers)try{const o=new Hi({widgetId:t,element:n,config:i.triggers});this.triggerManagers.set(t,o),e.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:t,triggers:i.triggers})}catch(i){e.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}return i.compositionId&&this.trackWidgetForComposition(i.compositionId,t),this.widgets.set(t,s),this.widgetConfigs.set(t,i),s.state.ready=!0,e.info("[WidgetManager] Widget registered:",{widgetId:t,compositionId:i.compositionId}),this.emitEvent({type:"widget_registered",widgetId:t,data:{config:i},timestamp:Date.now()}),s}catch(i){throw e.error("[WidgetManager] Widget registration failed:",i),this.emitError({code:"REGISTRATION_FAILED",message:"Widget registration failed",widgetId:t,timestamp:Date.now(),details:{error:i instanceof Error?i.message:"Unknown error"}}),i}}))}trackWidgetForComposition(e,t){this.compositionWidgets.has(e)||this.compositionWidgets.set(e,new Set),this.compositionWidgets.get(e).add(t)}applyContentToWidget(t,i){return P(this,void 0,void 0,(function*(){try{if("string"==typeof i)if("iframe"===t.element.tagName.toLowerCase()){const e=t.element;e.contentWindow&&e.contentWindow.postMessage({type:"widgetic_content_update",content:i},d.CLIENT_URL||"*")}else{const e=yield this.sanitizeContent(i,t.id);t.element.innerHTML=e}else if("object"==typeof i)if("iframe"===t.element.tagName.toLowerCase()){const e=t.element;e.contentWindow&&e.contentWindow.postMessage({type:"widgetic_data_update",data:i},d.CLIENT_URL||"*")}else t.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:i}));e.debug("[WidgetManager] Content applied to widget:",{widgetId:t.id,contentType:typeof i})}catch(t){throw e.error("[WidgetManager] Failed to apply content:",t),t}}))}sanitizeContent(e,t){return P(this,void 0,void 0,(function*(){const i=this.securityManager.validateTextFieldUpdate(t,"content",e);if(!i.allowed)throw new Error(`Content blocked by security: ${i.reason}`);return i.sanitizedText||e}))}validateWidgetConfig(e){return P(this,void 0,void 0,(function*(){var t;if(!e.compositionId)return{allowed:!1,reason:"Missing composition ID",severity:"high"};if(null===(t=this.config.security)||void 0===t?void 0:t.enableSanitization){const t=JSON.stringify(e),i=this.securityManager.validateTextFieldUpdate(e.compositionId,"config",t);if(!i.allowed)return{allowed:!1,reason:i.reason,severity:i.severity||"medium"}}return{allowed:!0}}))}setContent(t,i){return P(this,arguments,void 0,(function*(t,i,n={}){try{e.debug("[WidgetManager] Setting dynamic content:",{compositionId:t,contentType:typeof i,options:n});const o={content:i};void 0!==n.validate&&(o.validate=n.validate),void 0!==n.partial&&(o.partial=n.partial),void 0!==n.version&&(o.version=n.version),void 0!==n.source&&(o.source=n.source);const s=yield this.compositionsApi.setDynamicContentRaw({id:t,setDynamicContentRequest:o,idempotencyKey:ji()}),r=yield Ni(s.raw),a=this.getWidgetsByComposition(t),d=this.compositionData.get(t);let l=i;n.partial&&(null==d?void 0:d.content)&&(l=this.mergeContent(d.content,i));const c={id:t,widgetId:t,content:l,theme:(null==d?void 0:d.theme)||{},version:n.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(t,c);const h=a.map((i=>P(this,void 0,void 0,(function*(){var o;try{yield this.applyContentToWidget(i,l);const s=null===(o=i.updateHandlers)||void 0===o?void 0:o.get("content");s&&(yield s(l)),i.lastUpdate=Date.now(),e.debug("[WidgetManager] Content applied to widget:",{widgetId:i.id,compositionId:t,source:n.source})}catch(t){throw e.error("[WidgetManager] Failed to update widget content:",{widgetId:i.id,error:t instanceof Error?t.message:"Unknown error"}),t}}))));return yield Promise.all(h),this.emitEvent({type:"content_updated",widgetId:t,data:{content:l,source:n.source,version:n.version,partial:n.partial},timestamp:Date.now()}),e.info("[WidgetManager] Content updated successfully via API:",{compositionId:t,widgetCount:a.length,source:n.source,realtimeUpdateSent:r.realtimeUpdateSent}),{success:!0===r.success,validationResult:r.validationResult}}catch(e){const i=e instanceof Error?e.message:"Unknown error";return this.emitError({code:"CONTENT_UPDATE_FAILED",message:`Failed to set content: ${i}`,widgetId:t,timestamp:Date.now(),details:{error:i,options:n}}),{success:!1,error:i}}}))}getContentSchema(t){return P(this,void 0,void 0,(function*(){try{e.debug("[WidgetManager] Getting widget content schema:",{widgetId:t});const i=yield this.widgetsApi.getWidgetContentSchema({id:t});return e.debug("[WidgetManager] Content schema retrieved:",{widgetId:t,schema:i}),i}catch(i){throw e.error("[WidgetManager] Failed to get content schema:",i),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get content schema: ${i instanceof Error?i.message:"Unknown error"}`,widgetId:t,timestamp:Date.now()}),i}}))}getDesignSchema(t){return P(this,void 0,void 0,(function*(){try{e.debug("[WidgetManager] Getting widget design schema:",{widgetId:t});const i=yield this.widgetsApi.getWidgetDesignSchema({id:t});return e.debug("[WidgetManager] Design schema retrieved:",{widgetId:t,schema:i}),i}catch(i){throw e.error("[WidgetManager] Failed to get design schema:",i),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get design schema: ${i instanceof Error?i.message:"Unknown error"}`,widgetId:t,timestamp:Date.now()}),i}}))}validateContent(t,i){return P(this,void 0,void 0,(function*(){try{e.debug("[WidgetManager] Validating content:",{compositionId:t});const n=yield this.compositionsApi.validateCompositionContentRaw({id:t,requestBody:i,idempotencyKey:ji()}),o=yield Ni(n.raw),s=!0===o.valid;return e.debug("[WidgetManager] Content validation completed:",{compositionId:t,valid:s}),{valid:s,errors:Array.isArray(o.errors)?o.errors:void 0,warnings:Array.isArray(o.warnings)?o.warnings:void 0,sanitizedContent:o.sanitizedContent}}catch(t){throw e.error("[WidgetManager] Content validation failed:",t),t}}))}getContent(e){const t=this.compositionData.get(e);return(null==t?void 0:t.content)||null}mergeContent(e,t){if(!e||"object"!=typeof e)return t;if(!t||"object"!=typeof t)return e;const i=Object.assign({},e);for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&!Array.isArray(n)?i[e]=this.mergeContent(i[e],n):i[e]=n;return i}registerUpdateHandler(t,i,n){const o=this.widgets.get(t);if(!o)throw new Error(`Widget not found: ${t}`);o.updateHandlers||(o.updateHandlers=new Map),o.updateHandlers.set(i,n),e.info("[WidgetManager] Update handler registered:",{widgetId:t,updateType:i})}unregisterWidget(t){return P(this,void 0,void 0,(function*(){var i;const n=this.widgets.get(t);if(n)try{const o=n.config.compositionId;o&&this.compositionWidgets.has(o)&&(this.compositionWidgets.get(o).delete(t),0===this.compositionWidgets.get(o).size&&this.compositionWidgets.delete(o));try{this.displayManager.cleanup(t),e.debug("[WidgetManager] Display management cleaned up:",{widgetId:t})}catch(i){e.warn("[WidgetManager] Failed to cleanup display management:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}const s=this.triggerManagers.get(t);if(s)try{s.destroy(),this.triggerManagers.delete(t),e.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:t})}catch(i){e.warn("[WidgetManager] Failed to cleanup trigger manager:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}this.widgets.delete(t),this.widgetConfigs.delete(t),e.info("[WidgetManager] Widget unregistered:",{widgetId:t,compositionId:o,remainingWidgetsForComposition:(null===(i=this.compositionWidgets.get(o||""))||void 0===i?void 0:i.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:t,data:{compositionId:o},timestamp:Date.now()})}catch(i){e.error("[WidgetManager] Widget unregistration failed:",i),this.emitError({code:"UNREGISTRATION_FAILED",message:"Widget unregistration failed",widgetId:t,timestamp:Date.now(),details:{error:i instanceof Error?i.message:"Unknown error"}})}else e.warn("[WidgetManager] Widget not found for unregistration:",t)}))}getWidget(e){return this.widgets.get(e)}getAllWidgets(){return Array.from(this.widgets.values())}getWidgetsByComposition(e){const t=this.compositionWidgets.get(e);return t?Array.from(t).map((e=>this.widgets.get(e))).filter((e=>void 0!==e)):[]}setupResponsiveTracking(){if("undefined"==typeof window)return;const e=()=>{const e={mode:"mobile"===Se().getDeviceType()?"mobile":"desktop",breakpoint:768,width:window.innerWidth,timestamp:Date.now()};this.responsiveState&&this.responsiveState.mode===e.mode||(this.responsiveState=e,this.emitEvent({type:"responsive_change",widgetId:"system",data:e,timestamp:Date.now()}),this.handleResponsiveChange(e))};let t;e(),window.addEventListener("resize",(()=>{clearTimeout(t),t=setTimeout(e,250)}))}handleResponsiveChange(t){for(const i of this.widgets.values())try{const n=this.widgetConfigs.get(i.id);if(n&&i.displayState){this.displayManager.cleanup(i.id);const o=this.displayManager.initializeWidget(i.id,n,i.element);i.displayState=o,e.debug("[WidgetManager] Responsive update applied:",{widgetId:i.id,mode:t.mode,width:t.width})}this.emitEvent({type:"widget_responsive_change",widgetId:i.id,data:t,timestamp:Date.now()})}catch(t){e.error("[WidgetManager] Responsive change handling failed for widget:",{widgetId:i.id,error:t})}}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}addErrorHandler(e){this.errorHandlers.add(e)}removeErrorHandler(e){this.errorHandlers.delete(e)}emitEvent(t){const i=this.eventListeners.get(t.type);i&&i.forEach((i=>{try{i(t)}catch(t){e.error("[WidgetManager] Event handler failed:",t)}}))}emitError(t){this.errorHandlers.forEach((i=>{try{i(t)}catch(t){e.error("[WidgetManager] Error handler failed:",t)}}))}setupEventListeners(){"undefined"!=typeof window&&document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})}))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return P(this,void 0,void 0,(function*(){e.info("[WidgetManager] Destroying widget manager");const t=Array.from(this.widgets.keys());yield Promise.allSettled(t.map((e=>this.unregisterWidget(e))));for(const[t,i]of this.triggerManagers)try{i.destroy(),e.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:t})}catch(i){e.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),e.debug("[WidgetManager] Display manager cleaned up")}catch(t){e.warn("[WidgetManager] Failed to cleanup display manager:",{error:t instanceof Error?t.message:"Unknown error"})}this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,$i.instance=null,e.info("[WidgetManager] Widget manager destroyed")}))}getActiveCompositions(){return Array.from(this.compositionWidgets.keys()).filter((e=>this.compositionWidgets.get(e).size>0))}getCompositionData(e){return this.compositionData.get(e)}}function _i(e){return $i.getInstance(e)}$i.instance=null;var Fi=Object.freeze({__proto__:null,WidgetManager:$i,getWidgetManager:_i});let Vi=!1;class Ki{constructor(t={}){var i,o,s,r,a,d,g,u,m,p,f,v,w,y,b,I,S,E,C,M,T;this.version=n,this.instances=new Map,this.isInitialized=!1,this.renderer=D(),this.widgetControllers=new Map,this.authDetector=ae(),this.editorOverlay=de(),this.displayManager=he(),this.resizeHandler=ge(),this.authenticationStatus=null,this.overlayManager=null,this.hostObserverStarted=!1,this.config=Object.assign({renderMode:"auto",performance:{enabled:!1,config:{}},lazyLoading:{enabled:!0,config:{}}},t),this.browserCapabilities=Z(),this.messenger=oe(this.config.messagingOptions);const W=this.config.logLevel||(this.config.debug?"debug":"info");if(e.setLevel(W),h.enabled&&e.info("Initializing EmbedSDK",{version:n,config:this.config,browserCapabilities:this.browserCapabilities}),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(i=this.config.performance)||void 0===i?void 0:i.enabled)){const e=Object.assign({enableTracking:l.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:l.AXIOM_API_KEY,axiomDataset:l.AXIOM_DATASET,axiomApiEndpoint:l.AXIOM_API_ENDPOINT,statsigKey:l.STATSIG_API_KEY,statsigApiEndpoint:l.STATSIG_API_ENDPOINT},null===(o=this.config.performance)||void 0===o?void 0:o.config);pe(e)}!1!==(null===(s=this.config.lazyLoading)||void 0===s?void 0:s.enabled)&&fe((null===(r=this.config.lazyLoading)||void 0===r?void 0:r.config)||{}),void 0!==this.config.debug&&(c.setDebug(this.config.debug),this.config.debug&&c.setLevel("debug")),!1!==(null===(a=this.config.resourceOptimization)||void 0===a?void 0:a.enabled)&&ve((null===(d=this.config.resourceOptimization)||void 0===d?void 0:d.config)||{}),this.config.editorOptions&&(this.editorOverlay=de(this.config.editorOptions)),!1!==(null===(g=this.config.overlayConfig)||void 0===g?void 0:g.enabled)&&(this.overlayManager=ue({enabled:!0,defaultMode:null===(u=this.config.overlayConfig)||void 0===u?void 0:u.defaultMode,exitIntentEnabled:null===(m=this.config.overlayConfig)||void 0===m?void 0:m.exitIntentEnabled,scrollTriggerEnabled:null===(p=this.config.overlayConfig)||void 0===p?void 0:p.scrollTriggerEnabled,timeTriggerEnabled:null===(f=this.config.overlayConfig)||void 0===f?void 0:f.timeTriggerEnabled,engagementThresholdEnabled:null===(v=this.config.overlayConfig)||void 0===v?void 0:v.engagementThresholdEnabled,externalTriggerEnabled:null===(w=this.config.overlayConfig)||void 0===w?void 0:w.externalTriggerEnabled,breakpoints:{useBreakpoints:(null===(b=null===(y=this.config.overlayConfig)||void 0===y?void 0:y.breakpoints)||void 0===b?void 0:b.useBreakpoints)||!1,mobile:(null===(S=null===(I=this.config.overlayConfig)||void 0===I?void 0:I.breakpoints)||void 0===S?void 0:S.mobile)||480,tablet:(null===(C=null===(E=this.config.overlayConfig)||void 0===E?void 0:E.breakpoints)||void 0===C?void 0:C.tablet)||768,desktop:(null===(T=null===(M=this.config.overlayConfig)||void 0===M?void 0:M.breakpoints)||void 0===T?void 0:T.desktop)||1024}})),e.info("Widgetic Embed SDK v1.0 initialized",{version:n,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&e.info("EmbedSDK initialized in debug mode",{config:this.config})}init(){return P(this,void 0,void 0,(function*(){var t,i;if(this.watchPublishedHosts(),yield this.scanPage(),this.isInitialized)e.warn("SDK already initialized");else if(Vi||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)e.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,Vi=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((t=>{e.warn("Background authentication check failed",{error:t})})),this.config.preloadUISDK&&(null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated))try{const t=le();yield t.preload(),e.info("UI SDK preloaded successfully")}catch(t){e.warn("Failed to preload UI SDK",{error:t})}yield this.scanPage(),e.info("Widgetic Embed SDK initialized successfully",{version:n,capabilities:this.browserCapabilities,authenticationStatus:null===(i=this.authenticationStatus)||void 0===i?void 0:i.isAuthenticated}),yield this.scanPage()}catch(t){throw e.error("SDK initialization failed",{error:t}),t}}))}checkAuthentication(){return P(this,void 0,void 0,(function*(){var t;try{this.authenticationStatus=yield this.authDetector.checkAuthentication(),this.authenticationStatus.isAuthenticated?e.info("User authenticated for editing",{userId:null===(t=this.authenticationStatus.user)||void 0===t?void 0:t.id}):e.debug("User not authenticated for editing")}catch(t){e.debug("Authentication check failed",{error:t}),this.authenticationStatus={isAuthenticated:!1,canEdit:!1}}}))}enhance(){return P(this,void 0,void 0,(function*(){yield this.scanPage()}))}refresh(){return P(this,void 0,void 0,(function*(){e.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){bi(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{bi()})).observe(document.documentElement,{childList:!0,subtree:!0}))}scanPage(){return P(this,void 0,void 0,(function*(){var t,i,n,o;const s=document.querySelectorAll("widgetic");if(e.debug("Found widgetic host elements",{count:s.length}),0===s.length)return void e.info("No widgets found on page");const r=[];for(const a of Array.from(s))if(X(a)&&a instanceof HTMLElement){if(yi(a))continue;try{const s=U(a),d=null===(i=null===(t=s.device)||void 0===t?void 0:t.mobileEnabled)||void 0===i||i;if(!Ee(d,null===(o=null===(n=s.device)||void 0===n?void 0:n.desktopEnabled)||void 0===o||o)){e.debug("Widget skipped due to device restrictions",{compositionId:s.compositionId,deviceRestrictions:s.device,element:a.outerHTML.substring(0,100)+"..."}),a.style.display="none",a.setAttribute("data-device-restricted","true");continue}r.push({element:a,config:s})}catch(t){e.error("Failed to parse widget configuration",{element:a.outerHTML,error:t})}}0!==r.length?yield this.renderWidgetsBatch(r):e.warn("No valid widget configurations found")}))}renderWidgetsBatch(t){return P(this,void 0,void 0,(function*(){try{const i=[],n=t.map((({element:e,config:t})=>{let n=e;if(e.parentNode){const t=document.createElement("div");t.className=`widgetic-host ${e.className}`.trim(),e.getAttribute("style")&&(t.style.cssText=e.getAttribute("style")||""),e.parentNode.replaceChild(t,e),n=t}return i.push(n),{compositionId:t.compositionId,renderMode:ee(t.renderMode,this.browserCapabilities),width:t.width,height:t.height,resize:t.resize,autoscale:t.autoscale,adaptive:t.adaptive,container:n}})),o=yield this.renderer.renderWidgets(n);for(let n=0;n<o.length;n++){const s=o[n],{config:r}=t[n],a=i[n],d=te(r.compositionId),l=this.displayManager.initializeWidget(d,r,s.element);s.element instanceof HTMLElement&&a instanceof HTMLElement&&this.resizeHandler.registerWidget(d,s.element,a.parentElement||a,r);const c={id:d,config:r,element:s.element,displayState:l,state:{ready:!0,error:null,width:"number"==typeof r.width?r.width:parseInt(String(r.width)),height:"number"==typeof r.height?r.height:parseInt(String(r.height))},enterFullscreen:()=>this.displayManager.enterFullscreen(d),exitFullscreen:()=>this.displayManager.exitFullscreen(d),showOverlay:()=>this.displayManager.showOverlay(d),hideOverlay:()=>this.displayManager.hideOverlay(d),openPopup:()=>this.displayManager.openPopup(d),closePopup:()=>this.displayManager.closePopup(d)};this.instances.set(c.id,c),yield this.maybeAddEditorOverlay(s.element,r.compositionId),e.debug("Widget rendered successfully",{instanceId:c.id,compositionId:r.compositionId,renderMode:s.renderMode,displayMode:r.displayMode})}e.info("Batch widget rendering complete",{rendered:o.length,total:t.length})}catch(i){e.error("Batch widget rendering failed",{error:i});for(const{element:i,config:n}of t)try{yield this.renderSingleWidget(i,n)}catch(t){e.error("Individual widget rendering failed",{compositionId:n.compositionId,error:t})}}}))}renderSingleWidget(t,i){return P(this,void 0,void 0,(function*(){try{performance.now(),me(),we();const e=ye();if(this.shouldUseLazyLoading(t,i))return void e.register(t,i.compositionId,(()=>P(this,void 0,void 0,(function*(){yield this.performActualWidgetRender(t,i)}))),{config:i,priority:this.getWidgetPriority(i),resourceUrls:this.getWidgetResourceUrls(i)});yield this.performActualWidgetRender(t,i)}catch(t){const n=me(),o=t instanceof Error?t.message:"Render failed";throw n.recordWidgetError(i.compositionId,o),n.endWidgetLoad(i.compositionId,!1),e.error("Widget rendering failed",{error:t,config:i}),t}}))}performActualWidgetRender(t,i){return P(this,void 0,void 0,(function*(){const n=performance.now(),o=me(),s=we();try{const e=this.getWidgetResourceUrls(i);if(e.length>0&&(yield s.loadResources(e,{type:"script",priority:"high",compositionId:i.compositionId})),!("render"in this.renderer)||"function"!=typeof this.renderer.render)throw new Error("Widget renderer does not support render method");{const{widgetElement:e,instance:s}=yield this.renderer.render(t,i);if(!e)throw new Error("Widget element not created");const r=performance.now()-n;o.recordWidgetRender(i.compositionId,r),o.endWidgetLoad(i.compositionId,!0),this.instances.set(s.id,s)}}catch(t){const n=me(),o=t instanceof Error?t.message:"Render failed";throw n.recordWidgetError(i.compositionId,o),n.endWidgetLoad(i.compositionId,!1),e.error("Widget rendering failed",{error:t,config:i}),t}}))}shouldUseLazyLoading(e,t){var i;if(!1===(null===(i=this.config.lazyLoading)||void 0===i?void 0:i.enabled))return!1;if("critical"===t.priority||!0===t.preload)return!1;const n=e.getBoundingClientRect();return!(n.top<window.innerHeight&&n.bottom>0)}getWidgetPriority(e){switch(e.priority){case"critical":return 10;case"high":return 7;case"medium":default:return 5;case"low":return 2}}getWidgetResourceUrls(e){const t=[];return e.scriptUrl&&t.push(e.scriptUrl),e.styleUrl&&t.push(e.styleUrl),e.resourceUrls&&Array.isArray(e.resourceUrls)&&t.push(...e.resourceUrls),t}maybeAddEditorOverlay(t,i){return P(this,void 0,void 0,(function*(){if(!1!==this.config.enableEditing)try{yield this.editorOverlay.addOverlay(t,i)}catch(t){e.debug("Failed to add editor overlay",{compositionId:i,error:t})}}))}getInstances(){return Array.from(this.instances.values())}getInstance(e){return this.instances.get(e)||null}getInstancesByComposition(e){return this.getInstances().filter((t=>t.config.compositionId===e))}getStats(){const e=this.renderer.getStats();return{version:n,widgetsRendered:this.instances.size,renderMode:"auto",cacheStats:e.batchCache,messagingActive:this.messenger.isActive(),customEventSubscriptions:this.messenger.getCustomEventSubscriptions(),functionHandlers:this.messenger.getFunctionHandlers(),authenticationStatus:this.authenticationStatus||void 0,editingSessions:this.editorOverlay.getActiveSessions().length}}createWidgetController(t){const i=Array.from(this.instances.values()).find((e=>e.config.compositionId===t));if(!i)return e.warn("Widget instance not found for controller creation",{compositionId:t}),null;const n=this.messenger.createWidgetController(i.id,t);return this.widgetControllers.set(t,n),e.info("Widget controller created",{compositionId:t,instanceId:i.id}),n}getWidgetController(e){return this.widgetControllers.get(e)||null}subscribeToWidget(e,t,i){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.subscribe(t,i)}callWidgetFunction(e,t,...i){return P(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.callFunction(t,...i)}))}updateWidgetConfig(e,t){return P(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.updateConfig(t)}))}getWidgetState(e,t){return P(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.getState(t)}))}setWidgetState(e,t,i){return P(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.setState(t,i)}))}emitToWidget(t,i,n,o){let s=this.getWidgetController(t);s||(s=this.createWidgetController(t),s)?s.emit(i,n,o):e.warn(`Cannot create controller for widget: ${t}`)}canEditComposition(e){return P(this,void 0,void 0,(function*(){return this.authDetector.canEditComposition(e)}))}getAuthenticationStatus(){return this.authenticationStatus}refreshAuthentication(){return P(this,void 0,void 0,(function*(){return yield this.checkAuthentication(),this.authenticationStatus}))}openEditor(e){return P(this,void 0,void 0,(function*(){if(!(yield this.canEditComposition(e)))throw new Error(`User cannot edit composition: ${e}`);yield this.editorOverlay.openEditor(e)}))}isEditorOpen(e){return this.editorOverlay.isEditorOpen(e)}closeEditor(e){return P(this,void 0,void 0,(function*(){yield this.editorOverlay.closeEditor(e)}))}setEditingEnabled(t){this.config.enableEditing=t,e.info("Editing mode changed",{enabled:t})}setContent(t,i){return P(this,arguments,void 0,(function*(t,i,n={}){try{const{getWidgetManager:e}=yield Promise.resolve().then((function(){return Fi})),o=e();return yield o.setContent(t,i,n)}catch(t){return e.error("[EmbedSDK] Failed to set content:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}))}getContentSchema(t){return P(this,void 0,void 0,(function*(){try{const e=this.getInstancesByComposition(t)[0];if(!e)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Fi})),n=i();return yield n.getContentSchema(e.config.compositionId)}catch(t){throw e.error("[EmbedSDK] Failed to get content schema:",t),t}}))}getDesignSchema(t){return P(this,void 0,void 0,(function*(){try{const e=this.getInstancesByComposition(t)[0];if(!e)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Fi})),n=i();return yield n.getDesignSchema(e.config.compositionId)}catch(t){throw e.error("[EmbedSDK] Failed to get design schema:",t),t}}))}validateContent(t,i){return P(this,void 0,void 0,(function*(){try{const{getWidgetManager:e}=yield Promise.resolve().then((function(){return Fi})),n=e();return yield n.validateContent(t,i)}catch(t){throw e.error("[EmbedSDK] Failed to validate content:",t),t}}))}getContent(t){try{return _i().getContent(t)}catch(t){return e.error("[EmbedSDK] Failed to get content:",t),null}}onContentUpdate(e,t){return this.subscribeToWidget(e,"content_updated",t)}scan(){return P(this,void 0,void 0,(function*(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{const e=document.querySelectorAll("[data-widgetic]"),t=Array.from(e).map((e=>{const t=e.getAttribute("data-widgetic"),i=e.getAttribute("data-id");return t&&i?{id:t,dataId:i,element:e}:null})).filter(Boolean);return yield this.loadWidgets(t),{success:!0,widgets:t,errors:[]}}catch(e){return{success:!1,widgets:[],errors:[e instanceof Error?e.message:"Unknown error"]}}}))}loadWidgets(e){return P(this,void 0,void 0,(function*(){for(const t of e)try{yield this.loadWidget(t)}catch(e){}}))}loadWidget(e){return P(this,void 0,void 0,(function*(){yield new Promise((e=>setTimeout(e,100*Math.random())));const t=this.determineRenderMode();"iframe"===t?this.renderIframe(e):"custom-element"===t&&this.renderCustomElement(e)}))}determineRenderMode(){return"iframe"===this.config.renderMode?"iframe":"custom-element"===this.config.renderMode||"undefined"!=typeof customElements?"custom-element":"iframe"}renderIframe(e){const t=document.createElement("iframe");t.src=`https://widgetic.com/widget/${e.dataId}`,t.style.width=e.element.style.width||"400px",t.style.height=e.element.style.height||"300px",t.style.border="none",e.element.appendChild(t)}renderCustomElement(e){if("undefined"!=typeof customElements){customElements.get("widgetic-widget")||customElements.define("widgetic-widget",class extends HTMLElement{connectedCallback(){this.innerHTML=`<div>Widgetic Widget: ${this.getAttribute("data-widget-id")}</div>`}});const t=document.createElement("widgetic-widget");t.setAttribute("data-widget-id",e.dataId),e.element.appendChild(t)}}getConfig(){return Object.assign({},this.config)}showOverlay(t){this.overlayManager?this.overlayManager.showOverlay(t):e.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():e.warn("Overlay manager not initialized")}triggerOverlay(t,i={}){this.overlayManager?this.overlayManager.triggerOverlay(t,i):e.warn("Overlay manager not initialized")}isOverlayActive(){var e;return(null===(e=this.overlayManager)||void 0===e?void 0:e.isOverlayActive())||!1}destroy(){document.querySelectorAll("iframe").forEach((e=>e.remove()));document.querySelectorAll("widgetic-widget").forEach((e=>e.remove())),this.overlayManager&&(this.overlayManager.destroy(),this.overlayManager=null),this.isInitialized=!1}}let qi=null;function Yi(e){return qi||(qi=new Ki(e)),qi}"undefined"!=typeof document&&(bi(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{bi()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{h.enabled&&e.info("DOM ready, auto-initializing SDK"),Yi().init().catch((t=>{e.error("Auto-initialization failed",{error:t})}))})):(h.enabled&&e.info("DOM already ready, auto-initializing SDK"),setTimeout((()=>{Yi().init().catch((t=>{e.error("Auto-initialization failed",{error:t})}))}),0)));var Gi=Object.freeze({__proto__:null,EmbedSDK:Ki,getSDK:Yi});class Qi{constructor(){this.debugMode=!1,this.trackedElements=new WeakSet}static getInstance(){return Qi.instance||(Qi.instance=new Qi),Qi.instance}enableDebugMode(){this.debugMode=!0,this.addDebugStyles(),e.info("CSS debugging mode enabled")}disableDebugMode(){this.debugMode=!1,this.removeDebugStyles(),e.info("CSS debugging mode disabled")}analyzeWidget(e){const t=e.getAttribute("data-widgetic-instance")||"unknown",i=[],n=[];this.detectCSSConflicts(e,i),this.checkStyleIsolation(e,n);const o={widgetId:t,conflicts:i,isolationScore:this.calculateIsolationScore(e,i),recommendations:n};return this.debugMode&&this.displayDebugReport(o),o}detectCSSConflicts(e,t){const i=window.getComputedStyle(e);["font-family","font-size","color","background-color","margin","padding","border","box-sizing"].forEach((n=>{const o=i.getPropertyValue(n);i.getPropertyPriority(n),this.isExternalStyle(e,n,o)&&t.push({property:n,widgetValue:this.getWidgetStyleValue(e,n),externalValue:o,specificity:this.calculateSpecificity(e,n),source:this.getStyleSource(e,n)})}))}checkStyleIsolation(e,t){e.getAttribute("data-widgetic-instance")||t.push("Add data-widgetic-instance attribute for proper namespace isolation");const i=window.getComputedStyle(e);Array.from(i).some((e=>e.startsWith("--widgetic-")))||t.push("Use CSS custom properties (--widgetic-*) for better theme isolation");const n=i.getPropertyValue("contain");n.includes("layout")&&n.includes("style")||t.push("Apply CSS containment (contain: layout style paint) for better isolation");"auto"===i.getPropertyValue("z-index")&&this.hasStackingContext(e)&&t.push("Consider explicit z-index management to prevent stacking conflicts")}calculateIsolationScore(e,t){let i=100;i-=10*t.length;const n=window.getComputedStyle(e),o=n.getPropertyValue("contain");o.includes("layout")||(i-=15),o.includes("style")||(i-=15),o.includes("paint")||(i-=10);"isolate"!==n.getPropertyValue("isolation")&&(i-=10);e.getAttribute("data-widgetic-instance")||(i-=15);return"border-box"!==n.getPropertyValue("box-sizing")&&(i-=5),Math.max(0,i)}isExternalStyle(e,t,i){const n=document.createElement(e.tagName.toLowerCase());n.style.cssText=e.getAttribute("style")||"",document.body.appendChild(n);const o=window.getComputedStyle(n).getPropertyValue(t);return document.body.removeChild(n),i!==o&&!this.isWidgetStyle(e,t)}isWidgetStyle(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return!1;return this.getMatchingCSSRules(e).some((e=>{var n;return(null===(n=e.selectorText)||void 0===n?void 0:n.includes(`[data-widgetic-instance="${i}"]`))&&e.style.getPropertyValue(t)}))}getWidgetStyleValue(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return"";const n=this.getMatchingCSSRules(e).find((e=>{var t;return null===(t=e.selectorText)||void 0===t?void 0:t.includes(`[data-widgetic-instance="${i}"]`)}));return(null==n?void 0:n.style.getPropertyValue(t))||""}calculateSpecificity(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return 0;const n=i.selectorText||"";let o=0;return o+=100*(n.match(/#/g)||[]).length,o+=10*(n.match(/[\.\[]/g)||[]).length,o+=(n.match(/[a-zA-Z]/g)||[]).length,o}getStyleSource(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return"unknown";if(i.parentStyleSheet){const e=i.parentStyleSheet;if(e.href)return e.href;if(e.ownerNode)return"inline styles"}return"unknown"}getMatchingCSSRules(t){const i=[];try{for(let e=0;e<document.styleSheets.length;e++){const n=document.styleSheets[e];try{const e=n.cssRules||n.rules;for(let n=0;n<e.length;n++){const o=e[n];o.selectorText&&t.matches(o.selectorText)&&i.push(o)}}catch(e){continue}}}catch(t){e.warn("Failed to analyze CSS rules",{error:t})}return i}hasStackingContext(e){const t=window.getComputedStyle(e),i=t.getPropertyValue("position"),n=t.getPropertyValue("z-index"),o=t.getPropertyValue("transform"),s=t.getPropertyValue("opacity");return"static"!==i&&"auto"!==n||"none"!==o||parseFloat(s)<1}addDebugStyles(){const e="widgetic-css-debug-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n /* CSS Debug Mode Styles */\n widgetic-widget[data-widgetic-instance] {\n outline: 2px dashed #007bff !important;\n outline-offset: 2px !important;\n position: relative !important;\n }\n\n widgetic-widget[data-widgetic-instance]::before {\n content: "Widget: " attr(data-widgetic-instance) !important;\n position: absolute !important;\n top: -20px !important;\n left: 0 !important;\n background: #007bff !important;\n color: white !important;\n padding: 2px 6px !important;\n font-size: 10px !important;\n font-family: monospace !important;\n z-index: 10000 !important;\n pointer-events: none !important;\n }\n\n widgetic-widget[data-error="true"] {\n outline-color: #dc3545 !important;\n }\n\n widgetic-widget[data-loading="true"] {\n outline-color: #ffc107 !important;\n }\n\n widgetic-widget[data-ready="true"] {\n outline-color: #28a745 !important;\n }\n ',document.head.appendChild(t)}removeDebugStyles(){const e=document.getElementById("widgetic-css-debug-styles");e&&e.remove()}displayDebugReport(e){}monitorWidget(e){if(this.trackedElements.has(e))return;this.trackedElements.add(e);new MutationObserver((e=>{e.forEach((e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.debugMode}))})).observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:["style","class"]})}}Qi.instance=null;const Ji=Qi.getInstance();function Zi(){Ji.enableDebugMode()}function Xi(){Ji.disableDebugMode()}function en(e){return Ji.analyzeWidget(e)}function tn(e){Ji.monitorWidget(e)}const nn={WidgeticWidget:O,registerWidgeticWidget:k,getSDK:Yi,setApiKey:v,setTokenProvider:f,StaticApiKeyProvider:p,EndpointTokenProvider:m,FunctionTokenProvider:u,getConfiguration:g},on={WidgetRenderer:z,getWidgetRenderer:D,CustomElementRenderer:R,IframeRenderer:L,AuthManager:I,detectBrowserCapabilities:Z,determineBestRenderMode:ee,parseWidgetConfig:U,generateInstanceId:te,isValidWidgetElement:X},sn={BatchApiClient:Si,getBatchClient:Ci,ModuleLoader:xi,getModuleLoader:Di,WidgeticMessenger:se,getMessenger:oe,config:d,getApiUrl:b,getCdnUrl:a,getTokenProvider:y,getAuthToken:t,DefaultTokenProvider:w,CSSDebugger:Qi,cssDebugger:Ji,enableCSSDebug:Zi,disableCSSDebug:Xi,log:e};export{Ti as A,Si as B,Qi as C,Oi as D,Ki as E,Gi as F,ei as G,nn as H,sn as L,on as M,Ce as O,gi as P,Bt as R,De as W,Di as a,ci as b,si as c,oi as d,Yt as e,ri as f,Ci as g,Wt as h,Gt as i,ni as j,Se as k,$i as l,_i as m,Yi as n,Ji as o,xi as p,en as q,Ut as r,Kt as s,Xi as t,Zi as u,tn as v,vt as w,Mi as x,ki as y,hi as z};
|
|
1
|
+
import{l as e,g as t,C as i,V as n,a as o,b as s,W as r,c as a,d,P as l,e as c,f as h,h as g,F as u,E as m,S as p,s as f,i as v,j as w,k as y,m as b,A as I}from"./core.js";import{r as S,w as E,a as T,b as C,c as M,s as W,d as x,e as A,g as D,f as k,W as O,I as L,C as R,h as z}from"./renderers.js";import{_ as P,a as H}from"./vendor.js";import{p as U,i as j,a as B,b as N,g as $,c as F,h as _,d as V,e as K,m as q,o as Y,f as G,D as Q,j as J,k as Z,l as X,r as ee,n as te,q as ie,M as ne,s as oe,t as se,u as re,v as ae}from"./scanner.js";import{g as de,a as le}from"./media.js";import{getMessenger as ce,WidgeticMessenger as he}from"./messaging.js";import{c as ge,g as ue,a as me,b as pe}from"./advanced.js";import{D as fe,g as ve,a as we,b as ye}from"./display.js";import{g as be,i as Ie,a as Se,b as Ee,c as Te,d as Ce}from"./performance.js";import{S as Me}from"./security.js";class We{constructor(){this.deviceInfo=null}static getInstance(){return We.instance||(We.instance=new We),We.instance}getDeviceInfo(){return this.deviceInfo||(this.deviceInfo=this.detectDevice()),this.deviceInfo}getDeviceType(){return this.getDeviceInfo().type}isMobile(){return this.getDeviceInfo().isMobile}isTablet(){return this.getDeviceInfo().isTablet}isDesktop(){return this.getDeviceInfo().isDesktop}hasTouch(){return this.getDeviceInfo().hasTouch}detectDevice(){const t=navigator.userAgent||"",i=navigator.platform||"",n=navigator.vendor||"",o=navigator.maxTouchPoints||0,s=navigator.hardwareConcurrency||1,r=navigator.deviceMemory,a=this.detectTouchCapability(),d=this.determineDeviceType(t,i,a,o),l={type:d,isMobile:"mobile"===d,isTablet:"tablet"===d,isDesktop:"desktop"===d||"tablet"===d,hasTouch:a,userAgent:t,platform:i,vendor:n,maxTouchPoints:o,hardwareConcurrency:s,deviceMemory:r};return e.debug("Device detected",l),l}detectTouchCapability(){if("ontouchstart"in window)return!0;if(navigator.maxTouchPoints&&navigator.maxTouchPoints>0)return!0;if("onpointerdown"in window)return!0;try{if(void 0!==window.DocumentTouch&&document instanceof window.DocumentTouch)return!0}catch(e){}return!1}determineDeviceType(e,t,i,n){const o=e.toLowerCase(),s=t.toLowerCase();return[/android.*mobile/,/iphone/,/ipod/,/blackberry/,/bb10/,/windows phone/,/iemobile/,/mobile/,/phone/].some((e=>e.test(o)))?"mobile":[/ipad/,/android(?!.*mobile)/,/kindle/,/silk/,/playbook/,/tablet/].some((e=>e.test(o)))?"tablet":[/windows nt/,/macintosh/,/mac os x/,/linux/,/x11/,/cros/].some((e=>e.test(o)))?"desktop":/^(iphone|ipod|android)/.test(s)?"mobile":/^(ipad)/.test(s)?"tablet":/^(win|mac|linux)/.test(s)?"desktop":i?n>=5?"tablet":n<=2?"mobile":"tablet":"desktop"}checkDeviceRestrictions(t=!0,i=!0){const n=this.getDeviceInfo();return n.isMobile&&!t?(e.debug("Widget restricted on mobile device"),!1):!(n.isDesktop&&!i)||(e.debug("Widget restricted on desktop/tablet device"),!1)}getDeviceCapabilities(){const e={userAgent:navigator.userAgent,platform:navigator.platform,vendor:navigator.vendor,language:navigator.language,languages:navigator.languages,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,maxTouchPoints:navigator.maxTouchPoints,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,connection:navigator.connection,standalone:navigator.standalone,webdriver:navigator.webdriver};return e.screen={width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,colorDepth:screen.colorDepth,pixelDepth:screen.pixelDepth,orientation:screen.orientation},e.touch={hasTouch:this.hasTouch(),hasTouchEvents:"ontouchstart"in window,hasPointerEvents:"onpointerdown"in window,hasGestureEvents:"ongesturestart"in window},window.matchMedia&&(e.mediaQueries={hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":"coarse",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":"coarse"}),e}reset(){this.deviceInfo=null}}function xe(){return We.getInstance()}function Ae(e=!0,t=!0){return xe().checkDeviceRestrictions(e,t)}const De="data-widgetic-overlay",ke="data-device-restricted",Oe=new WeakMap;!function(){if("undefined"==typeof window)return;const e=window.Widgetic,t=e=>function(e){const t=e.trim();if(!t)return!1;const i=Array.from(document.querySelectorAll(`widgetic[composition-id="${CSS.escape(t)}"]`));let n=!1;for(const e of i){const t=Oe.get(e);t&&(t.showFromManualApi(),n=!0)}return n}(e);window.Widgetic=e&&"object"==typeof e?Object.assign(Object.assign({},e),{show:t}):{show:t}}();const Le=new WeakMap,Re=new Map;function ze(t,i,n){if(Oe.has(t))return;const o=t.getAttribute("composition-id")||"widget",s=function(e,t){const i=Le.get(e);if(i)return i;const n=(Re.get(t)||0)+1;Re.set(t,n);const o=1===n?t:`${t}-${n}`;return Le.set(e,o),o}(t,o);let r=()=>{};if(n){const e=e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===s&&(r(),n())};document.addEventListener("widgetic:overlay-shown",e),r=()=>document.removeEventListener("widgetic:overlay-shown",e)}Promise.resolve().then((function(){return _i})).then((({TriggerManager:n})=>{if(Oe.has(t))return void r();const o=new n({widgetId:s,element:t,config:i,displayWhenShown:"block"});Oe.set(t,o),t.hasAttribute(De)&&t.setAttribute(De,"armed"),e.debug("[published-host-display] Trigger manager armed",{widgetId:s,mode:i.mode,eventTrigger:i.eventTrigger})})).catch((t=>{r(),e.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:s,error:t})}))}const Pe="data-widgetic-workflow-stage",He=2e3,Ue=150,je=5,Be=300,Ne=2e4,$e=[250,1e3,2500],Fe=new Set(["TEXTAREA","INPUT","SELECT","IFRAME","VIDEO","AUDIO","CANVAS","OBJECT","EMBED"]);function _e(e){return e.hasAttribute(Pe)}function Ve(e){return j(e)&&!_e(e)&&!e.hasAttribute(De)}function Ke(e,t,i){const n=e.getAttribute(t);if(null===n||!/^\d+$/.test(n.trim()))return null;const o=Number.parseInt(n.trim(),10);return Number.isFinite(o)?Math.min(o,i):null}function qe(e,t,i=function(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(e){return!1}}()){var n,o,s,r,a;const d=null!==(n=Ke(e,"autoscale-min-height",Ne))&&void 0!==n?n:Math.max(0,Math.round(t)),l=null!==(o=Ke(e,"autoscale-max-height",Ne))&&void 0!==o?o:He;return{floorHeight:d,maxHeight:Math.max(l,d),debounceDelay:null!==(s=Ke(e,"autoscale-debounce",5e3))&&void 0!==s?s:Ue,threshold:null!==(r=Ke(e,"autoscale-threshold",Ne))&&void 0!==r?r:je,animate:"false"!==e.getAttribute("autoscale-animate")&&!i,animationDuration:null!==(a=Ke(e,"autoscale-animation-duration",5e3))&&void 0!==a?a:Be}}function Ye(e,t){return Number.isNaN(e)?t.floorHeight:Math.max(t.floorHeight,Math.min(t.maxHeight,Math.ceil(e)))}function Ge(e){const t=Number.parseFloat(null!=e?e:"");return Number.isFinite(t)?t:0}function Qe(e){const t=e.overflowY;return"auto"===t||"scroll"===t||"overlay"===t}function Je(e,t,i){var n;if("fixed"===t.position)return!1;for(let t=e.parentElement;t&&t!==i;t=t.parentElement)if("fixed"===(null===(n=t.ownerDocument.defaultView)||void 0===n?void 0:n.getComputedStyle(t).position))return!1;if("absolute"===t.position){const t=e.parentElement;if(!t)return!1;return e.getBoundingClientRect().height>=t.getBoundingClientRect().height-2}return!0}function Ze(e){const t=e.getBoundingClientRect(),i=e.offsetHeight>0&&t.height>0?t.height/e.offsetHeight:1,n=e.scrollHeight-e.clientHeight,o=n>1?n:-function(e,t,i){const n=e.ownerDocument.defaultView;if(!n||e.clientHeight<=0)return 0;const o=n.getComputedStyle(e),s=t+e.clientTop*i;let r=s+Ge(o.paddingTop)*i,a=0;for(const t of Array.from(e.children)){const e=n.getComputedStyle(t);if("none"===e.display||"absolute"===e.position||"fixed"===e.position)continue;const o=t.getBoundingClientRect();0===o.width&&0===o.height||o.bottom>r&&(r=o.bottom,a=Ge(e.marginBottom)*i)}const d=(r+a-s+Ge(o.paddingBottom)*i)/i;return Math.max(0,Math.floor(e.clientHeight-d))}(e,t.top,i);return{region:e,top:t.top,bottom:t.bottom,delta:o}}function Xe(e){const t=[...e].sort(((e,t)=>e.top-t.top));let i=0,n=0,o=Number.NEGATIVE_INFINITY,s=!1;for(const e of t)s&&e.top<o-1?(n=Math.max(n,e.delta),o=Math.max(o,e.bottom)):(s&&(i+=n),n=e.delta,o=e.bottom,s=!0);return s&&(i+=n),i}function et(e,t,i,n,o){if(!Number.isFinite(i)||i<=0)return null;const s=function(e,t){const i=[];for(const n of Array.from(e.querySelectorAll("*"))){if(!(n instanceof HTMLElement))continue;if(Fe.has(n.tagName))continue;if(null==t?void 0:t.has(n))continue;const o=n.ownerDocument.defaultView;if(!o)continue;const s=o.getComputedStyle(n);Qe(s)&&(i.some((e=>e.contains(n)))||Je(n,s,e)&&i.push(n))}return i}(e,o).map((e=>Ze(e)));if(0===s.length)return i;const r=Math.max(0,Math.ceil(i+Xe(s))),a=Ye(r,n);if(!tt(i,a,n.threshold))return r;const d=function(e,t,i){const n=t.map((e=>e.clientHeight)),o=e.style.height,s=e.style.transition;try{return e.style.transition="none",e.style.height=`${i}px`,t.map(((e,t)=>{var i;return e.clientHeight-(null!==(i=n[t])&&void 0!==i?i:0)}))}finally{o?e.style.height=o:e.style.removeProperty("height"),e.offsetHeight,e.style.transition=s}}(t,s.map((e=>e.region)),a),l=s.map(((e,t)=>{var i;if(Math.abs(e.delta)<=1)return e;const n=null!==(i=d[t])&&void 0!==i?i:0;if(Math.abs(n)<1)return o.add(e.region),Object.assign(Object.assign({},e),{delta:0});const s=e.delta>0?Math.min(e.delta,Math.max(0,n)):Math.max(e.delta,Math.min(0,n));return Object.assign(Object.assign({},e),{delta:s})}));return Math.max(0,Math.ceil(i+Xe(l)))}function tt(e,t,i){return t!==e&&Math.abs(t-e)>=Math.max(1,i)}function it(t){const{host:i,box:n,compositionId:o,settings:s,startHeight:r,originalHeightCss:a}=t;let d=Math.round(r),l=!1,c=0;const h=(e,t)=>{c=t?Date.now()+s.animationDuration:0,n.style.transition=t?`height ${s.animationDuration}ms ease`:"none",e===Math.round(r)?a?n.style.height=a:n.style.removeProperty("height"):n.style.height=`${e}px`};return{currentHeight:()=>d,isAnimating:()=>Date.now()<c,follow(t){const n=Ye(t,s);if(!tt(d,n,s.threshold))return!1;const r=d;h(n,s.animate&&l),d=n,l=!0,E(o,n,s.floorHeight),e.debug("[autoscale] The embed follows its widget",{compositionId:o,previousHeight:r,nextHeight:n,naturalHeight:t});try{i.dispatchEvent(new CustomEvent("widgetic:autoscale",{bubbles:!0,composed:!0,detail:{compositionId:o,oldHeight:r,newHeight:n,contentHeight:Math.ceil(t)}}))}catch(e){}return!0},startAtStoredHeight(){const e=S(o);if(null===e)return!1;const t=Ye(e,s);return!(!tt(d,t,s.threshold)||t<=d)&&(h(t,!1),d=t,l=!0,!0)}}}const nt=new WeakMap;function ot(e){var t;null===(t=nt.get(e))||void 0===t||t.stop(),nt.delete(e)}const st=/^[A-Za-z0-9_.-]{1,64}$/;function rt(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function at(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch(e){return null}}function dt(e){const t=at(e);if(!t)return null;const i=Object.keys(t);if(i.length>50)return null;if(rt(t)>8192)return null;const n={};for(const e of i){if(!st.test(e))return null;const i=t[e];if("boolean"==typeof i)n[e]=i;else if("number"==typeof i){if(!Number.isFinite(i))return null;n[e]=i}else{if("string"!=typeof i)return null;if(i.length>2e3)return null;n[e]=i}}return n}function lt(e){if(!(null==e?void 0:e.trim()))return null;const t=e.trim();if(t.length>2048)return null;try{return"https:"!==new URL(t).protocol?null:t}catch(e){return null}}const ct=new WeakMap;function ht(e){var t;const i=e.getAttribute("context"),n=function(e){const t=at(e);if((null==e?void 0:e.trim())&&!t)return{value:null,invalid:!0};if(!t)return{value:null,invalid:!1};const i=Object.keys(t);if(i.length>20)return{value:null,invalid:!0};if(rt(t)>2048)return{value:null,invalid:!0};const n={};for(const e of i){if(!st.test(e))return{value:null,invalid:!0};const i=t[e];if("number"==typeof i){if(!Number.isFinite(i))return{value:null,invalid:!0};n[e]=i}else{if("string"!=typeof i)return{value:null,invalid:!0};if(i.length>500)return{value:null,invalid:!0};n[e]=i}}return{value:n,invalid:!1}}(i);return n.invalid&&function(e,t){const i=null!=t?t:"";let n=ct.get(e);n||(n=new Set,ct.set(e,n)),n.has(i)||n.add(i)}(e,i),{context:n.invalid?null:n.value,contextInvalid:n.invalid,values:dt(e.getAttribute("values")),mediaResolver:lt(null!==(t=e.getAttribute("media-resolver"))&&void 0!==t?t:e.getAttribute("mediaresolver"))}}function gt(e){return Object.assign(Object.assign({},e.entries?{entries:e.entries}:{}),e.adapters?{adapters:e.adapters}:{})}function ut(e,t,i){return Object.assign(Object.assign({type:"widgetic:host",version:1,compositionId:e,context:t.context,values:t.values,mediaResolver:t.mediaResolver},(null==i?void 0:i.entries)?{entries:i.entries}:{}),(null==i?void 0:i.adapters)?{adapters:i.adapters}:{})}const mt=1e4;function pt(e,t){const i=(null!=e?e:"").trim().toLowerCase();if(""===i)return t;const n=/^(\d+(?:\.\d+)?)(?:px)?$/.exec(i);if(!n)return null;const o=Number.parseFloat(n[1]);return o>0?o:null}const ft="data-widgetic-mobile",vt=new WeakMap;function wt(t){var i,n;const{host:o,box:s,widthCss:r,widthPixels:a,heightPixels:d}=t;!function(e){const t=vt.get(e);vt.delete(e),null==t||t()}(o);const l=()=>{};try{if(!function(e){return!_e(e)&&!e.hasAttribute(De)&&void 0===B(e)}(o))return l;const t=function(e){var t;const i=(null!==(t=e.getAttribute("resize"))&&void 0!==t?t:"").trim().toLowerCase();return"fill-width"===i?"fill-width":"responsive"===i?"responsive":"fixed"}(o),c=null!==(i=function(e){const t=e.getAttribute("adaptive");if(null===t||!/^\d+$/.test(t.trim()))return null;const i=Number.parseInt(t.trim(),10);return i<1?null:Math.min(i,mt)}(o))&&void 0!==i?i:"responsive"===t?480:null;if("fixed"===t&&null===c)return l;const h=[],g=(t,i)=>{try{h.push(i())}catch(i){e.debug(`[resize] ${t} could not be followed`,{error:i})}};if("fixed"!==t){s.style.setProperty("width","100%"),"responsive"===t&&s.style.setProperty("max-width",r);Ve(o)||null===a||null===d||g("The width of the space",(()=>function(e,t,i,n,o){let s=0;const r=e=>{if(!(e>0)||e===s)return;s=e;const r="responsive"===i?Math.min(e,n):e,a=Math.max(1,Math.round(r*o/n));t.style.setProperty("height",`${a}px`)};if("function"==typeof ResizeObserver){const t=new ResizeObserver((t=>{const i=t[t.length-1];r(i?i.contentRect.width:e.clientWidth)}));return t.observe(e),()=>t.disconnect()}const a=()=>r(e.clientWidth);return window.addEventListener("resize",a),a(),()=>window.removeEventListener("resize",a)}(o,s,t,a,d)))}null!==c&&g("The breakpoint",(()=>function(t,i){var n;if("function"!=typeof window.matchMedia)return e.debug("[resize] The window cannot be measured against the breakpoint here",{breakpointPixels:i}),()=>{};const o=null!==(n=t.getAttribute("composition-id"))&&void 0!==n?n:"",s=window.matchMedia(`(max-width: ${i}px)`),r=n=>{t.setAttribute(ft,n?"true":"false"),e.debug("[resize] The window is against the breakpoint of the embed",{compositionId:o,breakpointPixels:i,isMobile:n});try{t.dispatchEvent(new CustomEvent("widgetic:adaptive",{bubbles:!0,composed:!0,detail:{compositionId:o,isMobile:n,breakpoint:i}}))}catch(e){}};r(s.matches);const a=e=>r(e.matches);return"function"==typeof s.addEventListener?s.addEventListener("change",a):"function"==typeof s.addListener&&s.addListener(a),()=>{"function"==typeof s.removeEventListener?s.removeEventListener("change",a):"function"==typeof s.removeListener&&s.removeListener(a),t.removeAttribute(ft)}}(o,c))),e.debug("[resize] The embed follows the Resize Mode of its tag",{compositionId:null!==(n=o.getAttribute("composition-id"))&&void 0!==n?n:"",resizeMode:t,breakpointPixels:c});const u=()=>{for(const e of h)try{e()}catch(e){}};return vt.set(o,u),u}catch(t){return e.debug("[resize] The box could not be sized from its tag; it keeps the size of its tag",{error:t}),l}}const yt="data-widgetic-context-invalid";const bt=new Set;let It=0;function St(e){return P(this,void 0,void 0,(function*(){It+=1;try{const i=yield(t=e,import(t));return i&&!0!==i.acceptsHostProps&&bt.add(e),i}finally{It-=1,0===It&&null===xt&&Dt()}var t}))}function Et(e){try{return St(e).then((()=>!0),(()=>!1))}catch(e){return Promise.resolve(!1)}}const Tt=new WeakMap,Ct=new Set,Mt=new Map;function Wt(e,t){const i=Mt.get(e);i&&(i.delete(t),0===i.size&&Mt.delete(e))}let xt=null;const At={context:null,values:null,mediaResolver:null,contextInvalid:!1};function Dt(){if("undefined"==typeof window)return;const e=new Set;let t=!1;for(const i of Ct)i.payload.compositionId?e.add(i.payload.compositionId):t=!0;const i=!t&&1===e.size?Array.from(e)[0]:null;try{if(i&&1===bt.size&&0===It){const e=Array.from(Ct).find((e=>e.payload.compositionId===i)),t=e?gt(e.payload):{};if(e&&(t.entries||t.adapters)){const n=ht(e.host);return window.postMessage(ut(i,n,t),window.location.origin),void(xt=i)}}null!==xt&&i!==xt&&(window.postMessage(ut(xt,At),window.location.origin),xt=null)}catch(e){}}function kt(e,t){t.instance.update(zt(e,t.payload)),t.listensOnWindow&&Dt()}const Ot=new WeakMap;function Lt(e,t){t?Ot.set(e,t):Ot.delete(e);const i=Tt.get(e);if(i)try{kt(e,i)}catch(e){}}function Rt(e){const t=Tt.get(e);if(t){Tt.delete(e);try{t.instance.destroy()}catch(e){}t.stop(),null!==t.moduleSlot&&Wt(t.moduleUrl,t.moduleSlot),Ct.delete(t)&&Dt()}for(const t of Array.from(e.querySelectorAll("[data-widgetic-direct]")))t.remove()}function zt(e,t){const i=ht(e);i.contextInvalid?e.setAttribute(yt,""):e.removeAttribute(yt);const n=F(e,t),o=Object.assign(Object.assign(Object.assign({},t.content||{}),n.content),i.values||{}),s=Object.assign(Object.assign({},t.design||{}),n.design),r=n.contentItems&&n.contentItems.length>0?n.contentItems:t.contentItems||[],a=Ot.get(e);return Object.assign(Object.assign(Object.assign(Object.assign({design:s,content:o,contentItems:r,context:i.context,mediaResolver:i.mediaResolver},t.compositionId?{compositionId:t.compositionId}:{}),t.entries?{entries:t.entries}:{}),t.adapters?{adapters:t.adapters}:{}),a?{workflow:a}:{})}const Pt=400,Ht=300,Ut=/^\d+(?:\.\d+)?(?:px|%|em|rem|vh|vw|vmin|vmax|ch|cm|mm|in|pt|pc)?$/i,jt=/^\d+(?:\.\d+)?$/;function Bt(e,t){const i=(null!=e?e:"").trim();return Ut.test(i)?jt.test(i)?`${i}px`:i:`${t}px`}function Nt(e,t){const i=(null!=e?e:"").trim().toLowerCase(),n=/^(\d+(?:\.\d+)?)(?:px)?$/.exec(i);return n?Number.parseFloat(n[1]):t}function $t(t,i,n,o){return P(this,void 0,void 0,(function*(){N(t);const s=$(t)||"",r=i.direct;if(!r||2!==r.contractVersion||!r.moduleUrl)return!1;let a;try{a=yield St(r.moduleUrl)}catch(e){return!1}if(!t.isConnected||($(t)||"")!==s)return!1;if(2!==a.contractVersion)return!1;Rt(t);let d=null;if(!0===a.acceptsHostProps&&(d=function(e){var t;const i=null!==(t=Mt.get(e))&&void 0!==t?t:new Set;let n=1;for(;i.has(n);)n+=1;return i.add(n),Mt.set(e,i),n}(r.moduleUrl),d>1)){try{a=yield St(function(e,t){if(1===t)return e;try{const i=new URL(e);return i.hash=String(t),i.toString()}catch(i){return`${e}#${t}`}}(r.moduleUrl,d))}catch(e){return Wt(r.moduleUrl,d),!1}if(!t.isConnected||($(t)||"")!==s||2!==a.contractVersion)return Wt(r.moduleUrl,d),!1}const l=document.createElement("div");l.setAttribute("data-widgetic-direct","1"),l.setAttribute("width",n||t.getAttribute("width")||"400");const c=t.getAttribute("height");c&&l.setAttribute("height",c);const h=_e(t);h||function(e,t,i){e.style.display="block",e.style.boxSizing="border-box",e.style.width=Bt(t,Pt),e.style.height=Bt(i,Ht),e.style.maxWidth="100%",e.style.overflow="hidden"}(l,n||t.getAttribute("width"),c);const g=l.attachShadow({mode:"open"}),u=document.createElement("style");u.textContent=(h?"":".widgetic-direct-target { width: 100%; height: 100%; }\n.widgetic-direct-target > :first-child { width: 100%; height: 100%; min-width: 0; min-height: 0; }\n")+a.getStyles();const m=document.createElement("div");m.className="widgetic-direct-target",g.append(u,m);const p={host:t,compositionId:s,payload:i,instance:null,stop:()=>{},listensOnWindow:!0!==a.acceptsHostProps,moduleUrl:r.moduleUrl,moduleSlot:d};let f;p.listensOnWindow&&(Ct.add(p),Dt());try{f=a.mount(m,zt(t,p.payload))}catch(e){throw null!==d&&Wt(r.moduleUrl,d),Ct.delete(p)&&Dt(),e}p.instance=f;const v=function(e,t){const i="undefined"!=typeof MutationObserver?MutationObserver:null;if(!i)return()=>{};let n;try{n=new i((e=>{_(e)&&t()}))}catch(e){return()=>{}}return n.observe(e,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),()=>n.disconnect()}(t,(()=>kt(t,p))),w=["play","pause","ended","seeking","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"],y=["position","navigate","complete","reset","metadata"],b=[];let I=!1,S=0;for(const e of w){const i=`widgetic:media:${e}`,n=t=>{if(I)return;const i=t,n=i.detail&&"object"==typeof i.detail?i.detail:{};try{le().handleMediaEvent({type:e,compositionId:s,config:{persistState:!0,autoResume:!0},data:n})}catch(e){}};m.addEventListener(i,n),t.addEventListener(i,n),b.push((()=>{m.removeEventListener(i,n),t.removeEventListener(i,n)}))}const E=["play","pause","timeupdate","seeking","volumechange","ended"];for(const e of E){const t=t=>{if(I)return;const i=t.target;if(!i||"AUDIO"!==i.tagName&&"VIDEO"!==i.tagName)return;if("pause"===e&&i.ended)return;if("timeupdate"===e){const e=Date.now();if(e-S<750)return;S=e}const n="VIDEO"===i.tagName?"video":"audio";try{le().handleMediaEvent({type:e,compositionId:s,config:{mediaType:n,persistState:!0,autoResume:!0},data:{mediaType:n,position:i.currentTime||0,duration:Number.isFinite(i.duration)?i.duration:void 0,volume:i.muted?0:i.volume,playing:!i.paused}})}catch(e){}};m.addEventListener(e,t,!0),b.push((()=>{m.removeEventListener(e,t,!0)}))}const T=e=>{const t=e.detail;if(!t||"object"!=typeof t)return;const i=Array.from(m.querySelectorAll("audio, video")),n=i.find((e=>!e.paused))||i[0]||null;I=!0;try{if("pause"===t.command)for(const e of i){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{e.currentTime=t.position}catch(e){}try{e.pause()}catch(e){}}else if("play"===t.command){if(n){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{n.currentTime=t.position}catch(e){}try{const e=n.play();e&&"function"==typeof e.catch&&e.catch((()=>{}))}catch(e){}}}else if("restore"===t.command&&t.state){if(n&&("number"==typeof t.state.volume&&(n.volume=Math.max(0,Math.min(1,t.state.volume))),"number"==typeof t.state.position&&!Number.isNaN(t.state.position)&&t.state.position>=0))try{n.currentTime=t.state.position}catch(e){}}else if("setVolume"===t.command&&"number"==typeof t.volume){const e=Math.max(0,Math.min(1,t.volume));for(const t of i)t.volume=e}}finally{setTimeout((()=>{I=!1}),150)}};m.addEventListener("widgetic:media:command",T),b.push((()=>{m.removeEventListener("widgetic:media:command",T)}));for(const e of y){const i=`widgetic:content:${e}`,n=t=>{const i=t,n=i.detail&&"object"==typeof i.detail?i.detail:{};try{de().handleContentPositionEvent({type:e,compositionId:s,config:{contentType:"custom",persistState:!0,autoResume:!0},data:n})}catch(e){}};m.addEventListener(i,n),t.addEventListener(i,n),b.push((()=>{m.removeEventListener(i,n),t.removeEventListener(i,n)}))}p.stop=()=>{v();for(const e of b)e()},Tt.set(t,p),t.appendChild(l),o(t);const C=n||t.getAttribute("width");if(b.push(wt({host:t,box:l,widthCss:Bt(C,Pt),widthPixels:pt(C,Pt),heightPixels:pt(c,Ht)})),Ve(t))try{const i=function(t){var i,n;const{host:o,box:s,shadowRoot:r,compositionId:a}=t,d=s.offsetHeight>0?s.offsetHeight:t.fallbackHeightPixels,l=qe(o,d),c=it({host:o,box:s,compositionId:a,settings:l,startHeight:d,originalHeightCss:s.style.height});c.startAtStoredHeight();let h=!1,g=null;const u=[],m=new WeakSet,p=()=>{if(!h)if(c.isAnimating())f();else try{const e=et(r,s,s.offsetHeight,l,m);null!==e&&c.follow(e)}catch(t){e.debug("[autoscale] The widget could not be measured",{compositionId:a,error:t})}},f=()=>{h||null!==g||(g=setTimeout((()=>{g=null,p()}),l.debounceDelay))};let v=null;try{"undefined"!=typeof MutationObserver&&(v=new MutationObserver(f),v.observe(r,{subtree:!0,childList:!0,characterData:!0,attributes:!0}))}catch(t){e.debug("[autoscale] The widget's changes cannot be watched",{compositionId:a,error:t})}let w=null;try{"undefined"!=typeof ResizeObserver&&(w=new ResizeObserver(f),w.observe(s))}catch(t){e.debug("[autoscale] The size of the widget's box cannot be watched",{compositionId:a,error:t})}const y=["load","transitionend","animationend"];for(const e of y)r.addEventListener(e,f,!0);try{null===(n=null===(i=document.fonts)||void 0===i?void 0:i.ready)||void 0===n||n.then(f,(()=>{}))}catch(e){}u.push(setTimeout(p,0));for(const e of $e)u.push(setTimeout(f,e));return{refresh:f,stop(){if(!h){h=!0,null!==g&&clearTimeout(g),g=null;for(const e of u)clearTimeout(e);null==v||v.disconnect(),null==w||w.disconnect();for(const e of y)r.removeEventListener(e,f,!0)}}}}({host:t,box:l,shadowRoot:g,compositionId:s,fallbackHeightPixels:Nt(c,Ht)});b.push((()=>i.stop()))}catch(e){}try{de().resumeWidgetPosition(s)}catch(e){}try{le().resumeWidget(s)}catch(e){}return t.dispatchEvent(new CustomEvent("widgetic:ready",{bubbles:!0,composed:!0,detail:{compositionId:s}})),!0}))}const Ft=new WeakMap;function _t(e,t){Vt(e),Ft.set(e,t)}function Vt(t){const i=Ft.get(t);if(!i)return!1;Ft.delete(t);try{i.stop()}catch(t){e.debug("[workflows] A workflow failed while it was being stopped",{error:t})}return!0}const Kt="data-widgetic-refused",qt="data-widgetic-context-invalid",Yt="data-widgetic-composition-tracked";function Gt(e,t){const i=e.getAttribute(Yt);if(i&&i!==t){Vt(e),function(e){e.removeAttribute("data-widgetic-mounting"),e.removeAttribute("data-widgetic-mounted"),e.removeAttribute(ke),e.removeAttribute(Kt),e.removeAttribute(qt)}(e),Rt(e),ot(e);for(const t of Array.from(e.querySelectorAll("iframe")))t.remove();e.style.display="",e.removeAttribute("data-widgetic-overlay")}e.setAttribute(Yt,t)}const Qt=/^[a-z][a-z0-9_]{0,62}$/,Jt=/^[a-z][a-z0-9_]{0,39}$/;function Zt(e){if(e.length>200)return null;const t=e.indexOf("@");if(-1===t)return/^[a-z][a-z0-9_]{0,31}$/.test(e)?{metric:e,selector:null}:null;const i=e.slice(0,t),n=e.slice(t+1);return/^[a-z][a-z0-9_]{0,31}$/.test(i)&&""!==n&&n===n.trim()?{metric:i,selector:n}:null}function Xt(e){if(e.length>200)return!1;const t=e.indexOf("@"),i=-1===t?e:e.slice(0,t);return!!Jt.test(i)&&(-1===t||""!==e.slice(t+1))}function ei(e){const t=[],i=[],n=[],o=e=>{t.length<20&&Qt.test(e)&&!t.includes(e)&&t.push(e)};for(const t of e.inputTables)o(t);for(const t of e.inputColumns){if(i.length>=50)break;Qt.test(t.table)&&Qt.test(t.column)&&(i.some((e=>e.table===t.table&&e.column===t.column))||(i.push({table:t.table,column:t.column}),o(t.table)))}for(const t of e.actionIds){if(n.length>=20)break;Xt(t)&&!n.includes(t)&&n.push(t)}return{tables:t,fields:i,goals:n}}function ti(e,t){const i=[];for(const e of t.goals){const t=Zt(e);t&&i.push({id:e,metric:t.metric,goalTarget:t.selector})}return{compositionId:e,tables:t.tables,fields:t.fields,goals:i}}const ii=["context","values","media-resolver"],ni=new Set(["widgetic:ready","widgetic:error","widgetic:submitted","widgetic:resize","widgetic:data","widgetic:interaction","widgetic:form-submit","widgetic:goal"]),oi={play:!0,pause:!0,stop:!0,ended:!0,seeking:!0,seeked:!0,timeupdate:!0,progress:!0,durationchange:!0,loadedmetadata:!0,volumechange:!0,trackchange:!0,playlistchange:!0},si={position:!0,navigate:!0,complete:!0,reset:!0,metadata:!0};const ri="goal-reporter";const ai=new WeakMap;class di{constructor(e,t,i,n,o){this.host=e,this.iframe=t,this.gatewayOrigin=i,this.compositionId=n,this.services=o,this.readyDispatched=!1,this.pendingWidgetUpdate=null,this.latestAbGoal=null,this.latestWorkflowWatch=null,this.attributeFlushScheduled=!1,this.attributeObserver=null,N(this.host),this.onWindowMessage=e=>this.handleWrapperMessage(e),window.addEventListener("message",this.onWindowMessage),this.iframe.addEventListener("load",(()=>{this.postHostSnapshot(),this.flushPendingWidgetUpdate()})),this.observeHostAttributes()}observeHostAttributes(){const e="undefined"!=typeof MutationObserver?MutationObserver:null;if(!e)return;let t;try{t=new e((e=>{e.some((e=>"attributes"===e.type&&e.attributeName&&ii.includes(e.attributeName)))&&this.scheduleHostSnapshot()}))}catch(e){return}t.observe(this.host,{attributes:!0,attributeFilter:[...ii]}),this.attributeObserver=t}scheduleHostSnapshot(){this.attributeFlushScheduled||(this.attributeFlushScheduled=!0,queueMicrotask((()=>{this.attributeFlushScheduled=!1,this.postHostSnapshot()})))}postHostSnapshot(){try{const e=ht(this.host);e.contextInvalid?this.host.setAttribute(qt,"1"):this.host.removeAttribute(qt);const t=this.iframe.contentWindow;if(!t)return;if(!this.frameCanReceive())return;const i=ut(this.compositionId,e,this.services);t.postMessage(i,this.gatewayOrigin),this.postAbGoal(),this.postWorkflowWatch()}catch(e){}}sendAbGoal(e){this.latestAbGoal=e,this.postAbGoal()}postAbGoal(){if(this.latestAbGoal)try{const e=this.iframe.contentWindow;if(!e||!this.frameCanReceive())return;e.postMessage({type:"widgetic:ab-goal",compositionId:this.compositionId,metric:this.latestAbGoal.metric,goalTarget:this.latestAbGoal.goalTarget},this.gatewayOrigin)}catch(e){}}sendWorkflowWatch(e){this.latestWorkflowWatch=e,this.postWorkflowWatch()}postWorkflowWatch(){var e,t;if(this.latestWorkflowWatch)try{const i=this.iframe.contentWindow;if(!i||!this.frameCanReceive())return;i.postMessage((e=this.compositionId,t=this.latestWorkflowWatch,{type:"widgetic:workflow-watch",version:1,compositionId:e,tables:t.tables,fields:t.fields,goals:t.goals}),this.gatewayOrigin)}catch(e){}}sendWidgetUpdate(e){try{const t=this.iframe.contentWindow;if(!t)return;if(!this.frameCanReceive())return void(this.pendingWidgetUpdate=e);t.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update",compositionId:this.compositionId},e.design?{design:e.design}:{}),e.content?{content:e.content}:{}),e.contentItems?{contentItems:e.contentItems}:{}),this.gatewayOrigin)}catch(e){}}flushPendingWidgetUpdate(){const e=this.pendingWidgetUpdate;e&&(this.pendingWidgetUpdate=null,this.sendWidgetUpdate(e))}frameCanReceive(){return!function(e){var t;try{return"about:blank"===(null===(t=e.contentWindow)||void 0===t?void 0:t.location.href)}catch(e){return!1}}(this.iframe)}handleWrapperMessage(e){var t,i;if(e.source!==this.iframe.contentWindow)return;if(e.origin!==this.gatewayOrigin)return;const n=e.data;if(!n||"object"!=typeof n||Array.isArray(n))return;const o=n.type;if("string"!=typeof o)return;const s=n.compositionId;if("string"==typeof s&&s!==this.compositionId)return;let r=null!==(i=null!==(t=n.detail)&&void 0!==t?t:n.payload)&&void 0!==i?i:n.data;if(void 0===r){const e={};for(const t of Object.keys(n))"type"!==t&&"compositionId"!==t&&(e[t]=n[t]);Object.keys(e).length>0&&(r=e)}const a=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length>8192?{}:e}catch(e){return{}}}(r),d=Object.assign({compositionId:this.compositionId},a);if(o.startsWith("widgetic:media:")){const e=o.replace("widgetic:media:","");if(l=e,Object.prototype.hasOwnProperty.call(oi,l))try{le().handleMediaEvent({type:e,compositionId:this.compositionId,config:{persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else{var l;if(o.startsWith("widgetic:content:")){const e=o.replace("widgetic:content:","");if(function(e){return Object.prototype.hasOwnProperty.call(si,e)}(e))try{de().handleContentPositionEvent({type:e,compositionId:this.compositionId,config:{contentType:"custom",persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(ni.has(o))if("widgetic:ready"!==o)this.dispatchHostEvent(o,d);else{try{de().resumeWidgetPosition(this.compositionId)}catch(e){}try{le().resumeWidget(this.compositionId)}catch(e){}if(this.readyDispatched)return;this.readyDispatched=!0,this.postHostSnapshot(),this.flushPendingWidgetUpdate();const e=function(e){const t=e.capabilities;return Array.isArray(t)?t.filter((e=>"string"==typeof e&&e.length<=40)).slice(0,32):[]}(a);this.dispatchHostEvent("widgetic:ready",Object.assign({compositionId:this.compositionId},e.length>0?{capabilities:e}:{}))}}}dispatchHostEvent(e,t){this.host.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}destroy(){var e;window.removeEventListener("message",this.onWindowMessage),null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null}}function li(e){return ai.get(e)}function ci(e,t,i){e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{compositionId:t,code:i},bubbles:!0,composed:!0}))}const hi="widgetic:workflow-event",gi="widgetic:workflow-step",ui=/^[A-Za-z0-9_.:-]{1,64}$/,mi=new Set(["__proto__","constructor","prototype"]);function pi(e){return"string"==typeof e?e.length>200?e.slice(0,200):e:"number"==typeof e?Number.isFinite(e)?e:void 0:"boolean"==typeof e?e:void 0}function fi(e){if("object"!=typeof e||null===e||Array.isArray(e))return null;const{name:t,values:i}=e;if("string"!=typeof t||!ui.test(t))return null;const n={};if("object"==typeof i&&null!==i&&!Array.isArray(i)){let e=0;for(const t of Object.keys(i)){if(e>=12)break;if(mi.has(t)||!ui.test(t))continue;const o=pi(i[t]);void 0!==o&&(n[t]=o,e+=1)}}return{name:t,values:n}}function vi(t,i,n){if(!t||"function"!=typeof t.dispatchEvent)return!1;const o=fi({name:i,values:n});return o?(t.dispatchEvent(new CustomEvent(hi,{detail:o})),!0):(e.warn("[workflows] The page event was not sent: its name is not one a workflow can wait for",{name:i}),!1)}class wi{constructor(){this.events=[]}add(e){this.events.push(e),this.events.length>20&&this.events.shift()}take(){const e=this.events;return this.events=[],e}clear(){this.events=[]}}function yi(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(De)||(e.style.display="block")}function bi(t,i,n,o,s){yi(t);const r=$(t),a=q(t,n),d=x(i,o||t.getAttribute("width")||"400",t.getAttribute("height")||"300",r||void 0,a);t.appendChild(d);const l=o||t.getAttribute("width");if(wt({host:t,box:d,widthCss:Bt(l,Pt),widthPixels:pt(l,Pt),heightPixels:pt(t.getAttribute("height"),Ht)}),Ve(t))try{!function(e){const{host:t,iframe:i,compositionId:n}=e;ot(t);const o=i.offsetHeight>0?i.offsetHeight:e.fallbackHeightPixels,s=qe(t,o),r=it({host:t,box:i,compositionId:n,settings:s,startHeight:o,originalHeightCss:""});r.startAtStoredHeight();let a=!1,d=null,l=null;const c=()=>{l=null,a||null===d||r.follow(d)},h=e=>{var t;const i=null===(t=e.detail)||void 0===t?void 0:t.height;"number"!=typeof i||!Number.isFinite(i)||i<=0||(d=i,null===l&&(l=setTimeout(c,s.debounceDelay)))};t.addEventListener("widgetic:resize",h);const g={refresh:c,stop(){a||(a=!0,null!==l&&clearTimeout(l),l=null,t.removeEventListener("widgetic:resize",h))}};nt.set(t,g)}({host:t,iframe:d,compositionId:r||"",fallbackHeightPixels:Nt(t.getAttribute("height"),300)})}catch(t){e.debug("[autoscale] The frame could not be followed",{instanceId:r,error:t})}if(r)try{!function(e,t,i,n,o){let s;try{s=new URL(i).origin}catch(e){return}const r=ai.get(e);r&&r.destroy();const a=new di(e,t,s,n,o);ai.set(e,a),a.postHostSnapshot()}(t,d,i,r,s)}catch(e){}try{Y(t,n,(e=>{const i=li(t);if(i)i.sendWidgetUpdate({design:e.design,content:e.content,contentItems:e.contentItems});else if(d.contentWindow)try{d.contentWindow.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update"},e.design?{design:e.design}:{}),e.content?{content:e.content}:{}),e.contentItems?{contentItems:e.contentItems}:{}),"*")}catch(e){}}))}catch(e){}}function Ii(t,i,n){var o;const s=$(t)||"",r=q(t,i);"iframe"!==t.getAttribute("render-mode")&&"true"!==t.getAttribute("use-iframe")&&(null===(o=r.direct)||void 0===o?void 0:o.moduleUrl)||!r.embedUrl?function(t,i,n){return P(this,void 0,void 0,(function*(){try{return yield $t(t,i,n,yi)}catch(i){return e.warn("[mount] The widget threw while it was mounted in the page, so it is shown in its frame",{instanceId:$(t),error:i}),!1}}))}(t,r,n).then((i=>{if(!i&&t.isConnected&&($(t)||"")===s&&!t.getAttribute("data-widgetic-mounted"))return r.embedUrl?(e.debug("[mount] The widget cannot be mounted in the page, so it is shown in its frame",{instanceId:s}),void bi(t,r.embedUrl,r,n,gt(r))):void Ti(t,s,"NOT_FOUND","not_found")})):bi(t,r.embedUrl,r,n,gt(r))}function Si(t){if(!t.hasAttribute("workflow-id"))return null;try{return import("./workflows.js").catch((t=>(e.warn("[workflows] The workflow code could not be loaded, so the tag is embedded as it is",{error:t}),null)))}catch(t){return e.warn("[workflows] The workflow code could not be loaded, so the tag is embedded as it is",{error:t}),Promise.resolve(null)}}function Ei(t,i,n,o){n?n.then((n=>{var s;if(!t.isConnected||t.getAttribute("data-widgetic-mounted"))return;let r=null;try{r=null!==(s=null==n?void 0:n.startWorkflowEmbed(t,Object.assign({hydrate:e=>{Ci(e)},markMounted:yi},o?{width:o}:{})))&&void 0!==s?s:null}catch(t){e.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{error:t})}r||Ii(t,i,o)})):Ii(t,i,o)}function Ti(e,t,i,n){e.removeAttribute("data-widgetic-mounting"),e.setAttribute(Kt,i),ci(e,t,n)}function Ci(t){var i;N(t);const n=V(t),o=null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null;if(K(t),o&&Gt(t,o),t.getAttribute("data-widgetic-mounted")||t.getAttribute("data-widgetic-mounting")||t.getAttribute(ke)||t.getAttribute(Kt))return!0;const s=t.getAttribute("src");if(s)return bi(t,s),!0;if(!n||!o)return!1;const r=t.hasAttribute(ke),a=function(t){var i,n,o,s,r;let a;try{a=U(t)}catch(t){return e.warn("[published-host-display] Could not read the embed's display settings",{error:t}),{suppressed:!1}}return Ae(null===(n=null===(i=a.device)||void 0===i?void 0:i.mobileEnabled)||void 0===n||n,null===(s=null===(o=a.device)||void 0===o?void 0:o.desktopEnabled)||void 0===s||s)?("overlay"===(null===(r=a.triggers)||void 0===r?void 0:r.mode)&&(t.style.display="none",t.setAttribute(De,"pending")),{suppressed:!1,triggers:a.triggers}):(t.style.display="none",t.setAttribute(ke,"true"),e.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:a.compositionId,device:a.device}),{suppressed:!0})}(t);if(a.suppressed)return r||ci(t,o,"device_restricted"),!0;t.setAttribute("data-widgetic-mounting","1");const d="composition"===n.kind?Si(t):null;return("widget"===n.kind?T(o):C(o)).then((e=>{var i;if(t.getAttribute("data-widgetic-mounted"))return;if("refused"===e.status)return t.removeAttribute("data-widgetic-mounting"),t.setAttribute(Kt,e.refusal.code),M(o,e.refusal),void ci(t,o,W(e.refusal.code)||"domain_not_allowed");if("failed"===e.status)return void Ti(t,o,e.failure.gatewayCode,e.failure.stateCode);const n="found"===e.status?e.payload:null;if(!(null==n?void 0:n.embedUrl))return t.removeAttribute("data-widgetic-mounting"),void Ti(t,o,"NOT_FOUND","not_found");const{triggers:s}=a;if("overlay"!==(null==s?void 0:s.mode))Ei(t,n,d),s&&ze(t,s);else{const e=(null===(i=s.overlay)||void 0===i?void 0:i.fullWidth)?"100%":void 0;ze(t,s,(()=>Ei(t,n,d,e)))}})),!0}function Mi(e=document){const t=e.querySelectorAll("widgetic, widgetic-embed");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&Ci(e)&&(i+=1);return i}const Wi={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class xi{constructor(e={}){this.compositionCache=new Map,this.widgetCache=new Map,this.pendingCompositionRequests=new Map,this.pendingWidgetRequests=new Map,this.compositionResolvers=new Map,this.widgetResolvers=new Map,this.compositionBatchQueue=[],this.widgetBatchQueue=[],this.compositionBatchTimer=null,this.widgetBatchTimer=null,this.lastBatchError=null,this.config=Object.assign(Object.assign({},Wi),e)}getCompositions(e){return P(this,void 0,void 0,(function*(){"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-start");try{const t=[],i=[];for(const n of e){const e=this.getCachedComposition(n);if(e){t.push(e);continue}const o=this.pendingCompositionRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchCompositions(i);t.push(...e)}return Object.defineProperty(t,"compositions",{get(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(t,"success",{value:!this.lastBatchError,enumerable:!1,configurable:!0}),Object.defineProperty(t,"error",{value:this.lastBatchError||void 0,enumerable:!1,configurable:!0}),t}finally{"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-end")}}))}getWidgets(e){return P(this,void 0,void 0,(function*(){const t=[],i=[];for(const n of e){const e=this.getCachedWidget(n);if(e){t.push(e);continue}const o=this.pendingWidgetRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchWidgets(i);t.push(...e)}return t}))}getComposition(e){return P(this,void 0,void 0,(function*(){const t=yield this.getCompositions([e]);if(0===t.length)throw new Error(`Composition not found: ${e}`);return t[0]}))}getWidget(e){return P(this,void 0,void 0,(function*(){const t=yield this.getWidgets([e]);if(0===t.length)throw new Error(`Widget not found: ${e}`);return t[0]}))}batchCompositions(e){return P(this,void 0,void 0,(function*(){var t;const i=[];for(const t of e)if(this.pendingCompositionRequests.has(t))i.push(this.pendingCompositionRequests.get(t));else{const e=new Promise(((e,i)=>{this.compositionBatchQueue.push(t),this.scheduleCompositionBatch(),this.compositionResolvers.set(t,{resolve:e,reject:i})}));this.pendingCompositionRequests.set(t,e),i.push(e)}const n=yield Promise.allSettled(i),o=n.find((e=>"rejected"===e.status));return this.lastBatchError=o?(null===(t=o.reason)||void 0===t?void 0:t.message)||String(o.reason):null,n.filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}batchWidgets(e){return P(this,void 0,void 0,(function*(){const t=[];for(const i of e)if(this.pendingWidgetRequests.has(i))t.push(this.pendingWidgetRequests.get(i));else{const e=new Promise(((e,t)=>{this.widgetBatchQueue.push(i),this.scheduleWidgetBatch(),this.widgetResolvers.set(i,{resolve:e,reject:t})}));this.pendingWidgetRequests.set(i,e),t.push(e)}return(yield Promise.allSettled(t)).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}scheduleCompositionBatch(){this.compositionBatchTimer||(this.compositionBatchTimer=window.setTimeout((()=>{this.executeCompositionBatch()}),this.config.debounceDelay))}scheduleWidgetBatch(){this.widgetBatchTimer||(this.widgetBatchTimer=window.setTimeout((()=>{this.executeWidgetBatch()}),this.config.debounceDelay))}executeCompositionBatch(){return P(this,void 0,void 0,(function*(){const e=[...this.compositionBatchQueue];if(this.compositionBatchQueue=[],this.compositionBatchTimer=null,0!==e.length)try{const t=yield this.fetchCompositionsBatch(e);for(const e of t.compositions){this.cacheComposition(e);const t=this.compositionResolvers.get(e.id);t&&(t.resolve(e),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.compositionResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}for(const t of e){const e=this.compositionResolvers.get(t);e&&(e.reject(new Error(`Composition not found in batch response: ${t}`)),this.compositionResolvers.delete(t)),this.pendingCompositionRequests.delete(t)}}catch(t){for(const i of e){const e=this.compositionResolvers.get(i);e&&(e.reject(t),this.compositionResolvers.delete(i)),this.pendingCompositionRequests.delete(i)}}}))}executeWidgetBatch(){return P(this,void 0,void 0,(function*(){const e=[...this.widgetBatchQueue];if(this.widgetBatchQueue=[],this.widgetBatchTimer=null,0!==e.length)try{const t=yield this.fetchWidgetsBatch(e);for(const e of t.widgets){this.cacheWidget(e);const t=this.widgetResolvers.get(e.id);t&&(t.resolve(e),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.widgetResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}for(const t of e){const e=this.widgetResolvers.get(t);e&&(e.reject(new Error(`Widget not found in batch response: ${t}`)),this.widgetResolvers.delete(t)),this.pendingWidgetRequests.delete(t)}}catch(t){for(const i of e){const e=this.widgetResolvers.get(i);e&&(e.reject(t),this.widgetResolvers.delete(i)),this.pendingWidgetRequests.delete(i)}}}))}fetchCompositionsBatch(e){return P(this,arguments,void 0,(function*(e,r=1){var a,d,l;try{const r=yield t(),d=new i({basePath:o(),apiKey:()=>P(this,void 0,void 0,(function*(){return r})),headers:{"X-SDK-Version":`embed-sdk/${n}`}}),l=new s(d),c=yield l.getCompositionsBatch({getCompositionsBatchRequest:{compositionIds:e}}),h=c.compositions||[];return{compositions:h.map((e=>{if(!e||"object"!=typeof e)return e;const{internalConfig:t,adminNotes:i}=e;return H(e,["internalConfig","adminNotes"])})),errors:null===(a=c.errors)||void 0===a?void 0:a.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(r<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,r-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchCompositionsBatch(e,r+1)}const i=null===(d=null==t?void 0:t.response)||void 0===d?void 0:d.status,n=null===(l=null==t?void 0:t.response)||void 0===l?void 0:l.statusText;if("number"==typeof i){let e=`HTTP ${i}: ${n||"Request failed"}`;switch(i){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these compositions";break;case 404:e="Composition not found: One or more compositions do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}fetchWidgetsBatch(e){return P(this,arguments,void 0,(function*(e,s=1){var a,d,l;try{const s=yield t(),d=new i({basePath:o(),apiKey:()=>P(this,void 0,void 0,(function*(){return s})),headers:{"X-SDK-Version":`embed-sdk/${n}`}}),l=new r(d),c=yield l.getWidgetsBatch({getWidgetsBatchRequest:{widgetIds:e}});return{widgets:c.widgets||[],errors:null===(a=c.errors)||void 0===a?void 0:a.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(s<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,s-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchWidgetsBatch(e,s+1)}const i=null===(d=null==t?void 0:t.response)||void 0===d?void 0:d.status,n=null===(l=null==t?void 0:t.response)||void 0===l?void 0:l.statusText;if("number"==typeof i){let e=`HTTP ${i}: ${n||"Request failed"}`;switch(i){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these widgets";break;case 404:e="Widget not found: One or more widgets do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}getCachedComposition(e){const t=this.compositionCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.compositionCache.delete(e),null):t.data}getCachedWidget(e){const t=this.widgetCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.widgetCache.delete(e),null):t.data}cacheComposition(e){this.compositionCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}cacheWidget(e){this.widgetCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}clearCache(){this.compositionCache.clear(),this.widgetCache.clear()}getCacheStats(){return{compositions:{size:this.compositionCache.size,entries:Array.from(this.compositionCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},widgets:{size:this.widgetCache.size,entries:Array.from(this.widgetCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},pending:{compositions:this.pendingCompositionRequests.size,widgets:this.pendingWidgetRequests.size},queues:{compositions:this.compositionBatchQueue.length,widgets:this.widgetBatchQueue.length}}}}let Ai=null;function Di(){return Ai||(Ai=new xi),Ai}function ki(){Ai=null}var Oi=Object.freeze({__proto__:null,BatchApiClient:xi,getBatchClient:Di,resetBatchClient:ki});const Li={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:a()};class Ri{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},Li),e)}loadModule(e){return P(this,arguments,void 0,(function*(e,t={}){const i=this.getModuleKey(e.id,t.version||e.version),n=this.loadingPromises.get(i);if(n&&!t.force)return n;if(!t.force){const e=this.getCachedModule(i);if(e)return{module:e.module,url:e.url,loadTime:0,cached:!0}}const o=this.doLoadModule(e,t);this.loadingPromises.set(i,o);try{const e=yield o;return this.loadingPromises.delete(i),e}catch(e){throw this.loadingPromises.delete(i),e}}))}loadModules(e){return P(this,arguments,void 0,(function*(e,t={}){const i=new Map,n=new Map;for(const t of e)if(n.set(t.id,t),t.dependencies){this.dependencyGraph.set(t.id,new Set(t.dependencies));for(const e of t.dependencies)i.set(e,t)}const o=this.resolveDependencyOrder(e),s=[];for(const e of o)try{const i=yield this.loadModule(e,t);s.push(i)}catch(e){}return s}))}getLatestVersion(e){return P(this,void 0,void 0,(function*(){try{const t=`${this.config.cdnBaseUrl}/${e}/latest`,i=yield this.fetchWithHttp3(t,{timeout:5e3});if(i.ok){return(yield i.json()).version}}catch(e){}return null}))}preloadModules(e){return P(this,void 0,void 0,(function*(){const t=e.map((e=>this.loadModule(e,{timeout:3e4}).catch((e=>{}))));yield Promise.allSettled(t)}))}invalidateModule(e,t){if(t){const i=this.getModuleKey(e,t);this.moduleCache.delete(i)}else{Array.from(this.moduleCache.keys()).filter((t=>t.startsWith(`${e}@`))).forEach((e=>this.moduleCache.delete(e)))}}clearCache(){this.moduleCache.clear(),this.loadingPromises.clear()}getCacheStats(){return{size:this.moduleCache.size,entries:Array.from(this.moduleCache.entries()).map((([e,t])=>({key:e,version:t.version,age:Date.now()-t.timestamp,ttl:t.ttl,url:t.url}))),loading:this.loadingPromises.size,http3Supported:this.http3Supported}}doLoadModule(e,t){return P(this,void 0,void 0,(function*(){const i=Date.now(),n=t.version||e.version,o=this.resolveModuleUrl(e,n);try{e.dependencies&&e.dependencies.length>0&&(yield this.loadDependencies(e.dependencies));const s=yield this.loadModuleFromUrl(o,{timeout:t.timeout||this.config.loadTimeout,retries:t.retries||this.config.maxRetries});if(!this.validateModule(s))throw new Error(`Invalid module structure for ${e.id}`);const r=this.getModuleKey(e.id,n);return this.cacheModule(r,{module:s,url:o,timestamp:Date.now(),version:n,ttl:this.config.cacheTTL}),{module:s,url:o,loadTime:Date.now()-i,cached:!1}}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load module ${e.id}@${n}: ${i}`)}}))}loadModuleFromUrl(e,t){return P(this,void 0,void 0,(function*(){let i=null;for(let n=1;n<=t.retries;n++)try{if(e.endsWith(".mjs")||e.includes("type=module")){const i=yield this.loadEsModule(e,t.timeout);return this.extractWidgetFromEsModule(i)}const i=yield this.fetchModuleText(e,t.timeout);return this.evaluateUmdModule(i,e)}catch(e){if(i=e instanceof Error?e:new Error(String(e)),n<t.retries){const e=this.config.retryDelay*Math.pow(2,n-1);yield new Promise((t=>setTimeout(t,e)))}}throw i||new Error("Module loading failed")}))}loadEsModule(e,t){return P(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{const o=setTimeout((()=>{n(new Error(`Module load timeout: ${e}`))}),t);import(e).then((e=>{clearTimeout(o),i(e)})).catch((e=>{clearTimeout(o),n(e)}))}))}))}fetchModuleText(e,t){return P(this,void 0,void 0,(function*(){const i=yield this.fetchWithHttp3(e,{timeout:t});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return yield i.text()}))}fetchWithHttp3(e,t){return P(this,void 0,void 0,(function*(){null===this.http3Supported&&(this.http3Supported=yield this.detectHttp3Support());const i={signal:AbortSignal.timeout(t.timeout)};return fetch(e,i)}))}detectHttp3Support(){return P(this,void 0,void 0,(function*(){var e;try{if("connection"in navigator&&"effectiveType"in navigator.connection){const e=navigator.connection;return"4g"===e.effectiveType||"5g"===e.effectiveType}const t=`${this.config.cdnBaseUrl}/test-http3`,i=yield fetch(t,{method:"HEAD",signal:AbortSignal.timeout(2e3)}).catch((()=>null));return(null===(e=null==i?void 0:i.headers.get("alt-svc"))||void 0===e?void 0:e.includes("h3"))||!1}catch(e){return!1}}))}extractWidgetFromEsModule(e){const t=e.default||e.Widget||e.widget||e;if(!t)throw new Error("No widget found in module exports");return{id:t.id||"unknown",version:t.version||"1.0.0",component:t.component||t,metadata:t.metadata,dependencies:t.dependencies}}evaluateUmdModule(e,t){const i={window:"undefined"!=typeof window?window:{},document:"undefined"!=typeof document?document:{},console:console,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval},n=new Function("window","document","console","setTimeout","clearTimeout","setInterval","clearInterval",`\n let module = { exports: {} };\n let exports = module.exports;\n \n ${e}\n \n return module.exports.default || module.exports;\n `)(i.window,i.document,i.console,i.setTimeout,i.clearTimeout,i.setInterval,i.clearInterval);if(!n)throw new Error(`Module evaluation failed: ${t}`);return{id:n.id||"unknown",version:n.version||"1.0.0",component:n.component||n,metadata:n.metadata,dependencies:n.dependencies}}loadDependencies(e){return P(this,void 0,void 0,(function*(){const t=e.map((e=>P(this,void 0,void 0,(function*(){try{if("undefined"!=typeof window&&window[e])return}catch(e){}}))));yield Promise.allSettled(t)}))}resolveDependencyOrder(e){const t=new Set,i=new Set,n=[],o=new Map(e.map((e=>[e.id,e]))),s=e=>{if(i.has(e.id))throw new Error(`Circular dependency detected: ${e.id}`);if(!t.has(e.id)){if(i.add(e.id),e.dependencies)for(const t of e.dependencies){const e=o.get(t);e&&s(e)}i.delete(e.id),t.add(e.id),n.push(e)}};for(const i of e)t.has(i.id)||s(i);return n}resolveModuleUrl(e,t){return e.moduleUrl?e.moduleUrl.replace("{{version}}",t):`${this.config.cdnBaseUrl}/${e.id}/${t}/widget.mjs`}validateModule(e){return!!(e&&e.id&&e.version&&e.component)}getModuleKey(e,t){return`${e}@${t}`}getCachedModule(e){const t=this.moduleCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.moduleCache.delete(e),null):t}cacheModule(e,t){this.moduleCache.set(e,t)}}let zi=null;function Pi(){return zi||(zi=new Ri),zi}function Hi(){zi=null}var Ui=Object.freeze({__proto__:null,ModuleLoader:Ri,getModuleLoader:Pi,resetModuleLoader:Hi});class ji{constructor(e){this.scrollPercentTarget=50,this.intersectionObserver=null,this.isInViewport=!0,this.hasBeenInViewport=!1,this.scrollListener=null,this.lastScrollY=0,this.scrollDistance=0,this.isTriggered=!1,this.debounceTimer=null,this.rafId=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,totalScrollDistance:0,viewportChanges:0},this.widgetId=e.widgetId,this.element=e.element,this.type=e.type,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,threshold:.1,distance:100,direction:"down",debounce:100}}initialize(){this.config.enabled&&(e.debug("Initializing ScrollTrigger",{widgetId:this.widgetId,type:this.type,config:this.config}),this.lastScrollY=window.scrollY,"viewport"===this.type?this.initializeViewportDetection():"distance"===this.type?this.initializeScrollDistance():"percent"===this.type&&this.initializeScrollPercent())}initializeViewportDetection(){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:this.config.threshold||.1,rootMargin:"0px"}),this.intersectionObserver.observe(this.element),e.debug("Viewport detection initialized",{widgetId:this.widgetId,threshold:this.config.threshold})}initializeScrollPercent(){this.scrollListener=this.debounce(this.handleScrollPercent.bind(this),this.config.debounce||100),window.addEventListener("scroll",this.scrollListener,{passive:!0}),e.debug("Scroll percent tracking initialized",{widgetId:this.widgetId,percent:this.scrollPercentTarget})}setScrollPercentTarget(e){this.scrollPercentTarget=Math.min(100,Math.max(0,e))}handleScrollPercent(){this.isDestroyed||this.isTriggered||(this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame((()=>{const e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;const t=window.scrollY/e*100;t>=this.scrollPercentTarget&&(this.isTriggered=!0,this.triggerActivated("scroll-percent",{scrollPercentage:t,targetPercent:this.scrollPercentTarget}))})))}initializeScrollDistance(){this.scrollListener=this.debounce(this.handleScrollDistance.bind(this),this.config.debounce||100),window.addEventListener("scroll",this.scrollListener,{passive:!0}),e.debug("Scroll distance tracking initialized",{widgetId:this.widgetId,distance:this.config.distance})}handleIntersection(t){if(this.isDestroyed)return;const i=t[t.length-1];if(!i)return;const n=this.isInViewport;if(this.isInViewport=i.isIntersecting,i.isIntersecting&&(this.hasBeenInViewport=!0),this.stats.viewportChanges++,e.debug("Viewport intersection changed",{widgetId:this.widgetId,isIntersecting:this.isInViewport,intersectionRatio:i.intersectionRatio}),n&&!this.isInViewport){if(!this.hasBeenInViewport)return;this.triggerActivated("scroll-out-of-view",{intersectionRatio:i.intersectionRatio,boundingClientRect:i.boundingClientRect})}else!n&&this.isInViewport&&this.triggerDeactivated("scroll-back-in-view",{intersectionRatio:i.intersectionRatio,boundingClientRect:i.boundingClientRect})}observeElement(t){!this.isDestroyed&&"viewport"===this.type&&this.intersectionObserver&&t!==this.element&&(this.intersectionObserver.unobserve(this.element),this.element=t,this.intersectionObserver.observe(t),e.debug("ScrollTrigger now watching another element",{widgetId:this.widgetId}))}handleScrollDistance(){this.isDestroyed||(this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame((()=>{const t=window.scrollY,i=t-this.lastScrollY;this.stats.totalScrollDistance+=Math.abs(i);const n=i>0,o=i<0;"down"===this.config.direction&&n?this.scrollDistance+=i:("up"===this.config.direction&&o||"any"===this.config.direction)&&(this.scrollDistance+=Math.abs(i));const s=this.config.distance||100;!this.isTriggered&&this.scrollDistance>=s&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{scrollDistance:this.scrollDistance,direction:n?"down":"up",scrollY:t})),this.lastScrollY=t,e.debug("Scroll distance updated",{widgetId:this.widgetId,scrollDistance:this.scrollDistance,requiredDistance:s,isTriggered:this.isTriggered})})))}triggerActivated(t,i){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const n=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:t,triggerData:i}});document.dispatchEvent(n),e.debug("Scroll trigger activated",{widgetId:this.widgetId,triggerType:t,triggerData:i})}triggerDeactivated(t,i){const n=new CustomEvent("widgetic:trigger-deactivated",{detail:{widgetId:this.widgetId,triggerType:t,triggerData:i}});document.dispatchEvent(n),e.debug("Scroll trigger deactivated",{widgetId:this.widgetId,triggerType:t,triggerData:i})}debounce(e,t){return i=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e()}),t)}}updateConfig(t){if(this.isDestroyed)return;const i=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),t),void 0!==t.threshold&&"viewport"===this.type&&(this.destroy(),this.isDestroyed=!1,this.initializeViewportDetection()),void 0!==t.distance&&"distance"===this.type&&(this.scrollDistance=0,this.isTriggered=!1),e.debug("ScrollTrigger config updated",{widgetId:this.widgetId,oldConfig:i,newConfig:this.config})}reset(){this.isDestroyed||(this.scrollDistance=0,this.isTriggered=!1,this.lastScrollY=window.scrollY,e.debug("ScrollTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{type:this.type,isInViewport:this.isInViewport,scrollDistance:this.scrollDistance,isTriggered:this.isTriggered,currentScrollY:window.scrollY})}isActive(){return"viewport"===this.type?!this.isInViewport:("distance"===this.type||"percent"===this.type)&&this.isTriggered}forceActivate(){"viewport"===this.type?this.triggerActivated("scroll-out-of-view",{manual:!0}):"distance"===this.type&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{manual:!0}))}forceDeactivate(){"viewport"===this.type&&this.triggerDeactivated("scroll-back-in-view",{manual:!0})}destroy(){this.isDestroyed||(this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.scrollListener&&(window.removeEventListener("scroll",this.scrollListener),this.scrollListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.isDestroyed=!0,e.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class Bi{constructor(e){this.mouseLeaveListener=null,this.lastMouseY=0,this.isTriggered=!1,this.scrollUpListener=null,this.visibilityChangeListener=null,this.backButtonListener=null,this.touchStartListener=null,this.touchEndListener=null,this.lastScrollY=0,this.scrollUpDistance=0,this.touchStartY=0,this.touchStartTime=0,this.isScrollingUp=!1,this.debounceTimer=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,desktopTriggers:0,mobileTriggers:0,backButtonTriggers:0,scrollUpTriggers:0,tabSwitchTriggers:0},this.widgetId=e.widgetId,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}}}initialize(){var t,i;this.config.enabled&&(e.debug("Initializing ExitIntentTrigger",{widgetId:this.widgetId,config:this.config}),this.lastScrollY=window.scrollY,(null===(t=this.config.desktop)||void 0===t?void 0:t.enabled)&&this.isDesktop()&&this.initializeDesktopTriggers(),(null===(i=this.config.mobile)||void 0===i?void 0:i.enabled)&&this.isMobile()&&this.initializeMobileTriggers())}isDesktop(){return!("ontouchstart"in window)&&!navigator.maxTouchPoints}isMobile(){return"ontouchstart"in window||navigator.maxTouchPoints>0}initializeDesktopTriggers(){var t,i;this.mouseLeaveListener=this.debounce(this.handleMouseLeave.bind(this),(null===(t=this.config.desktop)||void 0===t?void 0:t.delay)||100),this.mouseLeaveListener&&(document.addEventListener("mouseleave",this.mouseLeaveListener),document.addEventListener("mouseout",this.mouseLeaveListener)),e.debug("Desktop exit intent triggers initialized",{widgetId:this.widgetId,sensitivity:null===(i=this.config.desktop)||void 0===i?void 0:i.sensitivity})}initializeMobileTriggers(){const t=this.config.mobile;t.backButton&&(this.backButtonListener=this.handleBackButton.bind(this),window.addEventListener("popstate",this.backButtonListener),history.pushState({widgeticExitIntent:!0},"",window.location.href)),t.scrollUp&&(this.scrollUpListener=this.debounce(this.handleScrollUp.bind(this),50),this.scrollUpListener&&window.addEventListener("scroll",this.scrollUpListener,{passive:!0}),this.touchStartListener=this.handleTouchStart.bind(this),this.touchEndListener=this.handleTouchEnd.bind(this),document.addEventListener("touchstart",this.touchStartListener,{passive:!0}),document.addEventListener("touchend",this.touchEndListener,{passive:!0})),t.tabSwitch&&(this.visibilityChangeListener=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeListener)),e.debug("Mobile exit intent triggers initialized",{widgetId:this.widgetId,backButton:t.backButton,scrollUp:t.scrollUp,tabSwitch:t.tabSwitch})}handleMouseLeave(e){var t;if(this.isDestroyed||this.isTriggered)return;const i=(null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity)||10;e.clientY<=i&&null===e.relatedTarget&&(this.isTriggered=!0,this.stats.desktopTriggers++,this.triggerActivated("exit-intent",{source:"desktop",method:"mouse-leave",mouseY:e.clientY,sensitivity:i}))}handleBackButton(e){var t;this.isDestroyed||(null===(t=e.state)||void 0===t?void 0:t.widgeticExitIntent)&&(this.stats.backButtonTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"back-button"}),history.pushState({widgeticExitIntent:!0},"",window.location.href))}handleScrollUp(){var e;if(this.isDestroyed)return;const t=window.scrollY,i=t-this.lastScrollY;if(i<0){this.scrollUpDistance+=Math.abs(i),this.isScrollingUp=!0;const n=(null===(e=this.config.mobile)||void 0===e?void 0:e.sensitivity)||50;this.scrollUpDistance>=n&&t<=100&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"scroll-up",scrollUpDistance:this.scrollUpDistance,currentScrollY:t,sensitivity:n}),this.scrollUpDistance=0)}else this.scrollUpDistance=0,this.isScrollingUp=!1;this.lastScrollY=t}handleTouchStart(e){if(this.isDestroyed||1!==e.touches.length)return;const t=e.touches[0];this.touchStartY=t.clientY,this.touchStartTime=Date.now()}handleTouchEnd(e){if(this.isDestroyed||1!==e.changedTouches.length)return;const t=e.changedTouches[0].clientY,i=Date.now()-this.touchStartTime,n=t-this.touchStartY;n>100&&i<300&&window.scrollY<=50&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"swipe-up",swipeDistance:n,touchDuration:i,scrollY:window.scrollY}))}handleVisibilityChange(){this.isDestroyed||document.hidden&&(this.stats.tabSwitchTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"tab-switch",visibilityState:document.visibilityState}))}triggerActivated(t,i){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const n=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:t,triggerData:i}});document.dispatchEvent(n),e.debug("Exit intent trigger activated",{widgetId:this.widgetId,triggerType:t,triggerData:i})}debounce(e,t){return(...i)=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e.apply(this,i)}),t)}}updateConfig(t){var i,n;if(this.isDestroyed)return;const o=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),t),void 0===t.enabled&&void 0===(null===(i=t.desktop)||void 0===i?void 0:i.enabled)&&void 0===(null===(n=t.mobile)||void 0===n?void 0:n.enabled)||(this.destroy(),this.isDestroyed=!1,this.initialize()),e.debug("ExitIntentTrigger config updated",{widgetId:this.widgetId,oldConfig:o,newConfig:this.config})}reset(){this.isDestroyed||(this.isTriggered=!1,this.scrollUpDistance=0,this.isScrollingUp=!1,this.lastScrollY=window.scrollY,e.debug("ExitIntentTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{isTriggered:this.isTriggered,scrollUpDistance:this.scrollUpDistance,isScrollingUp:this.isScrollingUp,currentScrollY:window.scrollY,isDesktop:this.isDesktop(),isMobile:this.isMobile()})}isActive(){return this.isTriggered}forceActivate(e="desktop"){this.triggerActivated("exit-intent",{source:e,method:"manual",manual:!0})}destroy(){this.isDestroyed||(this.mouseLeaveListener&&(document.removeEventListener("mouseleave",this.mouseLeaveListener),document.removeEventListener("mouseout",this.mouseLeaveListener),this.mouseLeaveListener=null),this.backButtonListener&&(window.removeEventListener("popstate",this.backButtonListener),this.backButtonListener=null),this.scrollUpListener&&(window.removeEventListener("scroll",this.scrollUpListener),this.scrollUpListener=null),this.visibilityChangeListener&&(document.removeEventListener("visibilitychange",this.visibilityChangeListener),this.visibilityChangeListener=null),this.touchStartListener&&(document.removeEventListener("touchstart",this.touchStartListener),this.touchStartListener=null),this.touchEndListener&&(document.removeEventListener("touchend",this.touchEndListener),this.touchEndListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.isDestroyed=!0,e.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const Ni={"top-left":["top","left"],"top-center":["top","center"],"top-right":["top","right"],"center-left":["center","left"],center:["center","center"],"center-center":["center","center"],"center-right":["center","right"],"bottom-left":["bottom","left"],"bottom-center":["bottom","center"],"bottom-right":["bottom","right"]};class $i{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return $i.instance||($i.instance=new $i),$i.instance}canShowOverlay(t,i){if(!(null==i?void 0:i.enabled))return!0;const n=this.getViewHistory(t,i),o=Date.now(),s=60*i.timePeriodHours*60*1e3,r=n.filter((e=>o-e.timestamp<=s)),a=r.length<i.maxViews;return e.debug(`[RecurrenceManager] Recurrence check for ${t}`,{maxViews:i.maxViews,timePeriodHours:i.timePeriodHours,recentViews:r.length,canShow:a}),a}recordView(t,i){if(!(null==i?void 0:i.enabled))return;const n={timestamp:Date.now(),widgetId:t},o=this.getViewHistory(t,i);o.push(n);const s=60*i.timePeriodHours*60*1e3,r=Date.now(),a=o.filter((e=>r-e.timestamp<=s));this.saveViewHistory(t,i,a),e.debug(`[RecurrenceManager] Recorded view for ${t}`,{totalViews:a.length,timePeriodHours:i.timePeriodHours})}getViewHistory(t,i){if(!this.isLocalStorageAvailable())return[];try{const e=this.getStorageKey(t,i),n=localStorage.getItem(e);if(!n)return[];const o=JSON.parse(n);return o.version!==this.storageVersion?[]:Array.isArray(o.views)?o.views:[]}catch(i){return e.warn(`[RecurrenceManager] Failed to load view history for ${t}`,{error:i}),[]}}saveViewHistory(t,i,n){if(this.isLocalStorageAvailable())try{const e=this.getStorageKey(t,i),o={version:this.storageVersion,widgetId:t,views:n,lastUpdated:Date.now()};localStorage.setItem(e,JSON.stringify(o))}catch(i){e.warn(`[RecurrenceManager] Failed to save view history for ${t}`,{error:i})}}getStorageKey(e,t){const i=(null==t?void 0:t.storageKeySuffix)?`-${t.storageKeySuffix}`:"";return`${this.storageKey}-${e}${i}`}isLocalStorageAvailable(){try{const e="__localStorage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}getStats(e,t){if(!(null==t?void 0:t.enabled))return null;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o));return{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,remainingViews:Math.max(0,t.maxViews-s.length),canShow:s.length<t.maxViews,lastView:s.length>0?s[s.length-1].timestamp:null,viewHistory:s.map((e=>e.timestamp))}}clearHistory(t,i){if(!(null==i?void 0:i.enabled)||!this.isLocalStorageAvailable())return;const n=this.getStorageKey(t,i);localStorage.removeItem(n),e.debug(`[RecurrenceManager] Cleared view history for ${t}`)}cleanup(){if(!this.isLocalStorageAvailable())return;const t=[];for(let e=0;e<localStorage.length;e++){const i=localStorage.key(e);if(null==i?void 0:i.startsWith(this.storageKey))try{const e=JSON.parse(localStorage.getItem(i)||"{}"),n=Date.now()-864e5;e.lastUpdated<n&&t.push(i)}catch(e){t.push(i)}}t.forEach((e=>localStorage.removeItem(e))),t.length>0&&e.debug(`[RecurrenceManager] Cleaned up ${t.length} old view records`)}}class Fi{constructor(e){var t;this.scrollTrigger=null,this.exitIntentTrigger=null,this.portal=null,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,this.placeholder=null,this.isInOverlay=!1,this.isDestroyed=!1,this.triggerInstances=new Map,this.keydownListener=null,this.recurrenceManager=$i.getInstance(),this.delayTimer=null,this.domReadyListener=null,this.fullWidthRestore=null,this.pageLoadTimeMs=Date.now(),this.showRulesGateOpen=!0,this.showRulesPollTimer=null,this.lastShowRulesEvaluation=null,this.overlayTriggersArmed=!1,this.onTriggerActivated=e=>this.handleTriggerActivated(e),this.onTriggerDeactivated=e=>this.handleTriggerDeactivated(e),this.onOverlayClose=e=>this.handleOverlayClose(e),this.widgetId=e.widgetId,this.element=e.element,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.mode=this.config.mode||"site",this.displayWhenShown=null!==(t=e.displayWhenShown)&&void 0!==t?t:"",this.originalParent=this.element.parentElement,this.originalNextSibling=this.element.nextSibling,this.initialize()}getDefaultConfig(){return{mode:"site",scroll:{enabled:!0,threshold:.1,distance:100,direction:"down"},exitIntent:{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}},overlay:{position:"bottom-right",offset:{x:20,y:20},className:"",style:"",closeButton:!0,backdrop:!1,animation:"slide",background:{enabled:!0,color:"#000",opacity:.5}},recurrence:{enabled:!1,maxViews:1,timePeriodHours:24}}}initialize(){switch(e.debug("Initializing TriggerManager",{widgetId:this.widgetId,mode:this.mode,config:this.config}),this.mode){case"site":break;case"mixed":this.initializeScrollTrigger("viewport");break;case"overlay":this.hideWidget(),this.armOverlayEventTrigger()}this.bindEvents(),this.startShowRulesPolling()}passesShowRules(){var t;const i=G(this.config.showRules,{widgetId:this.widgetId,storageKeySuffix:null===(t=this.config.recurrence)||void 0===t?void 0:t.storageKeySuffix},this.pageLoadTimeMs);return this.lastShowRulesEvaluation=i,this.showRulesGateOpen=i.allowed,i.allowed||e.debug("Show rules blocked overlay",{widgetId:this.widgetId,reason:i.reason}),i.allowed}startShowRulesPolling(){var e;(null===(e=this.config.showRules)||void 0===e?void 0:e.minTimeOnPageSeconds)&&null===this.showRulesPollTimer&&(this.showRulesPollTimer=setInterval((()=>{if(this.isDestroyed||this.isInOverlay)return;const e=this.showRulesGateOpen,t=this.passesShowRules();!e&&t&&"overlay"===this.mode&&this.armOverlayEventTrigger()}),1e3))}armOverlayEventTrigger(){if(!this.overlayTriggersArmed&&this.passesShowRules()){switch(this.config.eventTrigger){case"pageLoad":this.showOnLoad();break;case"delay":this.showAfterDelay();break;case"scroll":this.initializeScrollTrigger("distance");break;case"scrollPercent":{const e="number"==typeof this.config.scrollPercent&&Number.isFinite(this.config.scrollPercent)?Math.min(100,Math.max(0,this.config.scrollPercent)):Q;this.initializeScrollTrigger("percent",e);break}case"timesShown":if(!this.armTimesShownTrigger())return;break;case"manual":e.debug("Manual trigger armed",{widgetId:this.widgetId});break;default:this.initializeScrollTrigger("distance"),this.initializeExitIntentTrigger()}this.overlayTriggersArmed=!0}}armTimesShownTrigger(){var t;const i="number"==typeof this.config.timesShownPageViews&&this.config.timesShownPageViews>0?this.config.timesShownPageViews:J,n=null===(t=this.config.recurrence)||void 0===t?void 0:t.storageKeySuffix,o=Z(this.widgetId,n);return e.debug("Times-shown page view recorded",{widgetId:this.widgetId,views:o,required:i}),o>=i&&(this.showOnLoad(),!0)}whenDomReady(e){this.isDestroyed||("loading"===document.readyState?(this.domReadyListener=()=>{this.domReadyListener=null,this.isDestroyed||e()},document.addEventListener("DOMContentLoaded",this.domReadyListener,{once:!0})):e())}showOnLoad(){this.whenDomReady((()=>this.showOverlay()))}showAfterDelay(){var t,i;if(!1===(null===(t=this.config.delay)||void 0===t?void 0:t.enabled))return;const n=null===(i=this.config.delay)||void 0===i?void 0:i.delayMs,o="number"==typeof n&&Number.isFinite(n)&&n>=0?n:X;this.whenDomReady((()=>{null===this.delayTimer&&(this.delayTimer=setTimeout((()=>{this.delayTimer=null,this.showOverlay()}),o),e.debug("Delay trigger armed",{widgetId:this.widgetId,delayMs:o}))}))}initializeScrollTrigger(e,t){var i;if(!(null===(i=this.config.scroll)||void 0===i?void 0:i.enabled)&&"percent"!==e)return;const n="percent"===e?{enabled:!0,threshold:.1,distance:100,direction:"down",debounce:100}:this.config.scroll;this.scrollTrigger=new ji({widgetId:this.widgetId,element:this.element,type:e,config:null!=n?n:{enabled:!0,threshold:.1,distance:100,direction:"down"}}),"percent"===e&&"number"==typeof t&&this.scrollTrigger.setScrollPercentTarget(t),this.triggerInstances.set("scroll",this.scrollTrigger)}initializeExitIntentTrigger(){var e;(null===(e=this.config.exitIntent)||void 0===e?void 0:e.enabled)&&(this.exitIntentTrigger=new Bi({widgetId:this.widgetId,config:this.config.exitIntent}),this.triggerInstances.set("exitIntent",this.exitIntentTrigger))}bindEvents(){document.addEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.addEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.addEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener=this.handleEscapeKey.bind(this),document.addEventListener("keydown",this.keydownListener)}handleTriggerActivated(t){const i=t;if(i.detail.widgetId!==this.widgetId)return;if("trigger-manager"===i.detail.source)return;const{triggerType:n,triggerData:o}=i.detail;e.debug("Trigger activated",{widgetId:this.widgetId,triggerType:n,triggerData:o}),"mixed"===this.mode&&"scroll-out-of-view"===n?this.showOverlay():"overlay"!==this.mode||"scroll-distance"!==n&&"scroll-percent"!==n&&"exit-intent"!==n||this.showOverlay(),this.dispatchTriggerEvent("activated",n,o)}handleTriggerDeactivated(t){const i=t;if(i.detail.widgetId!==this.widgetId)return;if("trigger-manager"===i.detail.source)return;const{triggerType:n,triggerData:o}=i.detail;e.debug("Trigger deactivated",{widgetId:this.widgetId,triggerType:n,triggerData:o}),"mixed"===this.mode&&"scroll-back-in-view"===n&&this.hideOverlay(),this.dispatchTriggerEvent("deactivated",n,o)}handleOverlayClose(e){var t,i;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===this.widgetId&&(this.hideOverlay(),ee(this.widgetId,null===(i=this.config.recurrence)||void 0===i?void 0:i.storageKeySuffix),"overlay"===this.mode&&this.hideWidget())}handleEscapeKey(e){"Escape"===e.key&&this.isInOverlay&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}showOverlay(){var t,i,n,o,s,r;if(!this.isInOverlay&&!this.isDestroyed)if(this.passesShowRules()){if("overlay"===this.mode&&(null===(t=this.config.recurrence)||void 0===t?void 0:t.enabled)){if(!this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence))return e.debug("Overlay blocked by recurrence limits",{widgetId:this.widgetId,recurrenceConfig:this.config.recurrence}),void this.dispatchEvent("overlay-blocked",{reason:"recurrence-limit",recurrenceStats:this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)})}this.portal||(this.portal=ge({target:"widgetic-trigger-portal",className:(null===(i=this.config.overlay)||void 0===i?void 0:i.className)||"",style:(null===(n=this.config.overlay)||void 0===n?void 0:n.style)||"",zIndex:this.getOverlayZIndex(),clickThrough:!this.hasOverlayBackground()})),this.overlayContainer=this.createOverlayContainer(),this.portal.mount(this.overlayContainer),this.leavePlaceholder(),this.overlayContainer.appendChild(this.element),this.element.style.display=this.displayWhenShown,this.applyFullWidthSizing(),this.isInOverlay=!0,"overlay"===this.mode&&(null===(o=this.config.recurrence)||void 0===o?void 0:o.enabled)&&this.recurrenceManager.recordView(this.widgetId,this.config.recurrence),te(this.widgetId,null===(s=this.config.recurrence)||void 0===s?void 0:s.storageKeySuffix),e.debug("Widget moved to overlay",{widgetId:this.widgetId}),this.dispatchEvent("overlay-shown",{mode:this.mode,position:null===(r=this.config.overlay)||void 0===r?void 0:r.position})}else this.dispatchEvent("overlay-blocked",{reason:"show-rules",showRules:this.lastShowRulesEvaluation})}leavePlaceholder(){var e;if("mixed"!==this.mode||this.placeholder)return;const t=this.element.parentNode;if(!t)return;const{width:i,height:n}=this.element.getBoundingClientRect(),o=document.createElement("div");o.setAttribute("data-widgetic-placeholder",this.widgetId),o.setAttribute("aria-hidden","true"),o.style.cssText=`display:block;visibility:hidden;pointer-events:none;width:${i}px;height:${n}px;`,t.insertBefore(o,this.element),this.placeholder=o,null===(e=this.scrollTrigger)||void 0===e||e.observeElement(o)}returnToPlaceholder(){const e=this.placeholder;return!!e&&(this.placeholder=null,!!e.parentNode&&(e.parentNode.replaceChild(this.element,e),!0))}hideOverlay(){var t;this.isInOverlay&&!this.isDestroyed&&(this.restoreFullWidthSizing(),!this.returnToPlaceholder()&&this.originalParent&&(this.originalNextSibling?this.originalParent.insertBefore(this.element,this.originalNextSibling):this.originalParent.appendChild(this.element)),"mixed"===this.mode&&(null===(t=this.scrollTrigger)||void 0===t||t.observeElement(this.element)),this.portal&&this.portal.unmount(),this.overlayContainer=null,this.isInOverlay=!1,e.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,o;const s=document.createElement("div");s.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),l=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),c=this.getOverlayStyles(r,a,this.getOverlayZIndex(),l);if(s.style.cssText=c,d&&this.applyBackgroundStyling(s),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,l);s.appendChild(e)}return(null===(o=this.config.overlay)||void 0===o?void 0:o.animation)&&s.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(s),s}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,o=(null==n?void 0:n.color)||"#000000",s=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${o};\n opacity: ${s};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?ie:Math.min(Math.floor(t),ne)}getOverlayStyles(e,t,i,n){const[o,s]=Ni[e]||Ni["bottom-right"];let r=`\n position: fixed;\n z-index: ${i};\n pointer-events: auto;\n max-height: 90vh;\n `;return n?r+="left: 0; right: 0; width: 100%; max-width: 100vw;":(r+="max-width: 90vw;",r+="left"===s?`left: ${t.x}px;`:"right"===s?`right: ${t.x}px;`:"left: 0; right: 0; margin-left: auto; margin-right: auto; width: -moz-fit-content; width: fit-content;"),r+="top"===o?`top: ${n?0:t.y}px;`:"bottom"===o?`bottom: ${n?0:t.y}px;`:"top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; height: -moz-fit-content; height: fit-content;",r}applyFullWidthSizing(){var e;if(!(null===(e=this.config.overlay)||void 0===e?void 0:e.fullWidth)||this.fullWidthRestore)return;const t=Array.from(this.element.querySelectorAll("iframe"));this.fullWidthRestore={elementWidth:this.element.style.width,iframes:t.map((e=>({iframe:e,width:e.style.width})))},this.element.style.width="100%",t.forEach((e=>{e.style.width="100%"}))}restoreFullWidthSizing(){this.fullWidthRestore&&(this.element.style.width=this.fullWidthRestore.elementWidth,this.fullWidthRestore.iframes.forEach((({iframe:e,width:t})=>{e.style.width=t})),this.fullWidthRestore=null)}createCloseButton(e,t=!1){const i=document.createElement("button");i.className="widgetic-trigger-overlay-close",i.setAttribute("aria-label",A("closeOverlay")),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const o=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=o+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(t){this.isDestroyed||(this.config=Object.assign(Object.assign({},this.config),t),this.triggerInstances.forEach(((e,t)=>{"scroll"===t&&this.config.scroll?e.updateConfig(this.config.scroll):"exitIntent"===t&&this.config.exitIntent&&e.updateConfig(this.config.exitIntent)})),e.debug("TriggerManager config updated",{widgetId:this.widgetId,config:this.config}))}getStats(){var e;const t={widgetId:this.widgetId,mode:this.mode,isInOverlay:this.isInOverlay,isDestroyed:this.isDestroyed,triggerInstances:Array.from(this.triggerInstances.keys())};return this.triggerInstances.forEach(((e,i)=>{"function"==typeof e.getStats&&(t[`${i}Stats`]=e.getStats())})),(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(t.recurrenceStats=this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)),t}forceShowOverlay(){this.showOverlay()}showFromManualApi(){this.mode,this.showOverlay()}forceHideOverlay(){this.hideOverlay()}getRecurrenceStats(){var e;return(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)?this.recurrenceManager.getStats(this.widgetId,this.config.recurrence):null}clearRecurrenceHistory(){var t;(null===(t=this.config.recurrence)||void 0===t?void 0:t.enabled)&&(this.recurrenceManager.clearHistory(this.widgetId,this.config.recurrence),e.debug("Recurrence history cleared",{widgetId:this.widgetId}))}canShowOverlay(){var e;return"overlay"!==this.mode||!(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)||this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence)}destroy(){this.isDestroyed||(null!==this.showRulesPollTimer&&(clearInterval(this.showRulesPollTimer),this.showRulesPollTimer=null),null!==this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.domReadyListener&&(document.removeEventListener("DOMContentLoaded",this.domReadyListener),this.domReadyListener=null),this.isInOverlay&&this.hideOverlay(),this.placeholder&&(this.placeholder.remove(),this.placeholder=null),this.triggerInstances.forEach((e=>{"function"==typeof e.destroy&&e.destroy()})),this.triggerInstances.clear(),this.portal&&(this.portal.destroy(),this.portal=null),document.removeEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.removeEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.removeEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.recurrenceManager.cleanup(),this.isDestroyed=!0,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,e.debug("TriggerManager destroyed",{widgetId:this.widgetId}))}applyOverlayWidgetStyling(e){var t;if(!("mixed"===this.mode))return;if(!1!==(null===(t=this.config.overlay)||void 0===t?void 0:t.keepDimensions))return;const i=this.config.overlay;if(i){if(i.overlayWidth){const t="number"==typeof i.overlayWidth?`${i.overlayWidth}px`:i.overlayWidth;e.style.width=t,e.style.maxWidth=t}if(i.overlayHeight){const t="number"==typeof i.overlayHeight?`${i.overlayHeight}px`:i.overlayHeight;e.style.height=t,e.style.maxHeight=t}i.overlayResize&&this.applyOverlayResizeMode(e,i.overlayResize)}}applyOverlayResizeMode(e,t){switch(t){case"fill-width":e.style.width="90vw",e.style.height="auto",e.style.maxWidth="90vw";break;case"fill-height":e.style.height="90vh",e.style.width="auto",e.style.maxHeight="90vh";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="90vw",e.style.maxWidth="90vw";break;case"fixed-width":e.style.height="90vh",e.style.maxHeight="90vh";break;case"allow-scale-down":e.style.maxWidth="90vw",e.style.maxHeight="90vh";break;case"fill":e.style.width="90vw",e.style.height="90vh",e.style.maxWidth="90vw",e.style.maxHeight="90vh"}}}var _i=Object.freeze({__proto__:null,TriggerManager:Fi});function Vi(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=Math.floor(16*Math.random());return("x"===e?t:3&t|8).toString(16)}))}function Ki(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function qi(e){return P(this,void 0,void 0,(function*(){try{const t=yield e.json();return Ki(t)?function(e){const t=e.data;return Ki(t)?t:e}(t):{}}catch(e){return{}}}))}class Yi{constructor(t={}){var n,o;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},t),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},t.security)}),this.apiConfig=new i(Object.assign(Object.assign({basePath:this.config.apiBaseUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:3000")},this.config.apiKey&&{apiKey:this.config.apiKey}),this.config.accessToken&&{accessToken:this.config.accessToken})),this.widgetsApi=new r(this.apiConfig),this.compositionsApi=new s(this.apiConfig),this.securityManager=Me.getInstance(this.config.security||{}),this.displayManager=new fe,this.performanceMonitor=be(),this.setupResponsiveTracking(),this.setupEventListeners(),e.info("[WidgetManager] Initialized with config:",{securityEnabled:!!(null===(n=t.security)||void 0===n?void 0:n.enableSanitization),performanceEnabled:!!(null===(o=t.performance)||void 0===o?void 0:o.enabled)})}static getInstance(e){return Yi.instance||(Yi.instance=new Yi(e)),Yi.instance}initialize(){return P(this,void 0,void 0,(function*(){if(this.isInitialized)e.warn("[WidgetManager] Already initialized");else try{this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),e.info("[WidgetManager] Successfully initialized")}catch(t){throw e.error("[WidgetManager] Initialization failed:",t),this.emitError({code:"INIT_FAILED",message:"Widget manager initialization failed",widgetId:"system",timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}}),t}}))}registerWidget(t,i,n){return P(this,void 0,void 0,(function*(){try{const o=yield this.validateWidgetConfig(i);if(!o.allowed)throw new Error(`Widget validation failed: ${o.reason}`);const s={id:t,config:i,element:n,state:{ready:!1,error:null,width:i.width,height:i.height},displayState:{mode:i.displayMode,isFullscreen:!1,isOverlay:!1,isPopup:!1},updateHandlers:new Map,lastUpdate:Date.now()},r=this.displayManager.initializeWidget(t,i,n);if(s.displayState=r,i.triggers)try{const o=new Fi({widgetId:t,element:n,config:i.triggers});this.triggerManagers.set(t,o),e.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:t,triggers:i.triggers})}catch(i){e.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}return i.compositionId&&this.trackWidgetForComposition(i.compositionId,t),this.widgets.set(t,s),this.widgetConfigs.set(t,i),s.state.ready=!0,e.info("[WidgetManager] Widget registered:",{widgetId:t,compositionId:i.compositionId}),this.emitEvent({type:"widget_registered",widgetId:t,data:{config:i},timestamp:Date.now()}),s}catch(i){throw e.error("[WidgetManager] Widget registration failed:",i),this.emitError({code:"REGISTRATION_FAILED",message:"Widget registration failed",widgetId:t,timestamp:Date.now(),details:{error:i instanceof Error?i.message:"Unknown error"}}),i}}))}trackWidgetForComposition(e,t){this.compositionWidgets.has(e)||this.compositionWidgets.set(e,new Set),this.compositionWidgets.get(e).add(t)}applyContentToWidget(t,i){return P(this,void 0,void 0,(function*(){try{if("string"==typeof i)if("iframe"===t.element.tagName.toLowerCase()){const e=t.element;e.contentWindow&&e.contentWindow.postMessage({type:"widgetic_content_update",content:i},d.CLIENT_URL||"*")}else{const e=yield this.sanitizeContent(i,t.id);t.element.innerHTML=e}else if("object"==typeof i)if("iframe"===t.element.tagName.toLowerCase()){const e=t.element;e.contentWindow&&e.contentWindow.postMessage({type:"widgetic_data_update",data:i},d.CLIENT_URL||"*")}else t.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:i}));e.debug("[WidgetManager] Content applied to widget:",{widgetId:t.id,contentType:typeof i})}catch(t){throw e.error("[WidgetManager] Failed to apply content:",t),t}}))}sanitizeContent(e,t){return P(this,void 0,void 0,(function*(){const i=this.securityManager.validateTextFieldUpdate(t,"content",e);if(!i.allowed)throw new Error(`Content blocked by security: ${i.reason}`);return i.sanitizedText||e}))}validateWidgetConfig(e){return P(this,void 0,void 0,(function*(){var t;if(!e.compositionId)return{allowed:!1,reason:"Missing composition ID",severity:"high"};if(null===(t=this.config.security)||void 0===t?void 0:t.enableSanitization){const t=JSON.stringify(e),i=this.securityManager.validateTextFieldUpdate(e.compositionId,"config",t);if(!i.allowed)return{allowed:!1,reason:i.reason,severity:i.severity||"medium"}}return{allowed:!0}}))}setContent(t,i){return P(this,arguments,void 0,(function*(t,i,n={}){try{e.debug("[WidgetManager] Setting dynamic content:",{compositionId:t,contentType:typeof i,options:n});const o={content:i};void 0!==n.validate&&(o.validate=n.validate),void 0!==n.partial&&(o.partial=n.partial),void 0!==n.version&&(o.version=n.version),void 0!==n.source&&(o.source=n.source);const s=yield this.compositionsApi.setDynamicContentRaw({id:t,setDynamicContentRequest:o,idempotencyKey:Vi()}),r=yield qi(s.raw),a=this.getWidgetsByComposition(t),d=this.compositionData.get(t);let l=i;n.partial&&(null==d?void 0:d.content)&&(l=this.mergeContent(d.content,i));const c={id:t,widgetId:t,content:l,theme:(null==d?void 0:d.theme)||{},version:n.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(t,c);const h=a.map((i=>P(this,void 0,void 0,(function*(){var o;try{yield this.applyContentToWidget(i,l);const s=null===(o=i.updateHandlers)||void 0===o?void 0:o.get("content");s&&(yield s(l)),i.lastUpdate=Date.now(),e.debug("[WidgetManager] Content applied to widget:",{widgetId:i.id,compositionId:t,source:n.source})}catch(t){throw e.error("[WidgetManager] Failed to update widget content:",{widgetId:i.id,error:t instanceof Error?t.message:"Unknown error"}),t}}))));return yield Promise.all(h),this.emitEvent({type:"content_updated",widgetId:t,data:{content:l,source:n.source,version:n.version,partial:n.partial},timestamp:Date.now()}),e.info("[WidgetManager] Content updated successfully via API:",{compositionId:t,widgetCount:a.length,source:n.source,realtimeUpdateSent:r.realtimeUpdateSent}),{success:!0===r.success,validationResult:r.validationResult}}catch(e){const i=e instanceof Error?e.message:"Unknown error";return this.emitError({code:"CONTENT_UPDATE_FAILED",message:`Failed to set content: ${i}`,widgetId:t,timestamp:Date.now(),details:{error:i,options:n}}),{success:!1,error:i}}}))}getContentSchema(t){return P(this,void 0,void 0,(function*(){try{e.debug("[WidgetManager] Getting widget content schema:",{widgetId:t});const i=yield this.widgetsApi.getWidgetContentSchema({id:t});return e.debug("[WidgetManager] Content schema retrieved:",{widgetId:t,schema:i}),i}catch(i){throw e.error("[WidgetManager] Failed to get content schema:",i),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get content schema: ${i instanceof Error?i.message:"Unknown error"}`,widgetId:t,timestamp:Date.now()}),i}}))}getDesignSchema(t){return P(this,void 0,void 0,(function*(){try{e.debug("[WidgetManager] Getting widget design schema:",{widgetId:t});const i=yield this.widgetsApi.getWidgetDesignSchema({id:t});return e.debug("[WidgetManager] Design schema retrieved:",{widgetId:t,schema:i}),i}catch(i){throw e.error("[WidgetManager] Failed to get design schema:",i),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get design schema: ${i instanceof Error?i.message:"Unknown error"}`,widgetId:t,timestamp:Date.now()}),i}}))}validateContent(t,i){return P(this,void 0,void 0,(function*(){try{e.debug("[WidgetManager] Validating content:",{compositionId:t});const n=yield this.compositionsApi.validateCompositionContentRaw({id:t,requestBody:i,idempotencyKey:Vi()}),o=yield qi(n.raw),s=!0===o.valid;return e.debug("[WidgetManager] Content validation completed:",{compositionId:t,valid:s}),{valid:s,errors:Array.isArray(o.errors)?o.errors:void 0,warnings:Array.isArray(o.warnings)?o.warnings:void 0,sanitizedContent:o.sanitizedContent}}catch(t){throw e.error("[WidgetManager] Content validation failed:",t),t}}))}getContent(e){const t=this.compositionData.get(e);return(null==t?void 0:t.content)||null}mergeContent(e,t){if(!e||"object"!=typeof e)return t;if(!t||"object"!=typeof t)return e;const i=Object.assign({},e);for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&!Array.isArray(n)?i[e]=this.mergeContent(i[e],n):i[e]=n;return i}registerUpdateHandler(t,i,n){const o=this.widgets.get(t);if(!o)throw new Error(`Widget not found: ${t}`);o.updateHandlers||(o.updateHandlers=new Map),o.updateHandlers.set(i,n),e.info("[WidgetManager] Update handler registered:",{widgetId:t,updateType:i})}unregisterWidget(t){return P(this,void 0,void 0,(function*(){var i;const n=this.widgets.get(t);if(n)try{const o=n.config.compositionId;o&&this.compositionWidgets.has(o)&&(this.compositionWidgets.get(o).delete(t),0===this.compositionWidgets.get(o).size&&this.compositionWidgets.delete(o));try{this.displayManager.cleanup(t),e.debug("[WidgetManager] Display management cleaned up:",{widgetId:t})}catch(i){e.warn("[WidgetManager] Failed to cleanup display management:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}const s=this.triggerManagers.get(t);if(s)try{s.destroy(),this.triggerManagers.delete(t),e.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:t})}catch(i){e.warn("[WidgetManager] Failed to cleanup trigger manager:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}this.widgets.delete(t),this.widgetConfigs.delete(t),e.info("[WidgetManager] Widget unregistered:",{widgetId:t,compositionId:o,remainingWidgetsForComposition:(null===(i=this.compositionWidgets.get(o||""))||void 0===i?void 0:i.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:t,data:{compositionId:o},timestamp:Date.now()})}catch(i){e.error("[WidgetManager] Widget unregistration failed:",i),this.emitError({code:"UNREGISTRATION_FAILED",message:"Widget unregistration failed",widgetId:t,timestamp:Date.now(),details:{error:i instanceof Error?i.message:"Unknown error"}})}else e.warn("[WidgetManager] Widget not found for unregistration:",t)}))}getWidget(e){return this.widgets.get(e)}getAllWidgets(){return Array.from(this.widgets.values())}getWidgetsByComposition(e){const t=this.compositionWidgets.get(e);return t?Array.from(t).map((e=>this.widgets.get(e))).filter((e=>void 0!==e)):[]}setupResponsiveTracking(){if("undefined"==typeof window)return;const e=()=>{const e={mode:"mobile"===xe().getDeviceType()?"mobile":"desktop",breakpoint:768,width:window.innerWidth,timestamp:Date.now()};this.responsiveState&&this.responsiveState.mode===e.mode||(this.responsiveState=e,this.emitEvent({type:"responsive_change",widgetId:"system",data:e,timestamp:Date.now()}),this.handleResponsiveChange(e))};let t;e(),window.addEventListener("resize",(()=>{clearTimeout(t),t=setTimeout(e,250)}))}handleResponsiveChange(t){for(const i of this.widgets.values())try{const n=this.widgetConfigs.get(i.id);if(n&&i.displayState){this.displayManager.cleanup(i.id);const o=this.displayManager.initializeWidget(i.id,n,i.element);i.displayState=o,e.debug("[WidgetManager] Responsive update applied:",{widgetId:i.id,mode:t.mode,width:t.width})}this.emitEvent({type:"widget_responsive_change",widgetId:i.id,data:t,timestamp:Date.now()})}catch(t){e.error("[WidgetManager] Responsive change handling failed for widget:",{widgetId:i.id,error:t})}}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}addErrorHandler(e){this.errorHandlers.add(e)}removeErrorHandler(e){this.errorHandlers.delete(e)}emitEvent(t){const i=this.eventListeners.get(t.type);i&&i.forEach((i=>{try{i(t)}catch(t){e.error("[WidgetManager] Event handler failed:",t)}}))}emitError(t){this.errorHandlers.forEach((i=>{try{i(t)}catch(t){e.error("[WidgetManager] Error handler failed:",t)}}))}setupEventListeners(){"undefined"!=typeof window&&document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})}))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return P(this,void 0,void 0,(function*(){e.info("[WidgetManager] Destroying widget manager");const t=Array.from(this.widgets.keys());yield Promise.allSettled(t.map((e=>this.unregisterWidget(e))));for(const[t,i]of this.triggerManagers)try{i.destroy(),e.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:t})}catch(i){e.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:t,error:i instanceof Error?i.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),e.debug("[WidgetManager] Display manager cleaned up")}catch(t){e.warn("[WidgetManager] Failed to cleanup display manager:",{error:t instanceof Error?t.message:"Unknown error"})}this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,Yi.instance=null,e.info("[WidgetManager] Widget manager destroyed")}))}getActiveCompositions(){return Array.from(this.compositionWidgets.keys()).filter((e=>this.compositionWidgets.get(e).size>0))}getCompositionData(e){return this.compositionData.get(e)}}function Gi(e){return Yi.getInstance(e)}Yi.instance=null;var Qi=Object.freeze({__proto__:null,WidgetManager:Yi,getWidgetManager:Gi});let Ji=!1;class Zi{constructor(t={}){var i,o,s,r,a,d,g,u,m,p,f,v,w,y,b,I,S,E,T,C,M;this.version=n,this.instances=new Map,this.isInitialized=!1,this.renderer=D(),this.widgetControllers=new Map,this.authDetector=ue(),this.editorOverlay=me(),this.displayManager=ve(),this.resizeHandler=we(),this.authenticationStatus=null,this.overlayManager=null,this.hostObserverStarted=!1,this.config=Object.assign({renderMode:"auto",performance:{enabled:!1,config:{}},lazyLoading:{enabled:!0,config:{}}},t),this.browserCapabilities=oe(),this.messenger=ce(this.config.messagingOptions);const W=this.config.logLevel||(this.config.debug?"debug":"info");if(e.setLevel(W),h.enabled&&e.info("Initializing EmbedSDK",{version:n,config:this.config,browserCapabilities:this.browserCapabilities}),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(i=this.config.performance)||void 0===i?void 0:i.enabled)){const e=Object.assign({enableTracking:l.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:l.AXIOM_API_KEY,axiomDataset:l.AXIOM_DATASET,axiomApiEndpoint:l.AXIOM_API_ENDPOINT,statsigKey:l.STATSIG_API_KEY,statsigApiEndpoint:l.STATSIG_API_ENDPOINT},null===(o=this.config.performance)||void 0===o?void 0:o.config);Ie(e)}!1!==(null===(s=this.config.lazyLoading)||void 0===s?void 0:s.enabled)&&Se((null===(r=this.config.lazyLoading)||void 0===r?void 0:r.config)||{}),void 0!==this.config.debug&&(c.setDebug(this.config.debug),this.config.debug&&c.setLevel("debug")),!1!==(null===(a=this.config.resourceOptimization)||void 0===a?void 0:a.enabled)&&Ee((null===(d=this.config.resourceOptimization)||void 0===d?void 0:d.config)||{}),this.config.editorOptions&&(this.editorOverlay=me(this.config.editorOptions)),!1!==(null===(g=this.config.overlayConfig)||void 0===g?void 0:g.enabled)&&(this.overlayManager=ye({enabled:!0,defaultMode:null===(u=this.config.overlayConfig)||void 0===u?void 0:u.defaultMode,exitIntentEnabled:null===(m=this.config.overlayConfig)||void 0===m?void 0:m.exitIntentEnabled,scrollTriggerEnabled:null===(p=this.config.overlayConfig)||void 0===p?void 0:p.scrollTriggerEnabled,timeTriggerEnabled:null===(f=this.config.overlayConfig)||void 0===f?void 0:f.timeTriggerEnabled,engagementThresholdEnabled:null===(v=this.config.overlayConfig)||void 0===v?void 0:v.engagementThresholdEnabled,externalTriggerEnabled:null===(w=this.config.overlayConfig)||void 0===w?void 0:w.externalTriggerEnabled,breakpoints:{useBreakpoints:(null===(b=null===(y=this.config.overlayConfig)||void 0===y?void 0:y.breakpoints)||void 0===b?void 0:b.useBreakpoints)||!1,mobile:(null===(S=null===(I=this.config.overlayConfig)||void 0===I?void 0:I.breakpoints)||void 0===S?void 0:S.mobile)||480,tablet:(null===(T=null===(E=this.config.overlayConfig)||void 0===E?void 0:E.breakpoints)||void 0===T?void 0:T.tablet)||768,desktop:(null===(M=null===(C=this.config.overlayConfig)||void 0===C?void 0:C.breakpoints)||void 0===M?void 0:M.desktop)||1024}})),e.info("Widgetic Embed SDK v1.0 initialized",{version:n,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&e.info("EmbedSDK initialized in debug mode",{config:this.config})}init(){return P(this,void 0,void 0,(function*(){var t,i;if(this.watchPublishedHosts(),yield this.scanPage(),this.isInitialized)e.warn("SDK already initialized");else if(Ji||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)e.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,Ji=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((t=>{e.warn("Background authentication check failed",{error:t})})),this.config.preloadUISDK&&(null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated))try{const t=pe();yield t.preload(),e.info("UI SDK preloaded successfully")}catch(t){e.warn("Failed to preload UI SDK",{error:t})}yield this.scanPage(),e.info("Widgetic Embed SDK initialized successfully",{version:n,capabilities:this.browserCapabilities,authenticationStatus:null===(i=this.authenticationStatus)||void 0===i?void 0:i.isAuthenticated}),yield this.scanPage()}catch(t){throw e.error("SDK initialization failed",{error:t}),t}}))}checkAuthentication(){return P(this,void 0,void 0,(function*(){var t;try{this.authenticationStatus=yield this.authDetector.checkAuthentication(),this.authenticationStatus.isAuthenticated?e.info("User authenticated for editing",{userId:null===(t=this.authenticationStatus.user)||void 0===t?void 0:t.id}):e.debug("User not authenticated for editing")}catch(t){e.debug("Authentication check failed",{error:t}),this.authenticationStatus={isAuthenticated:!1,canEdit:!1}}}))}enhance(){return P(this,void 0,void 0,(function*(){yield this.scanPage()}))}refresh(){return P(this,void 0,void 0,(function*(){e.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){Mi(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{Mi()})).observe(document.documentElement,{childList:!0,subtree:!0}))}scanPage(){return P(this,void 0,void 0,(function*(){var t,i,n,o;const s=document.querySelectorAll("widgetic");if(e.debug("Found widgetic host elements",{count:s.length}),0===s.length)return void e.info("No widgets found on page");const r=[];for(const a of Array.from(s))if(se(a)&&a instanceof HTMLElement){if(Ci(a))continue;try{const s=U(a),d=null===(i=null===(t=s.device)||void 0===t?void 0:t.mobileEnabled)||void 0===i||i;if(!Ae(d,null===(o=null===(n=s.device)||void 0===n?void 0:n.desktopEnabled)||void 0===o||o)){e.debug("Widget skipped due to device restrictions",{compositionId:s.compositionId,deviceRestrictions:s.device,element:a.outerHTML.substring(0,100)+"..."}),a.style.display="none",a.setAttribute("data-device-restricted","true");continue}r.push({element:a,config:s})}catch(t){e.error("Failed to parse widget configuration",{element:a.outerHTML,error:t})}}0!==r.length?yield this.renderWidgetsBatch(r):e.warn("No valid widget configurations found")}))}renderWidgetsBatch(t){return P(this,void 0,void 0,(function*(){try{const i=[],n=t.map((({element:e,config:t})=>{let n=e;if(e.parentNode){const t=document.createElement("div");t.className=`widgetic-host ${e.className}`.trim(),e.getAttribute("style")&&(t.style.cssText=e.getAttribute("style")||""),e.parentNode.replaceChild(t,e),n=t}return i.push(n),{compositionId:t.compositionId,renderMode:re(t.renderMode,this.browserCapabilities),width:t.width,height:t.height,resize:t.resize,autoscale:t.autoscale,adaptive:t.adaptive,container:n}})),o=yield this.renderer.renderWidgets(n);for(let n=0;n<o.length;n++){const s=o[n],{config:r}=t[n],a=i[n],d=ae(r.compositionId),l=this.displayManager.initializeWidget(d,r,s.element);s.element instanceof HTMLElement&&a instanceof HTMLElement&&this.resizeHandler.registerWidget(d,s.element,a.parentElement||a,r);const c={id:d,config:r,element:s.element,displayState:l,state:{ready:!0,error:null,width:"number"==typeof r.width?r.width:parseInt(String(r.width)),height:"number"==typeof r.height?r.height:parseInt(String(r.height))},enterFullscreen:()=>this.displayManager.enterFullscreen(d),exitFullscreen:()=>this.displayManager.exitFullscreen(d),showOverlay:()=>this.displayManager.showOverlay(d),hideOverlay:()=>this.displayManager.hideOverlay(d),openPopup:()=>this.displayManager.openPopup(d),closePopup:()=>this.displayManager.closePopup(d)};this.instances.set(c.id,c),yield this.maybeAddEditorOverlay(s.element,r.compositionId),e.debug("Widget rendered successfully",{instanceId:c.id,compositionId:r.compositionId,renderMode:s.renderMode,displayMode:r.displayMode})}e.info("Batch widget rendering complete",{rendered:o.length,total:t.length})}catch(i){e.error("Batch widget rendering failed",{error:i});for(const{element:i,config:n}of t)try{yield this.renderSingleWidget(i,n)}catch(t){e.error("Individual widget rendering failed",{compositionId:n.compositionId,error:t})}}}))}renderSingleWidget(t,i){return P(this,void 0,void 0,(function*(){try{performance.now(),be(),Te();const e=Ce();if(this.shouldUseLazyLoading(t,i))return void e.register(t,i.compositionId,(()=>P(this,void 0,void 0,(function*(){yield this.performActualWidgetRender(t,i)}))),{config:i,priority:this.getWidgetPriority(i),resourceUrls:this.getWidgetResourceUrls(i)});yield this.performActualWidgetRender(t,i)}catch(t){const n=be(),o=t instanceof Error?t.message:"Render failed";throw n.recordWidgetError(i.compositionId,o),n.endWidgetLoad(i.compositionId,!1),e.error("Widget rendering failed",{error:t,config:i}),t}}))}performActualWidgetRender(t,i){return P(this,void 0,void 0,(function*(){const n=performance.now(),o=be(),s=Te();try{const e=this.getWidgetResourceUrls(i);if(e.length>0&&(yield s.loadResources(e,{type:"script",priority:"high",compositionId:i.compositionId})),!("render"in this.renderer)||"function"!=typeof this.renderer.render)throw new Error("Widget renderer does not support render method");{const{widgetElement:e,instance:s}=yield this.renderer.render(t,i);if(!e)throw new Error("Widget element not created");const r=performance.now()-n;o.recordWidgetRender(i.compositionId,r),o.endWidgetLoad(i.compositionId,!0),this.instances.set(s.id,s)}}catch(t){const n=be(),o=t instanceof Error?t.message:"Render failed";throw n.recordWidgetError(i.compositionId,o),n.endWidgetLoad(i.compositionId,!1),e.error("Widget rendering failed",{error:t,config:i}),t}}))}shouldUseLazyLoading(e,t){var i;if(!1===(null===(i=this.config.lazyLoading)||void 0===i?void 0:i.enabled))return!1;if("critical"===t.priority||!0===t.preload)return!1;const n=e.getBoundingClientRect();return!(n.top<window.innerHeight&&n.bottom>0)}getWidgetPriority(e){switch(e.priority){case"critical":return 10;case"high":return 7;case"medium":default:return 5;case"low":return 2}}getWidgetResourceUrls(e){const t=[];return e.scriptUrl&&t.push(e.scriptUrl),e.styleUrl&&t.push(e.styleUrl),e.resourceUrls&&Array.isArray(e.resourceUrls)&&t.push(...e.resourceUrls),t}maybeAddEditorOverlay(t,i){return P(this,void 0,void 0,(function*(){if(!1!==this.config.enableEditing)try{yield this.editorOverlay.addOverlay(t,i)}catch(t){e.debug("Failed to add editor overlay",{compositionId:i,error:t})}}))}getInstances(){return Array.from(this.instances.values())}getInstance(e){return this.instances.get(e)||null}getInstancesByComposition(e){return this.getInstances().filter((t=>t.config.compositionId===e))}getStats(){const e=this.renderer.getStats();return{version:n,widgetsRendered:this.instances.size,renderMode:"auto",cacheStats:e.batchCache,messagingActive:this.messenger.isActive(),customEventSubscriptions:this.messenger.getCustomEventSubscriptions(),functionHandlers:this.messenger.getFunctionHandlers(),authenticationStatus:this.authenticationStatus||void 0,editingSessions:this.editorOverlay.getActiveSessions().length}}createWidgetController(t){const i=Array.from(this.instances.values()).find((e=>e.config.compositionId===t));if(!i)return e.warn("Widget instance not found for controller creation",{compositionId:t}),null;const n=this.messenger.createWidgetController(i.id,t);return this.widgetControllers.set(t,n),e.info("Widget controller created",{compositionId:t,instanceId:i.id}),n}getWidgetController(e){return this.widgetControllers.get(e)||null}subscribeToWidget(e,t,i){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.subscribe(t,i)}callWidgetFunction(e,t,...i){return P(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.callFunction(t,...i)}))}updateWidgetConfig(e,t){return P(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.updateConfig(t)}))}getWidgetState(e,t){return P(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.getState(t)}))}setWidgetState(e,t,i){return P(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.setState(t,i)}))}emitToWidget(t,i,n,o){let s=this.getWidgetController(t);s||(s=this.createWidgetController(t),s)?s.emit(i,n,o):e.warn(`Cannot create controller for widget: ${t}`)}canEditComposition(e){return P(this,void 0,void 0,(function*(){return this.authDetector.canEditComposition(e)}))}getAuthenticationStatus(){return this.authenticationStatus}refreshAuthentication(){return P(this,void 0,void 0,(function*(){return yield this.checkAuthentication(),this.authenticationStatus}))}openEditor(e){return P(this,void 0,void 0,(function*(){if(!(yield this.canEditComposition(e)))throw new Error(`User cannot edit composition: ${e}`);yield this.editorOverlay.openEditor(e)}))}isEditorOpen(e){return this.editorOverlay.isEditorOpen(e)}closeEditor(e){return P(this,void 0,void 0,(function*(){yield this.editorOverlay.closeEditor(e)}))}setEditingEnabled(t){this.config.enableEditing=t,e.info("Editing mode changed",{enabled:t})}setContent(t,i){return P(this,arguments,void 0,(function*(t,i,n={}){try{const{getWidgetManager:e}=yield Promise.resolve().then((function(){return Qi})),o=e();return yield o.setContent(t,i,n)}catch(t){return e.error("[EmbedSDK] Failed to set content:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}))}getContentSchema(t){return P(this,void 0,void 0,(function*(){try{const e=this.getInstancesByComposition(t)[0];if(!e)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Qi})),n=i();return yield n.getContentSchema(e.config.compositionId)}catch(t){throw e.error("[EmbedSDK] Failed to get content schema:",t),t}}))}getDesignSchema(t){return P(this,void 0,void 0,(function*(){try{const e=this.getInstancesByComposition(t)[0];if(!e)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Qi})),n=i();return yield n.getDesignSchema(e.config.compositionId)}catch(t){throw e.error("[EmbedSDK] Failed to get design schema:",t),t}}))}validateContent(t,i){return P(this,void 0,void 0,(function*(){try{const{getWidgetManager:e}=yield Promise.resolve().then((function(){return Qi})),n=e();return yield n.validateContent(t,i)}catch(t){throw e.error("[EmbedSDK] Failed to validate content:",t),t}}))}getContent(t){try{return Gi().getContent(t)}catch(t){return e.error("[EmbedSDK] Failed to get content:",t),null}}onContentUpdate(e,t){return this.subscribeToWidget(e,"content_updated",t)}scan(){return P(this,void 0,void 0,(function*(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{const e=document.querySelectorAll("[data-widgetic]"),t=Array.from(e).map((e=>{const t=e.getAttribute("data-widgetic"),i=e.getAttribute("data-id");return t&&i?{id:t,dataId:i,element:e}:null})).filter(Boolean);return yield this.loadWidgets(t),{success:!0,widgets:t,errors:[]}}catch(e){return{success:!1,widgets:[],errors:[e instanceof Error?e.message:"Unknown error"]}}}))}loadWidgets(e){return P(this,void 0,void 0,(function*(){for(const t of e)try{yield this.loadWidget(t)}catch(e){}}))}loadWidget(e){return P(this,void 0,void 0,(function*(){yield new Promise((e=>setTimeout(e,100*Math.random())));const t=this.determineRenderMode();"iframe"===t?this.renderIframe(e):"custom-element"===t&&this.renderCustomElement(e)}))}determineRenderMode(){return"iframe"===this.config.renderMode?"iframe":"custom-element"===this.config.renderMode||"undefined"!=typeof customElements?"custom-element":"iframe"}renderIframe(e){const t=document.createElement("iframe");t.src=`https://widgetic.com/widget/${e.dataId}`,t.style.width=e.element.style.width||"400px",t.style.height=e.element.style.height||"300px",t.style.border="none",e.element.appendChild(t)}renderCustomElement(e){if("undefined"!=typeof customElements){customElements.get("widgetic-widget")||customElements.define("widgetic-widget",class extends HTMLElement{connectedCallback(){this.innerHTML=`<div>Widgetic Widget: ${this.getAttribute("data-widget-id")}</div>`}});const t=document.createElement("widgetic-widget");t.setAttribute("data-widget-id",e.dataId),e.element.appendChild(t)}}getConfig(){return Object.assign({},this.config)}showOverlay(t){this.overlayManager?this.overlayManager.showOverlay(t):e.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():e.warn("Overlay manager not initialized")}triggerOverlay(t,i={}){this.overlayManager?this.overlayManager.triggerOverlay(t,i):e.warn("Overlay manager not initialized")}isOverlayActive(){var e;return(null===(e=this.overlayManager)||void 0===e?void 0:e.isOverlayActive())||!1}destroy(){document.querySelectorAll("iframe").forEach((e=>e.remove()));document.querySelectorAll("widgetic-widget").forEach((e=>e.remove())),this.overlayManager&&(this.overlayManager.destroy(),this.overlayManager=null),this.isInitialized=!1}}let Xi=null;function en(e){return Xi||(Xi=new Zi(e)),Xi}"undefined"!=typeof document&&(Mi(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{Mi()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{h.enabled&&e.info("DOM ready, auto-initializing SDK"),en().init().catch((t=>{e.error("Auto-initialization failed",{error:t})}))})):(h.enabled&&e.info("DOM already ready, auto-initializing SDK"),setTimeout((()=>{en().init().catch((t=>{e.error("Auto-initialization failed",{error:t})}))}),0)));var tn=Object.freeze({__proto__:null,EmbedSDK:Zi,getSDK:en});class nn{constructor(){this.debugMode=!1,this.trackedElements=new WeakSet}static getInstance(){return nn.instance||(nn.instance=new nn),nn.instance}enableDebugMode(){this.debugMode=!0,this.addDebugStyles(),e.info("CSS debugging mode enabled")}disableDebugMode(){this.debugMode=!1,this.removeDebugStyles(),e.info("CSS debugging mode disabled")}analyzeWidget(e){const t=e.getAttribute("data-widgetic-instance")||"unknown",i=[],n=[];this.detectCSSConflicts(e,i),this.checkStyleIsolation(e,n);const o={widgetId:t,conflicts:i,isolationScore:this.calculateIsolationScore(e,i),recommendations:n};return this.debugMode&&this.displayDebugReport(o),o}detectCSSConflicts(e,t){const i=window.getComputedStyle(e);["font-family","font-size","color","background-color","margin","padding","border","box-sizing"].forEach((n=>{const o=i.getPropertyValue(n);i.getPropertyPriority(n),this.isExternalStyle(e,n,o)&&t.push({property:n,widgetValue:this.getWidgetStyleValue(e,n),externalValue:o,specificity:this.calculateSpecificity(e,n),source:this.getStyleSource(e,n)})}))}checkStyleIsolation(e,t){e.getAttribute("data-widgetic-instance")||t.push("Add data-widgetic-instance attribute for proper namespace isolation");const i=window.getComputedStyle(e);Array.from(i).some((e=>e.startsWith("--widgetic-")))||t.push("Use CSS custom properties (--widgetic-*) for better theme isolation");const n=i.getPropertyValue("contain");n.includes("layout")&&n.includes("style")||t.push("Apply CSS containment (contain: layout style paint) for better isolation");"auto"===i.getPropertyValue("z-index")&&this.hasStackingContext(e)&&t.push("Consider explicit z-index management to prevent stacking conflicts")}calculateIsolationScore(e,t){let i=100;i-=10*t.length;const n=window.getComputedStyle(e),o=n.getPropertyValue("contain");o.includes("layout")||(i-=15),o.includes("style")||(i-=15),o.includes("paint")||(i-=10);"isolate"!==n.getPropertyValue("isolation")&&(i-=10);e.getAttribute("data-widgetic-instance")||(i-=15);return"border-box"!==n.getPropertyValue("box-sizing")&&(i-=5),Math.max(0,i)}isExternalStyle(e,t,i){const n=document.createElement(e.tagName.toLowerCase());n.style.cssText=e.getAttribute("style")||"",document.body.appendChild(n);const o=window.getComputedStyle(n).getPropertyValue(t);return document.body.removeChild(n),i!==o&&!this.isWidgetStyle(e,t)}isWidgetStyle(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return!1;return this.getMatchingCSSRules(e).some((e=>{var n;return(null===(n=e.selectorText)||void 0===n?void 0:n.includes(`[data-widgetic-instance="${i}"]`))&&e.style.getPropertyValue(t)}))}getWidgetStyleValue(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return"";const n=this.getMatchingCSSRules(e).find((e=>{var t;return null===(t=e.selectorText)||void 0===t?void 0:t.includes(`[data-widgetic-instance="${i}"]`)}));return(null==n?void 0:n.style.getPropertyValue(t))||""}calculateSpecificity(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return 0;const n=i.selectorText||"";let o=0;return o+=100*(n.match(/#/g)||[]).length,o+=10*(n.match(/[\.\[]/g)||[]).length,o+=(n.match(/[a-zA-Z]/g)||[]).length,o}getStyleSource(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return"unknown";if(i.parentStyleSheet){const e=i.parentStyleSheet;if(e.href)return e.href;if(e.ownerNode)return"inline styles"}return"unknown"}getMatchingCSSRules(t){const i=[];try{for(let e=0;e<document.styleSheets.length;e++){const n=document.styleSheets[e];try{const e=n.cssRules||n.rules;for(let n=0;n<e.length;n++){const o=e[n];o.selectorText&&t.matches(o.selectorText)&&i.push(o)}}catch(e){continue}}}catch(t){e.warn("Failed to analyze CSS rules",{error:t})}return i}hasStackingContext(e){const t=window.getComputedStyle(e),i=t.getPropertyValue("position"),n=t.getPropertyValue("z-index"),o=t.getPropertyValue("transform"),s=t.getPropertyValue("opacity");return"static"!==i&&"auto"!==n||"none"!==o||parseFloat(s)<1}addDebugStyles(){const e="widgetic-css-debug-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n /* CSS Debug Mode Styles */\n widgetic-widget[data-widgetic-instance] {\n outline: 2px dashed #007bff !important;\n outline-offset: 2px !important;\n position: relative !important;\n }\n\n widgetic-widget[data-widgetic-instance]::before {\n content: "Widget: " attr(data-widgetic-instance) !important;\n position: absolute !important;\n top: -20px !important;\n left: 0 !important;\n background: #007bff !important;\n color: white !important;\n padding: 2px 6px !important;\n font-size: 10px !important;\n font-family: monospace !important;\n z-index: 10000 !important;\n pointer-events: none !important;\n }\n\n widgetic-widget[data-error="true"] {\n outline-color: #dc3545 !important;\n }\n\n widgetic-widget[data-loading="true"] {\n outline-color: #ffc107 !important;\n }\n\n widgetic-widget[data-ready="true"] {\n outline-color: #28a745 !important;\n }\n ',document.head.appendChild(t)}removeDebugStyles(){const e=document.getElementById("widgetic-css-debug-styles");e&&e.remove()}displayDebugReport(e){}monitorWidget(e){if(this.trackedElements.has(e))return;this.trackedElements.add(e);new MutationObserver((e=>{e.forEach((e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.debugMode}))})).observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:["style","class"]})}}nn.instance=null;const on=nn.getInstance();function sn(){on.enableDebugMode()}function rn(){on.disableDebugMode()}function an(e){return on.analyzeWidget(e)}function dn(e){on.monitorWidget(e)}const ln={WidgeticWidget:O,registerWidgeticWidget:k,getSDK:en,setApiKey:v,setTokenProvider:f,StaticApiKeyProvider:p,EndpointTokenProvider:m,FunctionTokenProvider:u,getConfiguration:g},cn={WidgetRenderer:z,getWidgetRenderer:D,CustomElementRenderer:R,IframeRenderer:L,AuthManager:I,detectBrowserCapabilities:oe,determineBestRenderMode:re,parseWidgetConfig:U,generateInstanceId:ae,isValidWidgetElement:se},hn={BatchApiClient:xi,getBatchClient:Di,ModuleLoader:Ri,getModuleLoader:Pi,WidgeticMessenger:he,getMessenger:ce,config:d,getApiUrl:b,getCdnUrl:a,getTokenProvider:y,getAuthToken:t,DefaultTokenProvider:w,CSSDebugger:nn,cssDebugger:on,enableCSSDebug:sn,disableCSSDebug:rn,log:e};export{Oi as A,xi as B,nn as C,Ui as D,Zi as E,tn as F,ri as G,ln as H,hn as L,cn as M,De as O,wi as P,Kt as R,Pe as W,Pi as a,fi as b,hi as c,ci as d,ei as e,gi as f,Di as g,Lt as h,ti as i,li as j,xe as k,Yi as l,Gi as m,en as n,on as o,Ri as p,an as q,_t as r,Zt as s,rn as t,sn as u,dn as v,Et as w,ki as x,Hi as y,vi as z};
|