@widgetic/embed-sdk 2.1.2 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{g as t,a as n}from"./api.js";import{n as i,m as o,l as s,d as r,g as a}from"./core.js";import{b as d,c,m as l}from"./scanner.js";import{a as u,g}from"./media.js";import{getMessenger as p}from"./messaging.js";import{R as m}from"./display.js";const h=["DOMAIN_NOT_ALLOWED","UNPUBLISHED","SUSPENDED","NOT_FOUND","RATE_LIMITED"],f={DOMAIN_NOT_ALLOWED:"domain_not_allowed",UNPUBLISHED:"unpublished",SUSPENDED:"suspended",NOT_FOUND:"not_found",RATE_LIMITED:"rate_limited"};function b(e){return h.includes(e)?f[e]:null}const w=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|gif|avif)(?:\?[^\s"'<>]*)?$/i,v=new Set;function y(e,t,n=e=>e){if("undefined"!=typeof document&&document.head)try{for(const i of function(e,t,n=2){const i=[];let o=0;const s=(e,t)=>{if(i.length>=n||o>=400)return;if(o+=1,"string"==typeof e)return void(w.test(e)&&!i.includes(e)&&i.push(e));if(t>=4||null===e||"object"!=typeof e)return;const r=Array.isArray(e)?e:Object.values(e);for(const e of r)s(e,t+1)};return s(e,0),s(t,0),i}(e,t)){const e=n(i);if(v.has(e))continue;v.add(e);const t=document.createElement("link");t.setAttribute("rel","preload"),t.setAttribute("as","image"),t.setAttribute("href",e),document.head.appendChild(t)}}catch(e){}}const I=[480,960,1600],k=["static.widgetic.com","cdn.widgetic.com"],E=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|avif)(?:\?[^\s"'<>]*)?$/i;function C(){var e;if("undefined"==typeof window)return I[I.length-1];return function(e){var t;const n=I,i=Number.isFinite(e)&&e>0?e:n[n.length-1];return null!==(t=n.find((e=>e>=i)))&&void 0!==t?t:n[n.length-1]}((window.innerWidth||(null===(e=document.documentElement)||void 0===e?void 0:e.clientWidth)||0)*Math.min(window.devicePixelRatio||1,2))}function x(e,t){let n=0;const i=(e,o)=>{if(n+=1,n>5e3)return e;if("string"==typeof e)return function(e,t){if(!E.test(e))return e;let n;try{n=new URL(e)}catch(t){return e}if(!k.includes(n.hostname.toLowerCase()))return e;if(n.pathname.startsWith("/cdn-cgi/"))return e;const i=`width=${t},fit=scale-down,quality=80,format=auto`;return`${n.origin}/cdn-cgi/image/${i}/${e}`}(e,t);if(o>=8||null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map((e=>i(e,o+1)));const s={};for(const[t,n]of Object.entries(e))s[t]=i(n,o+1);return s};return i(e,0)}function S(e,t,n){try{if(!function(e){if(!e||!0!==e.optimize)return!1;if("undefined"==typeof window||"undefined"==typeof document)return!1;if(!1===window.WIDGETIC_IMAGE_OPTIMIZE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-image-optimize]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-image-optimize")||"").trim().toLowerCase())return!1;return!0}(e))return{content:t,contentItems:n};const i=C();return{content:x(t,i),contentItems:x(n,i)}}catch(e){return{content:t,contentItems:n}}}const W="lookups",A=864e5;function M(){if("undefined"==typeof window||"undefined"==typeof document)return!1;const e=window;if(!e.indexedDB)return!1;if(!1===e.WIDGETIC_EMBED_LOOKUP_CACHE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-lookup-cache]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-lookup-cache")||"").trim().toLowerCase())return!1;return!0}let $=null;function L(){return $||($=new Promise((t=>{try{const n=window.indexedDB.open("widgetic-embed-lookup",1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(W)||n.result.createObjectStore(W)},n.onsuccess=()=>{t(n.result),function(t){e(this,void 0,void 0,(function*(){try{const e=t.transaction(W,"readwrite"),n=e.objectStore(W).openCursor(),i=Date.now()-A;n.onsuccess=()=>{const e=n.result;if(!e)return;const t=e.value;(!t||"number"!=typeof t.storedAtMs||t.storedAtMs<i)&&e.delete(),e.continue()}}catch(e){}}))}(n.result)},n.onerror=()=>t(null),n.onblocked=()=>t(null)}catch(e){t(null)}})),$)}const D="https://cdn.widgetic.com",_="DOMAIN_NOT_ALLOWED";function z(){if("undefined"==typeof document)return[];const e=[],t=document.querySelectorAll("script[src*='embed-sdk']");for(const n of Array.from(t)){const t=n.getAttribute("data-api-url");t&&t.trim()&&e.push(t.trim().replace(/\/+$/,""))}const n=window.WIDGETIC_EMBED_API;return n&&String(n).trim()&&e.push(String(n).trim().replace(/\/+$/,"")),e}function O(e){var t;if("undefined"==typeof window)return null;const n=window.__WIDGETIC_EMBED_LOOKUP__;return(null===(t=null==n?void 0:n[e])||void 0===t?void 0:t.embedUrl)||null}function R(e,t){if(!e||"object"!=typeof e)return null;let n="string"==typeof e.embedUrl?e.embedUrl:"";if(!n&&"string"==typeof e.js_path&&e.js_path.trim()){const t=e.js_path.trim();n=/^https?:\/\//i.test(t)?t:`${D}${t.startsWith("/")?"":"/"}${t}`}else!n&&"string"==typeof e.embed_url&&e.embed_url.trim()&&(n=e.embed_url.trim());if(!n)return null;const i=function(e){if(!e||"object"!=typeof e)return;const t=e;return"string"!=typeof t.moduleUrl||"number"!=typeof t.contractVersion?void 0:{moduleUrl:t.moduleUrl,contractVersion:t.contractVersion,moduleHash:"string"==typeof t.moduleHash?t.moduleHash:null}}(e.direct),o="string"==typeof e.compositionId?e.compositionId:void 0,s="string"==typeof e.widgetId?e.widgetId:"string"==typeof e.id?e.id:void 0,r="string"==typeof e.entryWriteToken?e.entryWriteToken:void 0;let a;if(e.entries&&"object"==typeof e.entries){const t=e.entries;"string"==typeof t.url&&(a=Object.assign({url:t.url},"string"==typeof t.writeToken?{writeToken:t.writeToken}:r?{writeToken:r}:{}))}else r&&o&&t&&(a={url:`${t.replace(/\/+$/,"")}/embed/compositions/${o}/entries`,writeToken:r});const d=function(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if("string"==typeof t.url&&t.url){const e=t.captcha,n=e&&"object"==typeof e&&"string"==typeof e.siteKey&&j.test(e.siteKey)?e.siteKey:void 0;return Object.assign({url:t.url},n?{captcha:{siteKey:n}}:{})}}if(t&&T.test(t.url))return{url:t.url.replace(/\/entries\/?$/,"/adapters")};return}(e.adapters,a),c=e.media,l=c&&"object"==typeof c&&"boolean"==typeof c.optimize?{optimize:c.optimize}:void 0,u=S(l,e.content&&"object"==typeof e.content?e.content:{},Array.isArray(e.contentItems)?e.contentItems:[]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({embedUrl:n,compositionId:o},s?{widgetId:s}:{}),{design:e.design&&"object"==typeof e.design?e.design:{},content:u.content,contentItems:u.contentItems}),l?{media:l}:{}),i?{direct:i}:{}),r?{entryWriteToken:r}:{}),a?{entries:a}:{}),d?{adapters:d}:{})}const j=/^[0-9A-Za-z_-]{10,80}$/,T=/\/embed\/compositions\/[^/]+\/entries\/?$/;function U(t){return e(this,void 0,void 0,(function*(){let e=null;try{e=yield t.json()}catch(t){e=null}const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e.code;return"string"==typeof t&&t.length>0&&t.length<=64?t:null}(e),i=(n&&b(n)?n:null)||(429===(o=t.status)?"RATE_LIMITED":404===o?"NOT_FOUND":null);var o;if(!i)return null;const s=b(i);return s?{gatewayCode:i,stateCode:s}:null}))}const H=new Map;function N(e){try{return new URL(e).origin}catch(e){return""}}function P(t){return e(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{method:"GET",mode:"cors"});if(!n.ok){const t=yield function(t){return e(this,void 0,void 0,(function*(){if(403!==t.status)return null;try{const e=yield t.json();if(!e||"object"!=typeof e||e.code!==_)return null;const n=e.details&&"object"==typeof e.details?e.details:null,i="string"==typeof(null==n?void 0:n.reason)?n.reason.slice(0,80):void 0;return{code:_,reason:i}}catch(e){return null}}))}(n);if(t)return{kind:"refused",refusal:t};const i=yield U(n);return i?{kind:"failed",failure:i}:{kind:"unavailable"}}return{kind:"json",json:yield n.json()}}catch(e){return{kind:"unavailable"}}}))}function F(t){const n=H.get(t);if(n)return n;const i=P(t).then((n=>("json"===n.kind&&R(n.json,N(t))&&function(t,n){e(this,void 0,void 0,(function*(){if(!M())return;const e=yield L();if(e)try{const i={json:n,storedAtMs:Date.now()};e.transaction(W,"readwrite").objectStore(W).put(i,t)}catch(e){}}))}(t,n.json),n)));return H.set(t,i),i.finally((()=>{H.get(t)===i&&H.delete(t)})),i}function B(e){return JSON.parse(JSON.stringify(e))}function q(t){return e(this,void 0,void 0,(function*(){const n=N(t),i=yield function(t){return e(this,void 0,void 0,(function*(){if(!M())return null;const e=yield L();return e?new Promise((n=>{try{const i=e.transaction(W,"readonly").objectStore(W).get(t);i.onsuccess=()=>{const e=i.result,t=e&&"number"==typeof e.storedAtMs&&e.json&&"object"==typeof e.json;n(t?e:null)},i.onerror=()=>n(null)}catch(e){n(null)}})):null}))}(t);if(i&&function(e,t=Date.now()){const n=t-e.storedAtMs;return n>=0&&n<=3e4}(i)){const e=R(B(i.json),n);if(e)return F(t),y(e.content,e.contentItems),{kind:"payload",payload:e,gatewayOrigin:n}}const o=yield F(t);if("json"!==o.kind)return o;const s=R(B(o.json),n);return s?(y(s.content,s.contentItems),{kind:"payload",payload:s,gatewayOrigin:n}):{kind:"unavailable"}}))}function V(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:"failed"===e.kind?{status:"failed",failure:e.failure}:{status:"found",payload:e.payload,gatewayOrigin:e.gatewayOrigin||void 0}}function K(){const e=[...z()];e.push(o().replace(/\/+$/,""));const t=String(i.PROD_API_URL).replace(/\/+$/,"");return t&&e.push(t),[...new Set(e)]}function J(e){const t=`/embed/compositions/${e}`;return K().map((e=>`${e}${t}`))}function G(t){return e(this,void 0,void 0,(function*(){const e=z();for(const n of e){const e=yield q(`${n}/embed/compositions/${t}`);if("unavailable"!==e.kind)return V(e)}const n=yield function(e){const t=O(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const n=document.createElement("script");n.src=`${D}/embed/compositions/${e}.js`,n.async=!0,n.onload=()=>t(O(e)),n.onerror=()=>t(null),document.head.appendChild(n)}))}(t);if(n){for(const e of J(t)){const t=yield q(e);if("refused"===t.kind)return V(t);if("failed"!==t.kind&&"payload"===t.kind){const e=t.payload;return{status:"found",payload:Object.assign(Object.assign({},e),{embedUrl:e.embedUrl||n}),gatewayOrigin:t.gatewayOrigin||void 0}}}return{status:"found",payload:{embedUrl:n,compositionId:t}}}let i=null;for(const e of J(t)){const t=yield q(e);if("refused"===t.kind)return V(t);if("failed"!==t.kind){if("payload"===t.kind)return V(t)}else i=t.failure}return i?{status:"failed",failure:i}:{status:"not-found"}}))}function Y(t){return e(this,void 0,void 0,(function*(){const e=z();for(const n of e){const e=yield q(`${n}/widgets/${encodeURIComponent(t)}`);if("unavailable"!==e.kind)return V(e)}const n=O(t);let i=null;for(const e of function(e){const t=`/widgets/${encodeURIComponent(e)}`;return K().map((e=>`${e}${t}`))}(t)){const t=yield q(e);if("refused"===t.kind)return V(t);if("failed"!==t.kind){if("payload"===t.kind)return V(t)}else i=t.failure}return n?{status:"found",payload:{embedUrl:n,widgetId:t}}:i?{status:"failed",failure:i}:{status:"not-found"}}))}const Z=new Set;function Q(e,t){var n;if(Z.has(e))return;Z.add(e);"undefined"!=typeof window&&(null===(n=window.location)||void 0===n?void 0:n.hostname)&&window.location.hostname,t.reason&&t.reason}function X(e,t,n,i,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=n,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",i&&s.setAttribute("data-composition-id",i),function(e,t){if(!t)return;const n=t.design&&Object.keys(t.design).length>0?t.design:null,i=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!n&&!i&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};n&&(s.design=n),i&&(s.content=i),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}const ee="undefined"!=typeof HTMLElement?HTMLElement:class{};class te extends ee{static get observedAttributes(){return["composition-id","width","height","resize","autoscale","adaptive","theme"]}constructor(){super(),this.svelteComponent=null,this.compositionData=null,this.widgetData=null,this.loadedModule=null,this.isInitialized=!1,this.isWidgetConnected=!1,this.resizeObserver=null,this.eventListeners=new Map,this.widgetState={ready:!1,error:null,loading:!1,data:{}},this.instanceId=this.generateInstanceId(),this.cssNamespace=`widgetic-${this.instanceId}`,this.initializeCSSIsolation(),s.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){var e;if(!this.isWidgetConnected){this.isWidgetConnected=!0,s.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const t=d(this),n=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:this.getAttribute("composition-id");if(!n)throw new Error("composition-id attribute is required");c(this);const i="widget"===(null==t?void 0:t.kind)?yield Y(n):yield G(n);if("refused"===i.status)throw Q(n,i.refusal),new Error("This embed is not authorized to be shown on this website.");const o="found"===i.status?i.payload:null;if(null==o?void 0:o.embedUrl){const e=l(this,o);return this.innerHTML="",this.appendChild(X(o.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",n,e)),void this.setWidgetReady()}yield this.loadWidgetData(n),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){s.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(s.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,n){if(this.isInitialized&&t!==n){switch(s.debug("WidgeticWidget attribute changed",{instanceId:this.instanceId,attribute:e,oldValue:t,newValue:n}),e){case"width":case"height":this.updateDimensions();break;case"resize":this.updateResizeMode();break;case"autoscale":this.updateAutoscale();break;case"adaptive":this.updateAdaptive();break;case"theme":this.updateTheme()}this.notifyWidgetPropsChanged()}}initializeCSSIsolation(){this.setAttribute("data-widgetic-instance",this.instanceId),this.addBaseStyles(),this.initializeCSSCustomProperties()}addBaseStyles(){const e=`widgetic-base-styles-${this.instanceId}`;if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n /* Widget base styles with namespace isolation */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] {\n /* CSS Reset for widget container */\n all: initial;\n \n /* Widget container properties */\n display: block;\n box-sizing: border-box;\n position: relative;\n \n /* CSS custom properties with namespacing */\n --widgetic-instance: ${this.instanceId};\n --widgetic-primary: var(--widgetic-${this.instanceId}-primary, #007bff);\n --widgetic-secondary: var(--widgetic-${this.instanceId}-secondary, #6c757d);\n --widgetic-background: var(--widgetic-${this.instanceId}-background, #ffffff);\n --widgetic-text: var(--widgetic-${this.instanceId}-text, #333333);\n --widgetic-border: var(--widgetic-${this.instanceId}-border, #dee2e6);\n \n /* Widget content isolation */\n contain: layout style paint;\n isolation: isolate;\n }\n\n /* Prevent external CSS interference */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] * {\n box-sizing: border-box;\n }\n\n /* Loading state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-loading="true"] {\n min-height: 120px;\n background: linear-gradient(90deg, #f0f0f0 25%, transparent 37%, #f0f0f0 63%);\n background-size: 400% 100%;\n animation: widgetic-loading-${this.instanceId} 1.5s ease-in-out infinite;\n }\n\n @keyframes widgetic-loading-${this.instanceId} {\n 0% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n\n /* Error state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-error="true"] {\n border: 2px dashed #dc3545;\n background-color: #f8d7da;\n color: #721c24;\n padding: 16px;\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n }\n `,document.head.appendChild(t)}initializeCSSCustomProperties(){const e=this.getAttribute("theme");if(e)try{const t=JSON.parse(e);Object.entries(t).forEach((([e,t])=>{this.style.setProperty(`--widgetic-${this.instanceId}-${e}`,String(t))}))}catch(t){s.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(n){return e(this,void 0,void 0,(function*(){const e=t();this.compositionData=yield e.getComposition(n),this.widgetData=yield e.getWidget(this.compositionData.widgetId),s.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:n,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=n();this.loadedModule=yield e.loadModule(this.widgetData),s.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return e(this,void 0,void 0,(function*(){if(!this.loadedModule||!this.compositionData)throw new Error("Widget module or composition data not loaded");try{const{component:e}=this.loadedModule.module,t=document.createElement("div");if(t.className=`widgetic-content-${this.instanceId}`,this.applyWidgetProperties(t),e.$$typeof)yield this.initializeReactComponent(t,e);else if(e._isVue||e.__isVue)yield this.initializeVueComponent(t,e);else{if("function"!=typeof e)throw new Error("Unsupported component type");yield this.initializeSvelteOrVanillaComponent(t,e)}this.innerHTML="",this.appendChild(t),this.isInitialized=!0,s.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw s.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,n){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.React||!window.ReactDOM)throw new Error("React not available globally");{const e=window.React,i=window.ReactDOM,o=this.getWidgetProps(),s=e.createElement(n,o);i.render(s,t)}}))}initializeVueComponent(t,n){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.Vue)throw new Error("Vue not available globally");{const e=window.Vue,i=this.getWidgetProps();new e({el:t,render:e=>e(n,{props:i})})}}))}initializeSvelteOrVanillaComponent(t,n){return e(this,void 0,void 0,(function*(){var e;const i=this.getWidgetProps();if(n.$$prop_def||(null===(e=n.prototype)||void 0===e?void 0:e.$$prop_def))this.svelteComponent=new n({target:t,props:i});else if(n.prototype&&n.prototype.constructor===n){const e=new n(t,i);"function"==typeof e.render&&(yield e.render())}else if("function"==typeof n)yield n(t,i);else{if(!n||"function"!=typeof n.init)throw new Error("Unknown component type");yield n.init(t,i)}}))}getWidgetProps(){var e,t;return{config:(null===(e=this.compositionData)||void 0===e?void 0:e.config)||{},metadata:(null===(t=this.compositionData)||void 0===t?void 0:t.metadata)||{},instance:this.instanceId,element:this,dimensions:{width:this.getAttribute("width")||"100%",height:this.getAttribute("height")||"400"},resize:this.getAttribute("resize")||"responsive",autoscale:"true"===this.getAttribute("autoscale"),adaptive:parseInt(this.getAttribute("adaptive")||"768"),state:this.widgetState,onStateChange:this.handleStateChange.bind(this),onResize:this.handleResize.bind(this),onError:this.handleError.bind(this)}}applyWidgetProperties(e){var t;const n=this.getAttribute("width")||"100%",i=this.getAttribute("height")||"400",o=this.getAttribute("resize")||"responsive";switch(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof i?`${i}px`:i,o){case"fill-width":e.style.width="100%";break;case"responsive":e.style.maxWidth="100%",e.style.height="auto"}e.classList.add(`widgetic-widget-${(null===(t=this.widgetData)||void 0===t?void 0:t.type)||"unknown"}`)}setupResponsiveBehavior(){const e=parseInt(this.getAttribute("adaptive")||"768"),t="true"===this.getAttribute("autoscale"),n=this.getAttribute("resize")||"responsive";t&&"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver((e=>{for(const t of e)this.handleAutoscale(t)})),this.resizeObserver.observe(this)),"responsive"!==n&&"fill-width"!==n||this.setupAdaptiveBehavior(e)}setupAdaptiveBehavior(e){const t=window.matchMedia(`(max-width: ${e}px)`),n=t=>{this.setAttribute("data-mobile",t.matches?"true":"false"),this.dispatchEvent(new CustomEvent("widgetic:adaptive",{detail:{isMobile:t.matches,breakpoint:e}}))};n(t),t.addEventListener("change",n),this.eventListeners.set("adaptive",(()=>{t.removeEventListener("change",n)}))}handleAutoscale(e){const{width:t,height:n}=e.contentRect;this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:t,height:n}})),this.widgetState.data.dimensions={width:t,height:n}}setupEventHandling(){const e=e=>{this.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{type:"click",originalEvent:e},bubbles:!0}))};this.addEventListener("click",e),this.eventListeners.set("click",(()=>{this.removeEventListener("click",e)}));const t=e=>{e.target instanceof HTMLFormElement&&this.handleFormSubmission(e)};this.addEventListener("submit",t),this.eventListeners.set("submit",(()=>{this.removeEventListener("submit",t)}))}handleFormSubmission(e){e.preventDefault();const t=e.target,n=new FormData(t),i={};n.forEach(((e,t)=>{i[t]=e})),this.widgetState.data.formData=i,this.dispatchEvent(new CustomEvent("widgetic:form-submit",{detail:{data:i,form:t},bubbles:!0})),s.debug("Form submitted",{instanceId:this.instanceId,data:i})}handleStateChange(e){this.widgetState.data=Object.assign(Object.assign({},this.widgetState.data),e),this.dispatchEvent(new CustomEvent("widgetic:state-change",{detail:{state:this.widgetState.data},bubbles:!0}))}handleResize(e){this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:e,bubbles:!0}))}handleError(e){this.setErrorState(e)}updateDimensions(){const e=this.querySelector(`.widgetic-content-${this.instanceId}`);e&&this.applyWidgetProperties(e)}updateResizeMode(){this.updateDimensions(),this.setupResponsiveBehavior()}updateAutoscale(){this.setupResponsiveBehavior()}updateAdaptive(){const e=parseInt(this.getAttribute("adaptive")||"768");this.setupAdaptiveBehavior(e)}updateTheme(){this.initializeCSSCustomProperties()}notifyWidgetPropsChanged(){this.svelteComponent&&"function"==typeof this.svelteComponent.$set&&this.svelteComponent.$set(this.getWidgetProps()),this.dispatchEvent(new CustomEvent("widgetic:props-changed",{detail:{props:this.getWidgetProps()}}))}setLoadingState(e){this.widgetState.loading=e,this.setAttribute("data-loading",e?"true":"false"),e&&(this.innerHTML=`\n <div class="widgetic-loading-${this.instanceId}">\n <div>Loading widget...</div>\n </div>\n `)}setWidgetReady(){this.widgetState.ready=!0,this.widgetState.loading=!1,this.widgetState.error=null,this.setAttribute("data-ready","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-error"),this.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:this.instanceId},bubbles:!0})),s.info("Widget ready",{instanceId:this.instanceId})}setErrorState(e){this.widgetState.error=e,this.widgetState.loading=!1,this.widgetState.ready=!1,this.setAttribute("data-error","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-ready"),this.innerHTML=`\n <div class="widgetic-error-${this.instanceId}">\n <strong>Widget Error</strong><br>\n <small>${e.message}</small>\n </div>\n `,this.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:e.message,instanceId:this.instanceId},bubbles:!0})),s.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return e(this,void 0,void 0,(function*(){this.cleanup(),this.isInitialized=!1,this.isWidgetConnected=!1,yield this.connectedCallback()}))}cleanup(){this.svelteComponent&&"function"==typeof this.svelteComponent.$destroy&&(this.svelteComponent.$destroy(),this.svelteComponent=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.eventListeners.forEach((e=>{if("function"==typeof e)try{e()}catch(e){s.warn("Failed to cleanup event listener",{instanceId:this.instanceId,error:e})}})),this.eventListeners.clear();const e=document.getElementById(`widgetic-base-styles-${this.instanceId}`);e&&e.remove(),s.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function ne(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",te),s.info("WidgeticWidget custom element registered")))}const ie="widgetic_autoscale_heights";function oe(e){return""!==e&&"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}function se(){try{const e=localStorage.getItem(ie);if(!e)return{};const t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}catch(e){return{}}}function re(e,t=Date.now()){if(!oe(e))return null;const n=se(),i=Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0;if(!i||"number"!=typeof i.height||!Number.isFinite(i.height)||i.height<=0)return null;if("number"!=typeof i.lastUpdated||t-i.lastUpdated>864e5){try{delete n[e],localStorage.setItem(ie,JSON.stringify(n))}catch(e){}return null}return i.height}function ae(e,t,n,i=Date.now()){if(oe(e)&&Number.isFinite(t)&&!(t<=0))try{const o=se();o[e]={compositionId:e,height:t,originalHeight:n,lastUpdated:i},localStorage.setItem(ie,JSON.stringify(o))}catch(e){}}class de{constructor(){this.observers=new Map,this.mutationObservers=new Map,this.timeouts=new Map,this.animationIds=new Map,this.storageKey=ie}static getInstance(){return de.instance||(de.instance=new de),de.instance}enableAutoScale(e,t,n={enabled:!0}){if(!n.enabled)return;const i=Object.assign({minHeight:n.minHeight||50,maxHeight:n.maxHeight||2e3,debounceDelay:n.debounceDelay||150,threshold:n.threshold||5,animate:!1!==n.animate,animationDuration:n.animationDuration||300},n),o=e.offsetHeight,s=this.getStoredHeight(t);s&&s!==o&&this.setElementHeight(e,s,i.animate,i.animationDuration),this.setupContentMonitoring(e,t,i,o)}disableAutoScale(e){const t=this.observers.get(e);t&&(t.disconnect(),this.observers.delete(e));const n=this.mutationObservers.get(e);n&&(n.disconnect(),this.mutationObservers.delete(e));const i=this.timeouts.get(e);i&&(clearTimeout(i),this.timeouts.delete(e));const o=this.animationIds.get(e);o&&(cancelAnimationFrame(o),this.animationIds.delete(e));const s=document.querySelector(`iframe[data-widgetic-id="${e}"], iframe[data-composition-id="${e}"]`);s&&s._autoscaleMessageCleanup&&(s._autoscaleMessageCleanup(),delete s._autoscaleMessageCleanup)}getStoredHeight(e){return re(e)}storeHeight(e,t,n){ae(e,t,n)}setupContentMonitoring(e,t,n,i){const o=this.findContentElement(e);if(!o)return void e.tagName.toLowerCase();const s=this.createDebouncedHeightUpdate(e,t,n,i);if("undefined"!=typeof ResizeObserver){const e=new ResizeObserver((e=>{for(const t of e){const e=t.target.scrollHeight;s(e)}}));e.observe(o),this.observers.set(t,e)}const r=new MutationObserver((()=>{const e=o.scrollHeight;s(e)}));r.observe(o,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,r);const a=o.scrollHeight;s(a)}findContentElement(e){var t;if("iframe"===e.tagName.toLowerCase())try{const n=e,i=n.contentDocument||(null===(t=n.contentWindow)||void 0===t?void 0:t.document);if(null==i?void 0:i.body)return i.body}catch(t){return this.setupIframePostMessageListener(e),null}const n=e.tagName.toLowerCase();if("widgetic"===n||"widgetic-widget"===n||e.classList.contains("widgetic-widget")){return e.querySelector(".widget-content, .widgetic-content, [data-content]")||e}return e}setupIframePostMessageListener(e){const t=e.getAttribute("data-widgetic-id")||e.getAttribute("data-composition-id")||"unknown",n=n=>{var i,o;if(n.source===e.contentWindow&&("widgetic:autoscale"===(null===(i=n.data)||void 0===i?void 0:i.type)||"autoscale"===(null===(o=n.data)||void 0===o?void 0:o.type))){const{height:i,contentHeight:o}=n.data.payload||n.data;if("number"==typeof i&&i>0){const n=this.getConfigForWidget(t),s=Math.max(n.minHeight||50,Math.min(n.maxHeight||2e3,i));this.setElementHeight(e,s,n.animate,n.animationDuration),this.storeHeight(t,s,e.offsetHeight),e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:e.offsetHeight,newHeight:s,contentHeight:o||i}}))}}};window.addEventListener("message",n),e._autoscaleMessageCleanup=()=>{window.removeEventListener("message",n)}}getConfigForWidget(e){return{enabled:!0,minHeight:50,maxHeight:2e3,animate:!0,animationDuration:300,debounceDelay:150,threshold:5}}createDebouncedHeightUpdate(e,t,n,i){let o=e.offsetHeight;return s=>{const r=this.timeouts.get(t);r&&clearTimeout(r);const a=setTimeout((()=>{const r=Math.max(n.minHeight,Math.min(n.maxHeight,s));Math.abs(r-o)>=n.threshold&&(this.setElementHeight(e,r,n.animate,n.animationDuration),this.storeHeight(t,r,i),o=r,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:o,newHeight:r,contentHeight:s}}))),this.timeouts.delete(t)}),n.debounceDelay);this.timeouts.set(t,a)}}setElementHeight(e,t,n=!0,i=300){if(!n)return void(e.style.height=`${t}px`);const o=e.offsetHeight,s=t-o;if(Math.abs(s)<1)return;const r=this.animationIds.get(e.id||e.tagName);r&&cancelAnimationFrame(r);const a=performance.now(),d=o,c=n=>{const o=n-a,r=Math.min(o/i,1),l=1-Math.pow(1-r,3),u=d+s*l;if(e.style.height=`${u}px`,r<1){const t=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},l=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,l)}clearStoredHeights(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStoredHeights(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return{}}}destroy(){this.observers.forEach((e=>e.disconnect())),this.observers.clear(),this.mutationObservers.forEach((e=>e.disconnect())),this.mutationObservers.clear(),this.timeouts.forEach((e=>clearTimeout(e))),this.timeouts.clear(),this.animationIds.forEach((e=>cancelAnimationFrame(e))),this.animationIds.clear()}}class ce{constructor(){this.autoScaleManager=de.getInstance(),ne()}render(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:n="100%",height:i="400",resize:o="responsive",autoscale:s=!0,adaptive:r=768,media:a,content:d}=t,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",e),c.setAttribute("width",String(n)),c.setAttribute("height",String(i)),c.setAttribute("resize",o),"boolean"==typeof s?c.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(c.setAttribute("autoscale","true"),void 0!==s.minHeight&&c.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&c.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&c.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&c.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&c.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&c.setAttribute("autoscale-animation-duration",String(s.animationDuration))):c.setAttribute("autoscale","false"),c.setAttribute("adaptive",String(r)),a&&Object.keys(a).length>0){u().registerWidget(e,a),this.setupCustomElementMediaListener(c,e)}if(d&&Object.keys(d).length>0){g().registerWidget(e,d),this.setupCustomElementContentListener(c,e)}return{id:`custom-${e}-${Date.now()}`,element:c,compositionData:{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},widgetData:{id:`widget-${e}`,name:`Widget ${e}`,type:"custom-element",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"custom-element",cleanup:()=>{c._mediaCommandCleanup&&c._mediaCommandCleanup(),c._mediaObserverCleanup&&c._mediaObserverCleanup(),c._contentPositionCleanup&&c._contentPositionCleanup()}}}))}initializeWidget(t,n,i){return e(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(t,n,i){return e(this,void 0,void 0,(function*(){if(n.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const e=window.React,o=window.ReactDOM,s=e.createElement(n,{config:i.config,metadata:i.metadata});o.render(s,t)}else{if(!n._isVue&&!n.__isVue||"undefined"==typeof window||!window.Vue)throw new Error("Framework component detected but framework not available");new(0,window.Vue)({el:t,render:e=>e(n,{props:{config:i.config,metadata:i.metadata}})})}}))}applyElementStyling(e,t,n){const{width:i,height:o,resize:s,autoscale:r,adaptive:a}=n;switch(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof o?`${o}px`:o,e.style.display="block",e.style.overflow="hidden",s){case"fill-width":e.style.width="100%";break;case"responsive":this.makeResponsive(e,a||768)}if(r){("boolean"==typeof r?r:r&&"object"==typeof r&&r.enabled)&&this.enableAutoscale(e,t,r)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const n=window.matchMedia(`(max-width: ${t}px)`),i=()=>{n.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};i(),n.addEventListener?n.addEventListener("change",i):n.addListener(i),e._responsiveCleanup=()=>{n.removeEventListener?n.removeEventListener("change",i):n.removeListener(i)}}enableAutoscale(e,t,n){const i="boolean"==typeof n?{enabled:n}:n;i.enabled&&(this.autoScaleManager.enableAutoScale(e,t,i),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)})}showLoadingState(e){e.innerHTML='\n <div class="widgetic-loading" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n ">\n <div style="text-align: center; color: #6c757d;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #dee2e6;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <small>Loading widget...</small>\n </div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n '}showErrorState(e,t){const n=t instanceof Error?t.message:"Unknown error";e.innerHTML=`\n <div class="widgetic-error" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #c53030;\n ">\n <div style="text-align: center; padding: 20px;">\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Error</div>\n <small style="color: #718096;">${n}</small>\n </div>\n </div>\n `,e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:n}}))}setupCustomElementMediaListener(e,t){const n=u(),i=t=>{const{command:n}=t.detail;if("pause"===n){const t=e.querySelectorAll("audio"),n=e.querySelectorAll("video");t.forEach((e=>{e.paused||e.pause()})),n.forEach((e=>{e.paused||e.pause()}))}else if("play"===n){const t=e.querySelectorAll("audio"),n=e.querySelectorAll("video"),i=Array.from(t).concat(Array.from(n)).find((e=>e.currentTime>0&&!e.ended));i&&i.play().catch((()=>{}))}};e.addEventListener("widgetic:media:command",i),e._mediaCommandCleanup=()=>{e.removeEventListener("widgetic:media:command",i)};const o=(i,o)=>s=>{const r=(e.__widgetConfig||{}).media||{},a="audio"===i.tagName.toLowerCase()?"audio":"video";n.handleMediaEvent({type:o,compositionId:t,config:r,data:{position:i.currentTime,duration:i.duration,volume:i.volume,mediaType:a,title:i.title||i.getAttribute("data-title")||void 0}})},s=()=>{const t=e.querySelectorAll("audio"),n=e.querySelectorAll("video");Array.from(t).concat(Array.from(n)).forEach((e=>{e.addEventListener("play",o(e,"play")),e.addEventListener("pause",o(e,"pause")),e.addEventListener("ended",o(e,"ended")),e.addEventListener("seeked",o(e,"seeking")),e.addEventListener("volumechange",o(e,"volumechange"))}))};s();const r=new MutationObserver((()=>{s()}));r.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{r.disconnect()}}setupCustomElementContentListener(e,t){const n=g(),i=i=>{if(i.detail&&i.detail.type){const o=i.detail.type,s=i.detail.data||i.detail;let r={};try{const t=e.getAttribute("data-content-config");t&&(r=JSON.parse(t))}catch(e){r={contentType:"custom",persistState:!0}}n.handleContentPositionEvent({type:o,compositionId:t,config:r,data:s})}};e.addEventListener("widgetic:content:position",i),e.addEventListener("widgetic:content:navigate",i),e.addEventListener("widgetic:content:complete",i),e.addEventListener("widgetic:content:reset",i),e.addEventListener("widgetic:content:metadata",i),e._contentPositionCleanup=()=>{e.removeEventListener("widgetic:content:position",i),e.removeEventListener("widgetic:content:navigate",i),e.removeEventListener("widgetic:content:complete",i),e.removeEventListener("widgetic:content:reset",i),e.removeEventListener("widgetic:content:metadata",i)}}}var le=Object.freeze({__proto__:null,CustomElementRenderer:ce});const ue={close:"Close",closeOverlay:"Close overlay",interactiveWidget:"Interactive widget"},ge=new Map([["fr",{close:"Fermer",closeOverlay:"Fermer la fenêtre",interactiveWidget:"Widget interactif"}],["de",{close:"Schließen",closeOverlay:"Fenster schließen",interactiveWidget:"Interaktives Widget"}],["es",{close:"Cerrar",closeOverlay:"Cerrar ventana",interactiveWidget:"Widget interactivo"}],["pt",{close:"Fechar",closeOverlay:"Fechar janela",interactiveWidget:"Widget interativo"}],["nl",{close:"Sluiten",closeOverlay:"Venster sluiten",interactiveWidget:"Interactieve widget"}],["da",{close:"Luk",closeOverlay:"Luk vinduet",interactiveWidget:"Interaktiv widget"}],["sv",{close:"Stäng",closeOverlay:"Stäng fönstret",interactiveWidget:"Interaktiv widget"}],["zh",{close:"关闭",closeOverlay:"关闭窗口",interactiveWidget:"交互式小组件"}],["ar",{close:"إغلاق",closeOverlay:"إغلاق النافذة",interactiveWidget:"ويجت تفاعلي"}],["he",{close:"סגירה",closeOverlay:"סגירת החלון",interactiveWidget:"וידג'ט אינטראקטיבי"}],["fa",{close:"بستن",closeOverlay:"بستن پنجره",interactiveWidget:"ویجت تعاملی"}],["ur",{close:"بند کریں",closeOverlay:"ونڈو بند کریں",interactiveWidget:"انٹرایکٹو ویجٹ"}]]);function pe(e,t=function(){var e,t;return"undefined"==typeof document?"":(null===(e=document.body)||void 0===e?void 0:e.getAttribute("lang"))||(null===(t=document.documentElement)||void 0===t?void 0:t.getAttribute("lang"))||""}()){const n=function(e){var t,n;const i=(null!=e?e:"").trim().replace(/_/g,"-").toLowerCase().split("-"),o="iw"===i[0]?"he":null!==(t=i[0])&&void 0!==t?t:"",s=null!==(n=i[1])&&void 0!==n?n:"";return("zh"!==o||"tw"!==s&&"hk"!==s&&"hant"!==s)&&ge.has(o)?o:null}(t),i=null===n?void 0:ge.get(n);return(null!=i?i:ue)[e]}ge.keys();class me{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&s.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,n,i){if("undefined"==typeof ResizeObserver)return void s.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,r=n.initialMode||(o<n.breakpoint?"mobile":"desktop"),a={mode:r,breakpoint:n.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,a),this.callbacks.set(e,i);const d=new ResizeObserver((t=>{this.handleResize(e,t,n)}));d.observe(t),this.observers.set(e,d),i(a),s.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:n.breakpoint,initialMode:r,containerWidth:o})}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e));const n=this.observers.get(e);n&&(n.disconnect(),this.observers.delete(e)),this.callbacks.delete(e),this.currentStates.delete(e),s.debug("Widget unregistered from responsive monitoring",{widgetId:e})}getCurrentState(e){return this.currentStates.get(e)||null}checkResponsiveState(e,t){const n=this.currentStates.get(e),i=this.callbacks.get(e);if(!n||!i)return void s.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<n.breakpoint?"mobile":"desktop";if(o!==n.mode){const r={mode:o,breakpoint:n.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,r),i(r),s.info("Responsive state changed manually",{widgetId:e,from:n.mode,to:o,width:t,breakpoint:n.breakpoint})}}handleResize(e,t,n){const i=this.debounceTimers.get(e);i&&clearTimeout(i);const o=setTimeout((()=>{this.processResize(e,t,n),this.debounceTimers.delete(e)}),n.debounceDelay||150);this.debounceTimers.set(e,o)}processResize(e,t,n){const i=this.currentStates.get(e),o=this.callbacks.get(e);if(!i||!o)return;const r=t[t.length-1];if(!r)return;const a=r.contentRect.width,d=a<n.breakpoint?"mobile":"desktop";if(d!==i.mode){const t={mode:d,breakpoint:n.breakpoint,width:a,timestamp:Date.now()};this.currentStates.set(e,t),o(t),s.info("Responsive breakpoint crossed",{widgetId:e,from:i.mode,to:d,width:a,breakpoint:n.breakpoint})}else if(Math.abs(a-i.width)>10){const t=Object.assign(Object.assign({},i),{width:a,timestamp:Date.now()});this.currentStates.set(e,t),s.debug("Container width updated",{widgetId:e,width:a,mode:i.mode,breakpoint:n.breakpoint})}}getRegisteredWidgets(){return Array.from(this.observers.keys())}cleanup(){const e=this.getRegisteredWidgets();for(const t of e)this.unregisterWidget(t);s.debug("ResponsiveManager cleanup complete")}}let he=null;function fe(){return he||(he=new me),he}class be{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=de.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:n,height:i,resize:o="fixed",autoscale:r=!1,adaptive:a,responsive:d,container:c,allowFullscreen:l=!0,sandbox:p=this.getDefaultSandboxPermissions(),allowedFeatures:h=this.getDefaultAllowedFeatures(),loading:f="lazy",enableResize:b=!0,compositionData:w,widgetData:v,security:y={},fallback:I={enabled:!0,timeout:1e4,retryCount:3},media:k}=t;if(!n||!i||!c)throw new Error("Missing required parameters: width, height, and container are required");const E=w||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},C=v||{id:E.widgetId,name:`Widget ${e}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]};try{const w=this.createSecureIframe(e,t);w.src=yield this.buildSecureIframeUrl(e,t),w.title=`Widgetic Widget: ${E.name||e}`,w.loading=f,this.applySandboxSecurity(w,p,h),w.width=n.toString(),w.height=i.toString(),w.frameBorder="0",w.scrolling="no",l&&(w.allowFullscreen=!0,w.setAttribute("allowfullscreen","")),w.title=`Widgetic Widget ${e}`,w.setAttribute("aria-label",`${pe("interactiveWidget")}: ${e}`);const v={compositionId:e,renderMode:"iframe",displayMode:"inline",resize:o,width:"number"==typeof n?n:parseInt(n.toString()),height:"number"==typeof i?i:parseInt(i.toString()),autoscale:r,adaptive:a,responsive:d,media:k},x=m.generateIframeCSS(v);x&&(w.style.cssText+=x),this.applyIframeStyling(w,e,{width:n,height:i,resize:o,autoscale:r,adaptive:a}),w.style.visibility="hidden",w.style.opacity="0",w.style.transition="opacity 0.3s ease",this.addLoadingIndicator(c,v),this.setupEnhancedIframeMessaging(w,e,y),this.setupLoadingOptimization(w,e,I);const S="lazy"===f,W=new Promise(((t,n)=>{let i=null;S||(i=setTimeout((()=>{n(new Error(`Iframe load timeout for composition: ${e}`))}),I.timeout||1e4)),w.onload=()=>{i&&clearTimeout(i),this.removeLoadingIndicator(c),w.style.visibility="visible",w.style.opacity="1",t()},w.onerror=()=>{i&&clearTimeout(i),this.removeLoadingIndicator(c),n(new Error(`Failed to load iframe for composition: ${e}`))}}));if(c.appendChild(w),b&&"undefined"!=typeof ResizeObserver){const t=new m({observeResize:!0}),n=`iframe-${e}-${Date.now()}`;w.setAttribute("data-widget-id",n),t.registerWidget(n,w,c,v),w.__resizeHandler=t,w.__widgetId=n}d&&"number"==typeof d&&d>0&&this.setupResponsiveMonitoring(w,c,e,d),this.iframeRegistry.set(e,w),w.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),S||(yield W);const A=`iframe-${e}-${Date.now()}`;if(s.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:n,height:i},resize:o,autoscale:r,responsive:d,sandbox:p.join(" "),features:h.join("; ")}),v.media&&Object.keys(v.media).length>0){u().registerWidget(e,v.media),this.setupIframeMediaListener(w,e)}if(t.content&&Object.keys(t.content).length>0){g().registerWidget(e,t.content),this.setupIframeContentListener(w,e)}return{id:A,element:w,compositionData:E,widgetData:C,renderMode:"iframe",cleanup:()=>this.cleanupWidget(w)}}catch(t){throw s.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(c),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){s.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),n=yield Promise.allSettled(e),i=[];for(let e=0;e<n.length;e++){const o=n[e],r=t[e];if("fulfilled"===o.status)i.push(o.value);else{s.error("Iframe widget rendering failed in batch",{compositionId:r.compositionId,error:o.reason});const e=`error-${r.compositionId}-${Date.now()}`;i.push({id:e,element:this.createErrorElement(r,o.reason),compositionData:{id:r.compositionId,name:`Composition ${r.compositionId}`,widgetId:`widget-${r.compositionId}`,config:{}},widgetData:{id:`widget-${r.compositionId}`,name:`Widget ${r.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return s.info("Iframe batch rendering complete",{total:t.length,successful:i.filter((e=>"IFRAME"===e.element.tagName)).length,failed:i.filter((e=>"IFRAME"!==e.element.tagName)).length}),i}))}createSecureIframe(e,t){var n;const i=document.createElement("iframe");return i.style.border="none",i.style.display="block",i.style.overflow="hidden",i.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),i.setAttribute("crossorigin","anonymous"),(null===(n=t.security)||void 0===n?void 0:n.enableCSP)&&i.setAttribute("csp",this.generateCSP(t.security.allowedOrigins)),i.setAttribute("data-widgetic-id",e),i.setAttribute("data-enhanced","true"),i}getDefaultSandboxPermissions(){return["allow-scripts","allow-same-origin","allow-forms","allow-popups","allow-presentation","allow-downloads"]}getDefaultAllowedFeatures(){return["autoplay","encrypted-media","picture-in-picture","fullscreen","clipboard-read","clipboard-write"]}applySandboxSecurity(e,t,n){e.setAttribute("sandbox",t.join(" ")),e.setAttribute("allow",n.join("; ")),e.setAttribute("fetchpriority","high")}generateCSP(e){const t=e||[r.CLIENT_URL];return[`default-src 'self' ${t.join(" ")}`,`script-src 'self' 'unsafe-inline' ${t.join(" ")}`,`style-src 'self' 'unsafe-inline' ${t.join(" ")}`,`img-src 'self' data: blob: ${t.join(" ")}`,`media-src 'self' blob: ${t.join(" ")}`,"object-src 'none'","base-uri 'self'","form-action 'self'"].join("; ")}buildSecureIframeUrl(t,n){return e(this,void 0,void 0,(function*(){var e;const i=`${r.CLIENT_URL}/embed/${t}`,o=new URLSearchParams;n.width&&o.set("width","number"==typeof n.width?n.width.toString():n.width),n.height&&o.set("height","number"==typeof n.height?n.height.toString():n.height),n.resize&&o.set("resize",n.resize),n.autoscale&&o.set("autoscale","true"),n.adaptive&&o.set("adaptive",n.adaptive.toString()),n.responsive&&"number"==typeof n.responsive&&o.set("responsive",n.responsive.toString()),(null===(e=n.security)||void 0===e?void 0:e.signatureValidation)&&o.set("validateSignature","true"),o.set("sdkVersion","1.0"),o.set("mode","iframe");try{const e=yield a();o.set("apiKey",e)}catch(e){s.warn("Failed to get auth token for iframe",e),r.API_KEY&&o.set("apiKey",r.API_KEY)}const d=`${i}?${o.toString()}`;return s.debug("Built secure iframe URL",{compositionId:t,url:d}),d}))}applyIframeStyling(e,t,n){const{width:i,height:o,resize:s,autoscale:r,adaptive:a}=n;if(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof o?`${o}px`:o,"fill-width"===s)e.style.width="100%",e.style.height="auto",e.style.minHeight="number"==typeof o?`${o}px`:o;r&&this.enableIframeAutoscale(e,t,r),a&&this.makeIframeResponsive(e,a)}makeIframeResponsive(e,t){const n=window.matchMedia(`(max-width: ${t}px)`),i=()=>{n.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};i(),n.addEventListener?n.addEventListener("change",i):n.addListener(i),e._responsiveCleanup=()=>{n.removeEventListener?n.removeEventListener("change",i):n.removeListener(i)}}enableIframeAutoscale(e,t,n){const i="boolean"==typeof n?{enabled:n}:n;i.enabled&&(this.autoScaleManager.enableAutoScale(e,t,i),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)},s.debug("AutoScale enabled for iframe",{compositionId:t,config:i}))}setupLoadingOptimization(e,t,n){if(!n.enabled)return;const i=n.timeout||1e4,o=n.retryCount||3;let r=0;const a=()=>{r<o?(r++,s.warn(`Iframe loading failed, retrying (${r}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+r}),1e3*r)):(s.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},d=setTimeout((()=>{s.warn("Iframe loading timeout",{compositionId:t,timeout:i}),a()}),i);this.loadingTimeouts.set(t,d),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),s.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{s.error("Iframe error occurred",{compositionId:t}),a()}))}handleIframeFallback(e,t){const n=document.createElement("div");n.className="widgetic-iframe-fallback",n.innerHTML='\n <div style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n text-align: center;\n padding: 20px;\n ">\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Unavailable</div>\n <small>The widget could not be loaded. Please try refreshing the page.</small>\n </div>\n </div>\n ',e.parentNode&&(e.parentNode.insertBefore(n,e),e.parentNode.removeChild(e)),n.dispatchEvent(new CustomEvent("widgetic:fallback",{detail:{compositionId:t,reason:"loading_failed"},bubbles:!0}))}setupEnhancedIframeMessaging(e,t,n={}){const i=p({enableSignatureValidation:n.signatureValidation||!1,allowedOrigins:n.allowedOrigins,enableHeartbeat:!0,heartbeatInterval:3e4});i.registerHandler(t,(t=>{this.handleEnhancedIframeMessage(e,t)})),e.addEventListener("load",(()=>{i.sendMessage(t,{type:"config",instanceId:t,payload:{compositionId:t,apiUrl:o(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),s.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=i,e.__messagingCompositionId=t,s.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(s.debug("Enhanced iframe message received",{type:t.type,instanceId:t.instanceId,sequence:t.sequence}),t.type){case"resize":this.handleResizeMessage(e,t);break;case"ready":this.handleReadyMessage(e,t);break;case"error":this.handleErrorMessage(e,t);break;case"data":this.handleDataMessage(e,t);break;case"event":this.handleEventMessage(e,t);break;default:s.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width:n,height:i}=t.payload;n&&i&&(e.style.width=`${n}px`,e.style.height=`${i}px`,e.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:n,height:i,instanceId:t.instanceId},bubbles:!0})),s.debug("Iframe resized",{width:n,height:i,instanceId:t.instanceId}))}handleReadyMessage(e,t){e.setAttribute("data-ready","true"),e.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,payload:t.payload},bubbles:!0})),s.info("Iframe widget ready",{instanceId:t.instanceId})}handleErrorMessage(e,t){e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,error:t.payload.error,code:t.payload.code},bubbles:!0})),s.error("Iframe widget error",{instanceId:t.instanceId,error:t.payload.error})}handleDataMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:data",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,data:t.payload},bubbles:!0})),s.debug("Iframe data received",{instanceId:t.instanceId,dataType:t.payload.type})}handleEventMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,eventType:t.payload.type,eventData:t.payload.data},bubbles:!0})),s.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,n){p().sendMessage(e,{type:t,instanceId:e,payload:n,timestamp:Date.now(),version:"1.0"})}addLoadingIndicator(e,t){const n=document.createElement("div");n.className="widgetic-loading-indicator",n.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${t.width}px;\n height: ${t.height}px;\n background: #f5f5f5;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #e0e0e0;\n border-radius: 4px;\n position: relative;\n `,n.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #666;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div>Loading widget...</div>\n </div>\n ';const i=document.createElement("style");i.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(i),e.appendChild(n)}removeLoadingIndicator(e){const t=e.querySelector(".widgetic-loading-indicator");t&&t.parentNode&&t.parentNode.removeChild(t)}createErrorElement(e,t){const n=document.createElement("div");return n.className="widgetic-error",n.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${e.width}px;\n height: ${e.height}px;\n background: #fff5f5;\n color: #e53e3e;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n text-align: center;\n padding: 16px;\n box-sizing: border-box;\n `,n.innerHTML=`\n <div>\n <div style="font-weight: 600; margin-bottom: 4px;">Widget Error</div>\n <div style="font-size: 12px; opacity: 0.8;">Failed to load composition: ${e.compositionId}</div>\n </div>\n `,n}cleanupWidget(e){const t=e.__resizeHandler,n=e.__widgetId;t&&n&&t.unregisterWidget(n);const i=e.__responsiveManager,o=e.__responsiveId;i&&o&&i.unregisterWidget(o);const r=e.__messenger,a=e.__messagingCompositionId;r&&a&&r.unregisterHandler(a);const d=this.loadingTimeouts.get(a);d&&(clearTimeout(d),this.loadingTimeouts.delete(a)),a&&this.iframeRegistry.delete(a),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),s.debug("Iframe cleanup complete",{compositionId:a})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,n,i){const o=fe(),r=p(),a={breakpoint:i,debounceDelay:150},d=`responsive-${n}`;o.registerWidget(d,t,a,(t=>{s.debug("Responsive state changed, notifying iframe",{compositionId:n,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),r.sendMessage(n,{type:"responsive",instanceId:n,compositionId:n,payload:{mode:t.mode,breakpoint:t.breakpoint,width:t.width,timestamp:t.timestamp},timestamp:Date.now(),version:"1.0"}),e.dispatchEvent(new CustomEvent("widgetic:responsive",{detail:{instanceId:n,compositionId:n,mode:t.mode,breakpoint:t.breakpoint,width:t.width},bubbles:!0}))})),e.__responsiveId=d,e.__responsiveManager=o,s.info("Responsive monitoring enabled for iframe",{compositionId:n,breakpoint:i,containerId:d})}setupIframeMediaListener(e,t){const n=u(),i=i=>{var o,s;if(i.source===e.contentWindow&&(null===(s=null===(o=i.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:media:"))){const o=i.data.type.replace("widgetic:media:","");if(["play","pause","stop","ended","seeking","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"].includes(o)){const s=e.getAttribute("data-widget-config"),r=s?JSON.parse(s):{};n.handleMediaEvent({type:o,compositionId:t,config:r.media||{},data:i.data.detail||i.data.payload||i.data.data||{}})}}};window.addEventListener("message",i),e._mediaListenerCleanup=()=>{window.removeEventListener("message",i)}}setupIframeContentListener(e,t){const n=g(),i=i=>{var o,s;if(i.source===e.contentWindow&&(null===(s=null===(o=i.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:content:"))){const o=i.data.type.replace("widgetic:content:","");if(["position","navigate","complete","reset","metadata"].includes(o)){const s=e.getAttribute("data-widgetic-config");let r={};if(s)try{r=JSON.parse(s).content||{}}catch(e){r={contentType:"custom",persistState:!0}}n.handleContentPositionEvent({type:o,compositionId:t,config:r,data:i.data.payload||i.data.data||{}})}}};window.addEventListener("message",i),e._contentListenerCleanup=()=>{window.removeEventListener("message",i)}}}let we=null;var ve=Object.freeze({__proto__:null,IframeRenderer:be,getIframeRenderer:function(){return we||(we=new be),we}});class ye{constructor(){this.batchClient=t(),this.moduleLoader=n(),this.customElementRenderer=new ce,this.iframeRenderer=new be,this.renderedWidgets=new Map}renderWidget(t){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId),n=this.createLoadingElement(t.container);t.container&&n&&t.container.appendChild(n);try{const i=yield this.batchClient.getComposition(t.compositionId),o=yield this.batchClient.getWidget(i.widgetId),s=this.determineRenderMode(t.renderMode,o);let r;if("custom-element"===s)try{r=yield this.moduleLoader.loadModule(o)}catch(s){const r=yield this.renderWithIframe(e,t,i,o);return this.removeLoadingElement(n),r}const a="iframe"===s?yield this.renderWithIframe(e,t,i,o):yield this.renderWithCustomElement(e,t,i,o,r);return this.removeLoadingElement(n),this.renderedWidgets.set(e,a),this.emitWidgetEvent("ready",{widgetId:e,compositionId:t.compositionId,renderMode:a.renderMode,loadTime:(null==r?void 0:r.loadTime)||0,cached:(null==r?void 0:r.cached)||!1}),a}catch(i){if(this.removeLoadingElement(n),this.emitWidgetEvent("error",{widgetId:e,compositionId:t.compositionId,error:i instanceof Error?i.message:String(i),fallback:"iframe"}),t.container){const e=this.createErrorElement(t.compositionId,i);t.container.appendChild(e)}try{const n=yield this.renderFallback(e,t);if(t.container){const e=t.container.querySelector(".widgetic-error");e&&e.remove()}return n}catch(e){throw new Error(`Widget rendering failed: ${i}. Fallback also failed: ${e}`)}}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){const n=t.map((e=>e.compositionId)),i=yield this.batchClient.getCompositions(n),o=new Map(i.map((e=>[e.id,e]))),s=new Set;for(const e of t)if("iframe"!==e.renderMode){const t=o.get(e.compositionId);t&&t.widgetId&&s.add(t.widgetId)}const r=s.size>0?yield this.batchClient.getWidgets(Array.from(s)):[],a=new Map(r.map((e=>[e.id,e]))),d=r.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));d.length>0&&(yield this.moduleLoader.preloadModules(d));const c=t.map((t=>e(this,void 0,void 0,(function*(){const e=o.get(t.compositionId)||{id:t.compositionId,widgetId:"default",name:"Composition",settings:{},config:{},version:"1.0.0"},n=a.get(e.widgetId)||{id:e.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(t,e,n)}))));return(yield Promise.allSettled(c)).filter((e=>"rejected"!==e.status)).map((e=>e.value))}))}getWidget(e){return this.renderedWidgets.get(e)||null}getAllWidgets(){return Array.from(this.renderedWidgets.values())}refreshWidget(t){return e(this,void 0,void 0,(function*(){const e=this.renderedWidgets.get(t);if(!e)return null;e.cleanup(),this.renderedWidgets.delete(t);const n={compositionId:e.compositionData.id,renderMode:e.renderMode,container:e.element.parentElement||void 0};return this.batchClient.clearCache(),this.moduleLoader.invalidateModule(e.widgetData.id),this.renderWidget(n)}))}cleanupWidget(e){const t=this.renderedWidgets.get(e);t&&(t.cleanup(),this.renderedWidgets.delete(e))}cleanupAll(){const e=Array.from(this.renderedWidgets.values());for(const t of e)t.cleanup();this.renderedWidgets.clear()}getStats(){return{renderedWidgets:this.renderedWidgets.size,batchCache:this.batchClient.getCacheStats(),moduleCache:this.moduleLoader.getCacheStats(),widgets:Array.from(this.renderedWidgets.entries()).map((([e,t])=>({id:e,compositionId:t.compositionData.id,widgetType:t.widgetData.type,renderMode:t.renderMode,hasModule:!!t.loadedModule})))}}renderSingleWidgetWithData(t,n,i){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId);if("custom-element"===this.determineRenderMode(t.renderMode,i))try{const o=yield this.moduleLoader.loadModule(i);return this.renderWithCustomElement(e,t,n,i,o)}catch(e){}return this.renderWithIframe(e,t,n,i)}))}renderWithCustomElement(t,n,i,o,s){return e(this,void 0,void 0,(function*(){const e=yield this.customElementRenderer.render({compositionId:n.compositionId,compositionData:i,widgetData:o,loadedModule:s,width:n.width,height:n.height,resize:n.resize,autoscale:n.autoscale,adaptive:n.adaptive});return n.container&&n.container.appendChild(e.element),{id:t,element:e.element,compositionData:i,widgetData:o,loadedModule:s,renderMode:"custom-element",cleanup:()=>{e.element.remove()}}}))}renderWithIframe(t,n,i,o){return e(this,void 0,void 0,(function*(){return yield this.iframeRenderer.renderWidget({compositionId:n.compositionId,compositionData:i,widgetData:o,width:n.width,height:n.height,resize:n.resize,autoscale:n.autoscale,adaptive:n.adaptive,container:n.container})}))}renderFallback(t,n){return e(this,void 0,void 0,(function*(){const e=document.createElement("div");return e.className="widgetic-fallback",e.innerHTML=`\n <div style="\n padding: 20px; \n text-align: center; \n background: #f5f5f5; \n border: 1px solid #ddd; \n border-radius: 4px;\n color: #666;\n ">\n <p>Widget temporarily unavailable</p>\n <small>Composition ID: ${n.compositionId}</small>\n </div>\n `,n.container&&n.container.appendChild(e),{id:t,element:e,compositionData:{id:n.compositionId,name:"Fallback",widgetId:"fallback",config:{}},widgetData:{id:"fallback",name:"Fallback Widget",type:"fallback",version:"1.0.0",moduleUrl:""},renderMode:"iframe",cleanup:()=>{e.remove()}}}))}determineRenderMode(e="auto",t){var n;if("auto"!==e)return e;const i="undefined"!=typeof customElements&&"function"==typeof customElements.define,o=(null==t?void 0:t.moduleUrl)||(null===(n=null==t?void 0:t.metadata)||void 0===n?void 0:n.supportsCustomElements);return i&&o?"custom-element":"iframe"}generateWidgetId(e){return`widget-${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}emitWidgetEvent(e,t){const n=new CustomEvent(`widgetic:${e}`,{detail:t,bubbles:!0});document.dispatchEvent(n)}createLoadingElement(e){if(!e)return null;const t=document.createElement("div");return t.className="widgetic-loading",t.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n ",t.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #f3f3f3;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div style="font-size: 14px;">Loading widget...</div>\n </div>\n ',this.addLoadingStyles(),t}removeLoadingElement(e){e&&e.parentNode&&e.parentNode.removeChild(e)}createErrorElement(e,t){const n=document.createElement("div");n.className="widgetic-error",n.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n padding: 20px;\n text-align: center;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #742a2a;\n ";const i=t instanceof Error?t.message:"Unknown error occurred",o=this.analyzeError(i,t);return n.innerHTML=`\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">${o.icon}</div>\n <div style="font-weight: 500; margin-bottom: 8px;">${o.title}</div>\n <div style="font-size: 14px; margin-bottom: 12px; color: #666;">\n ${o.description}\n </div>\n <div style="font-size: 12px; margin-bottom: 16px; color: #888;">\n Widget ID: ${e}\n </div>\n ${o.actionHtml}\n </div>\n `,n}analyzeError(e,t){const n=e.toLowerCase();return n.includes("composition not found")||n.includes("404")?{icon:"🔍",title:"Widget Not Found",description:"This widget may have been removed or the ID is incorrect.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Not%20Found%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThe%20widget%20could%20not%20be%20found.%20Please%20check%20if%20it%20was%20deleted%20or%20if%20the%20ID%20is%20correct.', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("unauthorized")||n.includes("forbidden")||n.includes("401")||n.includes("403")||n.includes("permission")||n.includes("access denied")?{icon:"🔒",title:"Access Restricted",description:"This widget requires an active subscription or has been restricted.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ Upgrade Plan\n </a>\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Access%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20am%20having%20trouble%20accessing%20this%20widget.%20Please%20check%20my%20account%20status%20and%20permissions.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("deleted")||n.includes("expired")||n.includes("no longer available")?{icon:"🗑️",title:"Widget Deleted",description:"This widget has been permanently removed.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Deleted%20Widget%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThis%20widget%20appears%20to%20have%20been%20deleted.%20Can%20you%20help%20me%20restore%20it%20or%20find%20an%20alternative?', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("subscription")||n.includes("billing")||n.includes("payment")||n.includes("plan")||n.includes("downgrade")?{icon:"💳",title:"Subscription Required",description:"This widget requires an active subscription to display.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ View Plans\n </a>\n <a \n href="https://widgetic.com/dashboard/billing" \n target="_blank"\n style="\n background: #6c757d;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#5a6268'"\n onmouseout="this.style.background='#6c757d'"\n >\n 💳 Billing\n </a>\n </div>\n <div style="font-size: 12px; color: #888; margin-top: 8px;">\n Need help? Contact support below\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Subscription%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20need%20help%20with%20my%20subscription%20to%20access%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 4px 8px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 11px;\n margin-top: 4px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("timeout")||n.includes("network")||n.includes("connection")||n.includes("fetch")?{icon:"🌐",title:"Connection Issue",description:"Unable to load widget due to network connectivity.",actionHtml:`\n <button \n onclick="window.location.reload()"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n 🔄 Retry\n </button>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Connection%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}%0A%0AI%20am%20experiencing%20connection%20issues%20loading%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:{icon:"⚠️",title:"Widget Unavailable",description:e||"An unknown error occurred while loading this widget.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Error%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n <div style="margin-top: 8px;">\n <button \n onclick="window.location.reload()"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n margin-left: 8px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 🔄 Refresh Page\n </button>\n </div>\n `}}addLoadingStyles(){const e="widgetic-loading-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(t)}}let Ie=null;function ke(){return Ie||(Ie=new ye),Ie}function Ee(){Ie&&Ie.cleanupAll(),Ie=null}var Ce=Object.freeze({__proto__:null,WidgetRenderer:ye,getWidgetRenderer:ke,resetWidgetRenderer:Ee});export{ce as C,be as I,te as W,G as a,Q as b,X as c,pe as d,ne as e,ye as f,ke as g,re as h,Ee as i,le as j,ve as k,Ce as l,K as p,Y as r,b as s,ae as w};
1
+ import{_ as e}from"./vendor.js";import{g as t,a as n}from"./api.js";import{n as i,m as o,l as s,d as r,g as a}from"./core.js";import{b as d,c,m as l}from"./scanner.js";import{a as u,g}from"./media.js";import{getMessenger as p}from"./messaging.js";import{R as m}from"./display.js";const h=["DOMAIN_NOT_ALLOWED","UNPUBLISHED","SUSPENDED","NOT_FOUND","RATE_LIMITED"],f={DOMAIN_NOT_ALLOWED:"domain_not_allowed",UNPUBLISHED:"unpublished",SUSPENDED:"suspended",NOT_FOUND:"not_found",RATE_LIMITED:"rate_limited"};function b(e){return h.includes(e)?f[e]:null}const w=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|gif|avif)(?:\?[^\s"'<>]*)?$/i,v=new Set;function y(e,t,n=e=>e){if("undefined"!=typeof document&&document.head)try{for(const i of function(e,t,n=2){const i=[];let o=0;const s=(e,t)=>{if(i.length>=n||o>=400)return;if(o+=1,"string"==typeof e)return void(w.test(e)&&!i.includes(e)&&i.push(e));if(t>=4||null===e||"object"!=typeof e)return;const r=Array.isArray(e)?e:Object.values(e);for(const e of r)s(e,t+1)};return s(e,0),s(t,0),i}(e,t)){const e=n(i);if(v.has(e))continue;v.add(e);const t=document.createElement("link");t.setAttribute("rel","preload"),t.setAttribute("as","image"),t.setAttribute("href",e),document.head.appendChild(t)}}catch(e){}}const I=[480,960,1600],k=["static.widgetic.com","cdn.widgetic.com"],E=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|avif)(?:\?[^\s"'<>]*)?$/i;function C(){var e;if("undefined"==typeof window)return I[I.length-1];return function(e){var t;const n=I,i=Number.isFinite(e)&&e>0?e:n[n.length-1];return null!==(t=n.find((e=>e>=i)))&&void 0!==t?t:n[n.length-1]}((window.innerWidth||(null===(e=document.documentElement)||void 0===e?void 0:e.clientWidth)||0)*Math.min(window.devicePixelRatio||1,2))}function x(e,t){let n=0;const i=(e,o)=>{if(n+=1,n>5e3)return e;if("string"==typeof e)return function(e,t){if(!E.test(e))return e;let n;try{n=new URL(e)}catch(t){return e}if(!k.includes(n.hostname.toLowerCase()))return e;if(n.pathname.startsWith("/cdn-cgi/"))return e;const i=`width=${t},fit=scale-down,quality=80,format=auto`;return`${n.origin}/cdn-cgi/image/${i}/${e}`}(e,t);if(o>=8||null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map((e=>i(e,o+1)));const s={};for(const[t,n]of Object.entries(e))s[t]=i(n,o+1);return s};return i(e,0)}function S(e,t,n){try{if(!function(e){if(!e||!0!==e.optimize)return!1;if("undefined"==typeof window||"undefined"==typeof document)return!1;if(!1===window.WIDGETIC_IMAGE_OPTIMIZE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-image-optimize]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-image-optimize")||"").trim().toLowerCase())return!1;return!0}(e))return{content:t,contentItems:n};const i=C();return{content:x(t,i),contentItems:x(n,i)}}catch(e){return{content:t,contentItems:n}}}const W="lookups",A=864e5;function M(){if("undefined"==typeof window||"undefined"==typeof document)return!1;const e=window;if(!e.indexedDB)return!1;if(!1===e.WIDGETIC_EMBED_LOOKUP_CACHE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-lookup-cache]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-lookup-cache")||"").trim().toLowerCase())return!1;return!0}let $=null;function L(){return $||($=new Promise((t=>{try{const n=window.indexedDB.open("widgetic-embed-lookup",1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(W)||n.result.createObjectStore(W)},n.onsuccess=()=>{t(n.result),function(t){e(this,void 0,void 0,(function*(){try{const e=t.transaction(W,"readwrite"),n=e.objectStore(W).openCursor(),i=Date.now()-A;n.onsuccess=()=>{const e=n.result;if(!e)return;const t=e.value;(!t||"number"!=typeof t.storedAtMs||t.storedAtMs<i)&&e.delete(),e.continue()}}catch(e){}}))}(n.result)},n.onerror=()=>t(null),n.onblocked=()=>t(null)}catch(e){t(null)}})),$)}const D="https://cdn.widgetic.com",_="DOMAIN_NOT_ALLOWED";function z(){if("undefined"==typeof document)return[];const e=[],t=document.querySelectorAll("script[src*='embed-sdk']");for(const n of Array.from(t)){const t=n.getAttribute("data-api-url");t&&t.trim()&&e.push(t.trim().replace(/\/+$/,""))}const n=window.WIDGETIC_EMBED_API;return n&&String(n).trim()&&e.push(String(n).trim().replace(/\/+$/,"")),e}function R(e){var t;if("undefined"==typeof window)return null;const n=window.__WIDGETIC_EMBED_LOOKUP__;return(null===(t=null==n?void 0:n[e])||void 0===t?void 0:t.embedUrl)||null}function O(e,t){if(!e||"object"!=typeof e)return null;let n="string"==typeof e.embedUrl?e.embedUrl:"";if(!n&&"string"==typeof e.js_path&&e.js_path.trim()){const t=e.js_path.trim();n=/^https?:\/\//i.test(t)?t:`${D}${t.startsWith("/")?"":"/"}${t}`}else!n&&"string"==typeof e.embed_url&&e.embed_url.trim()&&(n=e.embed_url.trim());if(!n)return null;const i=function(e){if(!e||"object"!=typeof e)return;const t=e;return"string"!=typeof t.moduleUrl||"number"!=typeof t.contractVersion?void 0:{moduleUrl:t.moduleUrl,contractVersion:t.contractVersion,moduleHash:"string"==typeof t.moduleHash?t.moduleHash:null}}(e.direct),o="string"==typeof e.compositionId?e.compositionId:void 0,s="string"==typeof e.widgetId?e.widgetId:"string"==typeof e.id?e.id:void 0,r="string"==typeof e.entryWriteToken?e.entryWriteToken:void 0;let a;if(e.entries&&"object"==typeof e.entries){const t=e.entries;"string"==typeof t.url&&(a=Object.assign({url:t.url},"string"==typeof t.writeToken?{writeToken:t.writeToken}:r?{writeToken:r}:{}))}else r&&o&&t&&(a={url:`${t.replace(/\/+$/,"")}/embed/compositions/${o}/entries`,writeToken:r});const d=function(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if("string"==typeof t.url&&t.url){const e=t.captcha,n=e&&"object"==typeof e&&"string"==typeof e.siteKey&&j.test(e.siteKey)?e.siteKey:void 0;return Object.assign({url:t.url},n?{captcha:{siteKey:n}}:{})}}if(t&&T.test(t.url))return{url:t.url.replace(/\/entries\/?$/,"/adapters")};return}(e.adapters,a),c=e.media,l=c&&"object"==typeof c&&"boolean"==typeof c.optimize?{optimize:c.optimize}:void 0,u=S(l,e.content&&"object"==typeof e.content?e.content:{},Array.isArray(e.contentItems)?e.contentItems:[]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({embedUrl:n,compositionId:o},s?{widgetId:s}:{}),{design:e.design&&"object"==typeof e.design?e.design:{},content:u.content,contentItems:u.contentItems}),l?{media:l}:{}),i?{direct:i}:{}),r?{entryWriteToken:r}:{}),a?{entries:a}:{}),d?{adapters:d}:{})}const j=/^[0-9A-Za-z_-]{10,80}$/,T=/\/embed\/compositions\/[^/]+\/entries\/?$/;function U(t){return e(this,void 0,void 0,(function*(){let e=null;try{e=yield t.json()}catch(t){e=null}const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e.code;return"string"==typeof t&&t.length>0&&t.length<=64?t:null}(e),i=(n&&b(n)?n:null)||(429===(o=t.status)?"RATE_LIMITED":404===o?"NOT_FOUND":null);var o;if(!i)return null;const s=b(i);return s?{gatewayCode:i,stateCode:s}:null}))}const H=new Map;function N(e){try{return new URL(e).origin}catch(e){return""}}function P(t){return e(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{method:"GET",mode:"cors"});if(!n.ok){const t=yield function(t){return e(this,void 0,void 0,(function*(){if(403!==t.status)return null;try{const e=yield t.json();if(!e||"object"!=typeof e||e.code!==_)return null;const n=e.details&&"object"==typeof e.details?e.details:null,i="string"==typeof(null==n?void 0:n.reason)?n.reason.slice(0,80):void 0;return{code:_,reason:i}}catch(e){return null}}))}(n);if(t)return{kind:"refused",refusal:t};const i=yield U(n);return i?{kind:"failed",failure:i}:{kind:"unavailable"}}return{kind:"json",json:yield n.json()}}catch(e){return{kind:"unavailable"}}}))}function F(t){const n=H.get(t);if(n)return n;const i=P(t).then((n=>("json"===n.kind&&O(n.json,N(t))&&function(t,n){e(this,void 0,void 0,(function*(){if(!M())return;const e=yield L();if(e)try{const i={json:n,storedAtMs:Date.now()};e.transaction(W,"readwrite").objectStore(W).put(i,t)}catch(e){}}))}(t,n.json),n)));return H.set(t,i),i.finally((()=>{H.get(t)===i&&H.delete(t)})),i}function B(e){return JSON.parse(JSON.stringify(e))}function q(t){return e(this,void 0,void 0,(function*(){const n=N(t),i=yield function(t){return e(this,void 0,void 0,(function*(){if(!M())return null;const e=yield L();return e?new Promise((n=>{try{const i=e.transaction(W,"readonly").objectStore(W).get(t);i.onsuccess=()=>{const e=i.result,t=e&&"number"==typeof e.storedAtMs&&e.json&&"object"==typeof e.json;n(t?e:null)},i.onerror=()=>n(null)}catch(e){n(null)}})):null}))}(t);if(i&&function(e,t=Date.now()){const n=t-e.storedAtMs;return n>=0&&n<=3e4}(i)){const e=O(B(i.json),n);if(e)return F(t),y(e.content,e.contentItems),{kind:"payload",payload:e,gatewayOrigin:n}}const o=yield F(t);if("json"!==o.kind)return o;const s=O(B(o.json),n);return s?(y(s.content,s.contentItems),{kind:"payload",payload:s,gatewayOrigin:n}):{kind:"unavailable"}}))}function V(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:"failed"===e.kind?{status:"failed",failure:e.failure}:{status:"found",payload:e.payload,gatewayOrigin:e.gatewayOrigin||void 0}}function K(){const e=[...z()];e.push(o().replace(/\/+$/,""));const t=String(i.PROD_API_URL).replace(/\/+$/,"");return t&&e.push(t),[...new Set(e)]}function J(t){return e(this,void 0,void 0,(function*(){const e=z();for(const n of e){const e=yield q(`${n}/embed/compositions/${t}`);if("unavailable"!==e.kind)return V(e)}const n=R(t);let i=null;for(const e of function(e){const t=`/embed/compositions/${e}`;return K().map((e=>`${e}${t}`))}(t)){const t=yield q(e);if("refused"===t.kind)return V(t);if("failed"!==t.kind){if("payload"===t.kind)return V(t)}else i=t.failure}const o=null!=n?n:yield function(e){const t=R(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const n=document.createElement("script");n.src=`${D}/embed/compositions/${e}.js`,n.async=!0,n.onload=()=>t(R(e)),n.onerror=()=>t(null),document.head.appendChild(n)}))}(t);return o?{status:"found",payload:{embedUrl:o,compositionId:t}}:i?{status:"failed",failure:i}:{status:"not-found"}}))}function G(t){return e(this,void 0,void 0,(function*(){const e=z();for(const n of e){const e=yield q(`${n}/widgets/${encodeURIComponent(t)}`);if("unavailable"!==e.kind)return V(e)}const n=R(t);let i=null;for(const e of function(e){const t=`/widgets/${encodeURIComponent(e)}`;return K().map((e=>`${e}${t}`))}(t)){const t=yield q(e);if("refused"===t.kind)return V(t);if("failed"!==t.kind){if("payload"===t.kind)return V(t)}else i=t.failure}return n?{status:"found",payload:{embedUrl:n,widgetId:t}}:i?{status:"failed",failure:i}:{status:"not-found"}}))}const Y=new Set;function Z(e,t){var n;if(Y.has(e))return;Y.add(e);"undefined"!=typeof window&&(null===(n=window.location)||void 0===n?void 0:n.hostname)&&window.location.hostname,t.reason&&t.reason}function Q(e,t,n,i,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=n,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",i&&s.setAttribute("data-composition-id",i),function(e,t){if(!t)return;const n=t.design&&Object.keys(t.design).length>0?t.design:null,i=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!n&&!i&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};n&&(s.design=n),i&&(s.content=i),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}const X="undefined"!=typeof HTMLElement?HTMLElement:class{};class ee extends X{static get observedAttributes(){return["composition-id","width","height","resize","autoscale","adaptive","theme"]}constructor(){super(),this.svelteComponent=null,this.compositionData=null,this.widgetData=null,this.loadedModule=null,this.isInitialized=!1,this.isWidgetConnected=!1,this.resizeObserver=null,this.eventListeners=new Map,this.widgetState={ready:!1,error:null,loading:!1,data:{}},this.instanceId=this.generateInstanceId(),this.cssNamespace=`widgetic-${this.instanceId}`,this.initializeCSSIsolation(),s.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){var e;if(!this.isWidgetConnected){this.isWidgetConnected=!0,s.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const t=d(this),n=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:this.getAttribute("composition-id");if(!n)throw new Error("composition-id attribute is required");c(this);const i="widget"===(null==t?void 0:t.kind)?yield G(n):yield J(n);if("refused"===i.status)throw Z(n,i.refusal),new Error("This embed is not authorized to be shown on this website.");const o="found"===i.status?i.payload:null;if(null==o?void 0:o.embedUrl){const e=l(this,o);return this.innerHTML="",this.appendChild(Q(o.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",n,e)),void this.setWidgetReady()}yield this.loadWidgetData(n),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){s.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(s.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,n){if(this.isInitialized&&t!==n){switch(s.debug("WidgeticWidget attribute changed",{instanceId:this.instanceId,attribute:e,oldValue:t,newValue:n}),e){case"width":case"height":this.updateDimensions();break;case"resize":this.updateResizeMode();break;case"autoscale":this.updateAutoscale();break;case"adaptive":this.updateAdaptive();break;case"theme":this.updateTheme()}this.notifyWidgetPropsChanged()}}initializeCSSIsolation(){this.setAttribute("data-widgetic-instance",this.instanceId),this.addBaseStyles(),this.initializeCSSCustomProperties()}addBaseStyles(){const e=`widgetic-base-styles-${this.instanceId}`;if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n /* Widget base styles with namespace isolation */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] {\n /* CSS Reset for widget container */\n all: initial;\n \n /* Widget container properties */\n display: block;\n box-sizing: border-box;\n position: relative;\n \n /* CSS custom properties with namespacing */\n --widgetic-instance: ${this.instanceId};\n --widgetic-primary: var(--widgetic-${this.instanceId}-primary, #007bff);\n --widgetic-secondary: var(--widgetic-${this.instanceId}-secondary, #6c757d);\n --widgetic-background: var(--widgetic-${this.instanceId}-background, #ffffff);\n --widgetic-text: var(--widgetic-${this.instanceId}-text, #333333);\n --widgetic-border: var(--widgetic-${this.instanceId}-border, #dee2e6);\n \n /* Widget content isolation */\n contain: layout style paint;\n isolation: isolate;\n }\n\n /* Prevent external CSS interference */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] * {\n box-sizing: border-box;\n }\n\n /* Loading state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-loading="true"] {\n min-height: 120px;\n background: linear-gradient(90deg, #f0f0f0 25%, transparent 37%, #f0f0f0 63%);\n background-size: 400% 100%;\n animation: widgetic-loading-${this.instanceId} 1.5s ease-in-out infinite;\n }\n\n @keyframes widgetic-loading-${this.instanceId} {\n 0% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n\n /* Error state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-error="true"] {\n border: 2px dashed #dc3545;\n background-color: #f8d7da;\n color: #721c24;\n padding: 16px;\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n }\n `,document.head.appendChild(t)}initializeCSSCustomProperties(){const e=this.getAttribute("theme");if(e)try{const t=JSON.parse(e);Object.entries(t).forEach((([e,t])=>{this.style.setProperty(`--widgetic-${this.instanceId}-${e}`,String(t))}))}catch(t){s.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(n){return e(this,void 0,void 0,(function*(){const e=t();this.compositionData=yield e.getComposition(n),this.widgetData=yield e.getWidget(this.compositionData.widgetId),s.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:n,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=n();this.loadedModule=yield e.loadModule(this.widgetData),s.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return e(this,void 0,void 0,(function*(){if(!this.loadedModule||!this.compositionData)throw new Error("Widget module or composition data not loaded");try{const{component:e}=this.loadedModule.module,t=document.createElement("div");if(t.className=`widgetic-content-${this.instanceId}`,this.applyWidgetProperties(t),e.$$typeof)yield this.initializeReactComponent(t,e);else if(e._isVue||e.__isVue)yield this.initializeVueComponent(t,e);else{if("function"!=typeof e)throw new Error("Unsupported component type");yield this.initializeSvelteOrVanillaComponent(t,e)}this.innerHTML="",this.appendChild(t),this.isInitialized=!0,s.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw s.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,n){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.React||!window.ReactDOM)throw new Error("React not available globally");{const e=window.React,i=window.ReactDOM,o=this.getWidgetProps(),s=e.createElement(n,o);i.render(s,t)}}))}initializeVueComponent(t,n){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.Vue)throw new Error("Vue not available globally");{const e=window.Vue,i=this.getWidgetProps();new e({el:t,render:e=>e(n,{props:i})})}}))}initializeSvelteOrVanillaComponent(t,n){return e(this,void 0,void 0,(function*(){var e;const i=this.getWidgetProps();if(n.$$prop_def||(null===(e=n.prototype)||void 0===e?void 0:e.$$prop_def))this.svelteComponent=new n({target:t,props:i});else if(n.prototype&&n.prototype.constructor===n){const e=new n(t,i);"function"==typeof e.render&&(yield e.render())}else if("function"==typeof n)yield n(t,i);else{if(!n||"function"!=typeof n.init)throw new Error("Unknown component type");yield n.init(t,i)}}))}getWidgetProps(){var e,t;return{config:(null===(e=this.compositionData)||void 0===e?void 0:e.config)||{},metadata:(null===(t=this.compositionData)||void 0===t?void 0:t.metadata)||{},instance:this.instanceId,element:this,dimensions:{width:this.getAttribute("width")||"100%",height:this.getAttribute("height")||"400"},resize:this.getAttribute("resize")||"responsive",autoscale:"true"===this.getAttribute("autoscale"),adaptive:parseInt(this.getAttribute("adaptive")||"768"),state:this.widgetState,onStateChange:this.handleStateChange.bind(this),onResize:this.handleResize.bind(this),onError:this.handleError.bind(this)}}applyWidgetProperties(e){var t;const n=this.getAttribute("width")||"100%",i=this.getAttribute("height")||"400",o=this.getAttribute("resize")||"responsive";switch(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof i?`${i}px`:i,o){case"fill-width":e.style.width="100%";break;case"responsive":e.style.maxWidth="100%",e.style.height="auto"}e.classList.add(`widgetic-widget-${(null===(t=this.widgetData)||void 0===t?void 0:t.type)||"unknown"}`)}setupResponsiveBehavior(){const e=parseInt(this.getAttribute("adaptive")||"768"),t="true"===this.getAttribute("autoscale"),n=this.getAttribute("resize")||"responsive";t&&"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver((e=>{for(const t of e)this.handleAutoscale(t)})),this.resizeObserver.observe(this)),"responsive"!==n&&"fill-width"!==n||this.setupAdaptiveBehavior(e)}setupAdaptiveBehavior(e){const t=window.matchMedia(`(max-width: ${e}px)`),n=t=>{this.setAttribute("data-mobile",t.matches?"true":"false"),this.dispatchEvent(new CustomEvent("widgetic:adaptive",{detail:{isMobile:t.matches,breakpoint:e}}))};n(t),t.addEventListener("change",n),this.eventListeners.set("adaptive",(()=>{t.removeEventListener("change",n)}))}handleAutoscale(e){const{width:t,height:n}=e.contentRect;this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:t,height:n}})),this.widgetState.data.dimensions={width:t,height:n}}setupEventHandling(){const e=e=>{this.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{type:"click",originalEvent:e},bubbles:!0}))};this.addEventListener("click",e),this.eventListeners.set("click",(()=>{this.removeEventListener("click",e)}));const t=e=>{e.target instanceof HTMLFormElement&&this.handleFormSubmission(e)};this.addEventListener("submit",t),this.eventListeners.set("submit",(()=>{this.removeEventListener("submit",t)}))}handleFormSubmission(e){e.preventDefault();const t=e.target,n=new FormData(t),i={};n.forEach(((e,t)=>{i[t]=e})),this.widgetState.data.formData=i,this.dispatchEvent(new CustomEvent("widgetic:form-submit",{detail:{data:i,form:t},bubbles:!0})),s.debug("Form submitted",{instanceId:this.instanceId,data:i})}handleStateChange(e){this.widgetState.data=Object.assign(Object.assign({},this.widgetState.data),e),this.dispatchEvent(new CustomEvent("widgetic:state-change",{detail:{state:this.widgetState.data},bubbles:!0}))}handleResize(e){this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:e,bubbles:!0}))}handleError(e){this.setErrorState(e)}updateDimensions(){const e=this.querySelector(`.widgetic-content-${this.instanceId}`);e&&this.applyWidgetProperties(e)}updateResizeMode(){this.updateDimensions(),this.setupResponsiveBehavior()}updateAutoscale(){this.setupResponsiveBehavior()}updateAdaptive(){const e=parseInt(this.getAttribute("adaptive")||"768");this.setupAdaptiveBehavior(e)}updateTheme(){this.initializeCSSCustomProperties()}notifyWidgetPropsChanged(){this.svelteComponent&&"function"==typeof this.svelteComponent.$set&&this.svelteComponent.$set(this.getWidgetProps()),this.dispatchEvent(new CustomEvent("widgetic:props-changed",{detail:{props:this.getWidgetProps()}}))}setLoadingState(e){this.widgetState.loading=e,this.setAttribute("data-loading",e?"true":"false"),e&&(this.innerHTML=`\n <div class="widgetic-loading-${this.instanceId}">\n <div>Loading widget...</div>\n </div>\n `)}setWidgetReady(){this.widgetState.ready=!0,this.widgetState.loading=!1,this.widgetState.error=null,this.setAttribute("data-ready","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-error"),this.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:this.instanceId},bubbles:!0})),s.info("Widget ready",{instanceId:this.instanceId})}setErrorState(e){this.widgetState.error=e,this.widgetState.loading=!1,this.widgetState.ready=!1,this.setAttribute("data-error","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-ready"),this.innerHTML=`\n <div class="widgetic-error-${this.instanceId}">\n <strong>Widget Error</strong><br>\n <small>${e.message}</small>\n </div>\n `,this.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:e.message,instanceId:this.instanceId},bubbles:!0})),s.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return e(this,void 0,void 0,(function*(){this.cleanup(),this.isInitialized=!1,this.isWidgetConnected=!1,yield this.connectedCallback()}))}cleanup(){this.svelteComponent&&"function"==typeof this.svelteComponent.$destroy&&(this.svelteComponent.$destroy(),this.svelteComponent=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.eventListeners.forEach((e=>{if("function"==typeof e)try{e()}catch(e){s.warn("Failed to cleanup event listener",{instanceId:this.instanceId,error:e})}})),this.eventListeners.clear();const e=document.getElementById(`widgetic-base-styles-${this.instanceId}`);e&&e.remove(),s.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function te(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",ee),s.info("WidgeticWidget custom element registered")))}const ne="widgetic_autoscale_heights";function ie(e){return""!==e&&"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}function oe(){try{const e=localStorage.getItem(ne);if(!e)return{};const t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}catch(e){return{}}}function se(e,t=Date.now()){if(!ie(e))return null;const n=oe(),i=Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0;if(!i||"number"!=typeof i.height||!Number.isFinite(i.height)||i.height<=0)return null;if("number"!=typeof i.lastUpdated||t-i.lastUpdated>864e5){try{delete n[e],localStorage.setItem(ne,JSON.stringify(n))}catch(e){}return null}return i.height}function re(e,t,n,i=Date.now()){if(ie(e)&&Number.isFinite(t)&&!(t<=0))try{const o=oe();o[e]={compositionId:e,height:t,originalHeight:n,lastUpdated:i},localStorage.setItem(ne,JSON.stringify(o))}catch(e){}}class ae{constructor(){this.observers=new Map,this.mutationObservers=new Map,this.timeouts=new Map,this.animationIds=new Map,this.storageKey=ne}static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}enableAutoScale(e,t,n={enabled:!0}){if(!n.enabled)return;const i=Object.assign({minHeight:n.minHeight||50,maxHeight:n.maxHeight||2e3,debounceDelay:n.debounceDelay||150,threshold:n.threshold||5,animate:!1!==n.animate,animationDuration:n.animationDuration||300},n),o=e.offsetHeight,s=this.getStoredHeight(t);s&&s!==o&&this.setElementHeight(e,s,i.animate,i.animationDuration),this.setupContentMonitoring(e,t,i,o)}disableAutoScale(e){const t=this.observers.get(e);t&&(t.disconnect(),this.observers.delete(e));const n=this.mutationObservers.get(e);n&&(n.disconnect(),this.mutationObservers.delete(e));const i=this.timeouts.get(e);i&&(clearTimeout(i),this.timeouts.delete(e));const o=this.animationIds.get(e);o&&(cancelAnimationFrame(o),this.animationIds.delete(e));const s=document.querySelector(`iframe[data-widgetic-id="${e}"], iframe[data-composition-id="${e}"]`);s&&s._autoscaleMessageCleanup&&(s._autoscaleMessageCleanup(),delete s._autoscaleMessageCleanup)}getStoredHeight(e){return se(e)}storeHeight(e,t,n){re(e,t,n)}setupContentMonitoring(e,t,n,i){const o=this.findContentElement(e);if(!o)return void e.tagName.toLowerCase();const s=this.createDebouncedHeightUpdate(e,t,n,i);if("undefined"!=typeof ResizeObserver){const e=new ResizeObserver((e=>{for(const t of e){const e=t.target.scrollHeight;s(e)}}));e.observe(o),this.observers.set(t,e)}const r=new MutationObserver((()=>{const e=o.scrollHeight;s(e)}));r.observe(o,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,r);const a=o.scrollHeight;s(a)}findContentElement(e){var t;if("iframe"===e.tagName.toLowerCase())try{const n=e,i=n.contentDocument||(null===(t=n.contentWindow)||void 0===t?void 0:t.document);if(null==i?void 0:i.body)return i.body}catch(t){return this.setupIframePostMessageListener(e),null}const n=e.tagName.toLowerCase();if("widgetic"===n||"widgetic-widget"===n||e.classList.contains("widgetic-widget")){return e.querySelector(".widget-content, .widgetic-content, [data-content]")||e}return e}setupIframePostMessageListener(e){const t=e.getAttribute("data-widgetic-id")||e.getAttribute("data-composition-id")||"unknown",n=n=>{var i,o;if(n.source===e.contentWindow&&("widgetic:autoscale"===(null===(i=n.data)||void 0===i?void 0:i.type)||"autoscale"===(null===(o=n.data)||void 0===o?void 0:o.type))){const{height:i,contentHeight:o}=n.data.payload||n.data;if("number"==typeof i&&i>0){const n=this.getConfigForWidget(t),s=Math.max(n.minHeight||50,Math.min(n.maxHeight||2e3,i));this.setElementHeight(e,s,n.animate,n.animationDuration),this.storeHeight(t,s,e.offsetHeight),e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:e.offsetHeight,newHeight:s,contentHeight:o||i}}))}}};window.addEventListener("message",n),e._autoscaleMessageCleanup=()=>{window.removeEventListener("message",n)}}getConfigForWidget(e){return{enabled:!0,minHeight:50,maxHeight:2e3,animate:!0,animationDuration:300,debounceDelay:150,threshold:5}}createDebouncedHeightUpdate(e,t,n,i){let o=e.offsetHeight;return s=>{const r=this.timeouts.get(t);r&&clearTimeout(r);const a=setTimeout((()=>{const r=Math.max(n.minHeight,Math.min(n.maxHeight,s));Math.abs(r-o)>=n.threshold&&(this.setElementHeight(e,r,n.animate,n.animationDuration),this.storeHeight(t,r,i),o=r,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:o,newHeight:r,contentHeight:s}}))),this.timeouts.delete(t)}),n.debounceDelay);this.timeouts.set(t,a)}}setElementHeight(e,t,n=!0,i=300){if(!n)return void(e.style.height=`${t}px`);const o=e.offsetHeight,s=t-o;if(Math.abs(s)<1)return;const r=this.animationIds.get(e.id||e.tagName);r&&cancelAnimationFrame(r);const a=performance.now(),d=o,c=n=>{const o=n-a,r=Math.min(o/i,1),l=1-Math.pow(1-r,3),u=d+s*l;if(e.style.height=`${u}px`,r<1){const t=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},l=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,l)}clearStoredHeights(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStoredHeights(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return{}}}destroy(){this.observers.forEach((e=>e.disconnect())),this.observers.clear(),this.mutationObservers.forEach((e=>e.disconnect())),this.mutationObservers.clear(),this.timeouts.forEach((e=>clearTimeout(e))),this.timeouts.clear(),this.animationIds.forEach((e=>cancelAnimationFrame(e))),this.animationIds.clear()}}class de{constructor(){this.autoScaleManager=ae.getInstance(),te()}render(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:n="100%",height:i="400",resize:o="responsive",autoscale:s=!0,adaptive:r=768,media:a,content:d}=t,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",e),c.setAttribute("width",String(n)),c.setAttribute("height",String(i)),c.setAttribute("resize",o),"boolean"==typeof s?c.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(c.setAttribute("autoscale","true"),void 0!==s.minHeight&&c.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&c.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&c.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&c.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&c.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&c.setAttribute("autoscale-animation-duration",String(s.animationDuration))):c.setAttribute("autoscale","false"),c.setAttribute("adaptive",String(r)),a&&Object.keys(a).length>0){u().registerWidget(e,a),this.setupCustomElementMediaListener(c,e)}if(d&&Object.keys(d).length>0){g().registerWidget(e,d),this.setupCustomElementContentListener(c,e)}return{id:`custom-${e}-${Date.now()}`,element:c,compositionData:{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},widgetData:{id:`widget-${e}`,name:`Widget ${e}`,type:"custom-element",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"custom-element",cleanup:()=>{c._mediaCommandCleanup&&c._mediaCommandCleanup(),c._mediaObserverCleanup&&c._mediaObserverCleanup(),c._contentPositionCleanup&&c._contentPositionCleanup()}}}))}initializeWidget(t,n,i){return e(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(t,n,i){return e(this,void 0,void 0,(function*(){if(n.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const e=window.React,o=window.ReactDOM,s=e.createElement(n,{config:i.config,metadata:i.metadata});o.render(s,t)}else{if(!n._isVue&&!n.__isVue||"undefined"==typeof window||!window.Vue)throw new Error("Framework component detected but framework not available");new(0,window.Vue)({el:t,render:e=>e(n,{props:{config:i.config,metadata:i.metadata}})})}}))}applyElementStyling(e,t,n){const{width:i,height:o,resize:s,autoscale:r,adaptive:a}=n;switch(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof o?`${o}px`:o,e.style.display="block",e.style.overflow="hidden",s){case"fill-width":e.style.width="100%";break;case"responsive":this.makeResponsive(e,a||768)}if(r){("boolean"==typeof r?r:r&&"object"==typeof r&&r.enabled)&&this.enableAutoscale(e,t,r)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const n=window.matchMedia(`(max-width: ${t}px)`),i=()=>{n.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};i(),n.addEventListener?n.addEventListener("change",i):n.addListener(i),e._responsiveCleanup=()=>{n.removeEventListener?n.removeEventListener("change",i):n.removeListener(i)}}enableAutoscale(e,t,n){const i="boolean"==typeof n?{enabled:n}:n;i.enabled&&(this.autoScaleManager.enableAutoScale(e,t,i),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)})}showLoadingState(e){e.innerHTML='\n <div class="widgetic-loading" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n ">\n <div style="text-align: center; color: #6c757d;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #dee2e6;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <small>Loading widget...</small>\n </div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n '}showErrorState(e,t){const n=t instanceof Error?t.message:"Unknown error";e.innerHTML=`\n <div class="widgetic-error" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #c53030;\n ">\n <div style="text-align: center; padding: 20px;">\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Error</div>\n <small style="color: #718096;">${n}</small>\n </div>\n </div>\n `,e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:n}}))}setupCustomElementMediaListener(e,t){const n=u(),i=t=>{const{command:n}=t.detail;if("pause"===n){const t=e.querySelectorAll("audio"),n=e.querySelectorAll("video");t.forEach((e=>{e.paused||e.pause()})),n.forEach((e=>{e.paused||e.pause()}))}else if("play"===n){const t=e.querySelectorAll("audio"),n=e.querySelectorAll("video"),i=Array.from(t).concat(Array.from(n)).find((e=>e.currentTime>0&&!e.ended));i&&i.play().catch((()=>{}))}};e.addEventListener("widgetic:media:command",i),e._mediaCommandCleanup=()=>{e.removeEventListener("widgetic:media:command",i)};const o=(i,o)=>s=>{const r=(e.__widgetConfig||{}).media||{},a="audio"===i.tagName.toLowerCase()?"audio":"video";n.handleMediaEvent({type:o,compositionId:t,config:r,data:{position:i.currentTime,duration:i.duration,volume:i.volume,mediaType:a,title:i.title||i.getAttribute("data-title")||void 0}})},s=()=>{const t=e.querySelectorAll("audio"),n=e.querySelectorAll("video");Array.from(t).concat(Array.from(n)).forEach((e=>{e.addEventListener("play",o(e,"play")),e.addEventListener("pause",o(e,"pause")),e.addEventListener("ended",o(e,"ended")),e.addEventListener("seeked",o(e,"seeking")),e.addEventListener("volumechange",o(e,"volumechange"))}))};s();const r=new MutationObserver((()=>{s()}));r.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{r.disconnect()}}setupCustomElementContentListener(e,t){const n=g(),i=i=>{if(i.detail&&i.detail.type){const o=i.detail.type,s=i.detail.data||i.detail;let r={};try{const t=e.getAttribute("data-content-config");t&&(r=JSON.parse(t))}catch(e){r={contentType:"custom",persistState:!0}}n.handleContentPositionEvent({type:o,compositionId:t,config:r,data:s})}};e.addEventListener("widgetic:content:position",i),e.addEventListener("widgetic:content:navigate",i),e.addEventListener("widgetic:content:complete",i),e.addEventListener("widgetic:content:reset",i),e.addEventListener("widgetic:content:metadata",i),e._contentPositionCleanup=()=>{e.removeEventListener("widgetic:content:position",i),e.removeEventListener("widgetic:content:navigate",i),e.removeEventListener("widgetic:content:complete",i),e.removeEventListener("widgetic:content:reset",i),e.removeEventListener("widgetic:content:metadata",i)}}}var ce=Object.freeze({__proto__:null,CustomElementRenderer:de});const le={close:"Close",closeOverlay:"Close overlay",interactiveWidget:"Interactive widget"},ue=new Map([["fr",{close:"Fermer",closeOverlay:"Fermer la fenêtre",interactiveWidget:"Widget interactif"}],["de",{close:"Schließen",closeOverlay:"Fenster schließen",interactiveWidget:"Interaktives Widget"}],["es",{close:"Cerrar",closeOverlay:"Cerrar ventana",interactiveWidget:"Widget interactivo"}],["pt",{close:"Fechar",closeOverlay:"Fechar janela",interactiveWidget:"Widget interativo"}],["nl",{close:"Sluiten",closeOverlay:"Venster sluiten",interactiveWidget:"Interactieve widget"}],["da",{close:"Luk",closeOverlay:"Luk vinduet",interactiveWidget:"Interaktiv widget"}],["sv",{close:"Stäng",closeOverlay:"Stäng fönstret",interactiveWidget:"Interaktiv widget"}],["zh",{close:"关闭",closeOverlay:"关闭窗口",interactiveWidget:"交互式小组件"}],["ar",{close:"إغلاق",closeOverlay:"إغلاق النافذة",interactiveWidget:"ويجت تفاعلي"}],["he",{close:"סגירה",closeOverlay:"סגירת החלון",interactiveWidget:"וידג'ט אינטראקטיבי"}],["fa",{close:"بستن",closeOverlay:"بستن پنجره",interactiveWidget:"ویجت تعاملی"}],["ur",{close:"بند کریں",closeOverlay:"ونڈو بند کریں",interactiveWidget:"انٹرایکٹو ویجٹ"}]]);function ge(e,t=function(){var e,t;return"undefined"==typeof document?"":(null===(e=document.body)||void 0===e?void 0:e.getAttribute("lang"))||(null===(t=document.documentElement)||void 0===t?void 0:t.getAttribute("lang"))||""}()){const n=function(e){var t,n;const i=(null!=e?e:"").trim().replace(/_/g,"-").toLowerCase().split("-"),o="iw"===i[0]?"he":null!==(t=i[0])&&void 0!==t?t:"",s=null!==(n=i[1])&&void 0!==n?n:"";return("zh"!==o||"tw"!==s&&"hk"!==s&&"hant"!==s)&&ue.has(o)?o:null}(t),i=null===n?void 0:ue.get(n);return(null!=i?i:le)[e]}ue.keys();class pe{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&s.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,n,i){if("undefined"==typeof ResizeObserver)return void s.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,r=n.initialMode||(o<n.breakpoint?"mobile":"desktop"),a={mode:r,breakpoint:n.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,a),this.callbacks.set(e,i);const d=new ResizeObserver((t=>{this.handleResize(e,t,n)}));d.observe(t),this.observers.set(e,d),i(a),s.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:n.breakpoint,initialMode:r,containerWidth:o})}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e));const n=this.observers.get(e);n&&(n.disconnect(),this.observers.delete(e)),this.callbacks.delete(e),this.currentStates.delete(e),s.debug("Widget unregistered from responsive monitoring",{widgetId:e})}getCurrentState(e){return this.currentStates.get(e)||null}checkResponsiveState(e,t){const n=this.currentStates.get(e),i=this.callbacks.get(e);if(!n||!i)return void s.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<n.breakpoint?"mobile":"desktop";if(o!==n.mode){const r={mode:o,breakpoint:n.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,r),i(r),s.info("Responsive state changed manually",{widgetId:e,from:n.mode,to:o,width:t,breakpoint:n.breakpoint})}}handleResize(e,t,n){const i=this.debounceTimers.get(e);i&&clearTimeout(i);const o=setTimeout((()=>{this.processResize(e,t,n),this.debounceTimers.delete(e)}),n.debounceDelay||150);this.debounceTimers.set(e,o)}processResize(e,t,n){const i=this.currentStates.get(e),o=this.callbacks.get(e);if(!i||!o)return;const r=t[t.length-1];if(!r)return;const a=r.contentRect.width,d=a<n.breakpoint?"mobile":"desktop";if(d!==i.mode){const t={mode:d,breakpoint:n.breakpoint,width:a,timestamp:Date.now()};this.currentStates.set(e,t),o(t),s.info("Responsive breakpoint crossed",{widgetId:e,from:i.mode,to:d,width:a,breakpoint:n.breakpoint})}else if(Math.abs(a-i.width)>10){const t=Object.assign(Object.assign({},i),{width:a,timestamp:Date.now()});this.currentStates.set(e,t),s.debug("Container width updated",{widgetId:e,width:a,mode:i.mode,breakpoint:n.breakpoint})}}getRegisteredWidgets(){return Array.from(this.observers.keys())}cleanup(){const e=this.getRegisteredWidgets();for(const t of e)this.unregisterWidget(t);s.debug("ResponsiveManager cleanup complete")}}let me=null;function he(){return me||(me=new pe),me}class fe{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=ae.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:n,height:i,resize:o="fixed",autoscale:r=!1,adaptive:a,responsive:d,container:c,allowFullscreen:l=!0,sandbox:p=this.getDefaultSandboxPermissions(),allowedFeatures:h=this.getDefaultAllowedFeatures(),loading:f="lazy",enableResize:b=!0,compositionData:w,widgetData:v,security:y={},fallback:I={enabled:!0,timeout:1e4,retryCount:3},media:k}=t;if(!n||!i||!c)throw new Error("Missing required parameters: width, height, and container are required");const E=w||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},C=v||{id:E.widgetId,name:`Widget ${e}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]};try{const w=this.createSecureIframe(e,t);w.src=yield this.buildSecureIframeUrl(e,t),w.title=`Widgetic Widget: ${E.name||e}`,w.loading=f,this.applySandboxSecurity(w,p,h),w.width=n.toString(),w.height=i.toString(),w.frameBorder="0",w.scrolling="no",l&&(w.allowFullscreen=!0,w.setAttribute("allowfullscreen","")),w.title=`Widgetic Widget ${e}`,w.setAttribute("aria-label",`${ge("interactiveWidget")}: ${e}`);const v={compositionId:e,renderMode:"iframe",displayMode:"inline",resize:o,width:"number"==typeof n?n:parseInt(n.toString()),height:"number"==typeof i?i:parseInt(i.toString()),autoscale:r,adaptive:a,responsive:d,media:k},x=m.generateIframeCSS(v);x&&(w.style.cssText+=x),this.applyIframeStyling(w,e,{width:n,height:i,resize:o,autoscale:r,adaptive:a}),w.style.visibility="hidden",w.style.opacity="0",w.style.transition="opacity 0.3s ease",this.addLoadingIndicator(c,v),this.setupEnhancedIframeMessaging(w,e,y),this.setupLoadingOptimization(w,e,I);const S="lazy"===f,W=new Promise(((t,n)=>{let i=null;S||(i=setTimeout((()=>{n(new Error(`Iframe load timeout for composition: ${e}`))}),I.timeout||1e4)),w.onload=()=>{i&&clearTimeout(i),this.removeLoadingIndicator(c),w.style.visibility="visible",w.style.opacity="1",t()},w.onerror=()=>{i&&clearTimeout(i),this.removeLoadingIndicator(c),n(new Error(`Failed to load iframe for composition: ${e}`))}}));if(c.appendChild(w),b&&"undefined"!=typeof ResizeObserver){const t=new m({observeResize:!0}),n=`iframe-${e}-${Date.now()}`;w.setAttribute("data-widget-id",n),t.registerWidget(n,w,c,v),w.__resizeHandler=t,w.__widgetId=n}d&&"number"==typeof d&&d>0&&this.setupResponsiveMonitoring(w,c,e,d),this.iframeRegistry.set(e,w),w.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),S||(yield W);const A=`iframe-${e}-${Date.now()}`;if(s.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:n,height:i},resize:o,autoscale:r,responsive:d,sandbox:p.join(" "),features:h.join("; ")}),v.media&&Object.keys(v.media).length>0){u().registerWidget(e,v.media),this.setupIframeMediaListener(w,e)}if(t.content&&Object.keys(t.content).length>0){g().registerWidget(e,t.content),this.setupIframeContentListener(w,e)}return{id:A,element:w,compositionData:E,widgetData:C,renderMode:"iframe",cleanup:()=>this.cleanupWidget(w)}}catch(t){throw s.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(c),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){s.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),n=yield Promise.allSettled(e),i=[];for(let e=0;e<n.length;e++){const o=n[e],r=t[e];if("fulfilled"===o.status)i.push(o.value);else{s.error("Iframe widget rendering failed in batch",{compositionId:r.compositionId,error:o.reason});const e=`error-${r.compositionId}-${Date.now()}`;i.push({id:e,element:this.createErrorElement(r,o.reason),compositionData:{id:r.compositionId,name:`Composition ${r.compositionId}`,widgetId:`widget-${r.compositionId}`,config:{}},widgetData:{id:`widget-${r.compositionId}`,name:`Widget ${r.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return s.info("Iframe batch rendering complete",{total:t.length,successful:i.filter((e=>"IFRAME"===e.element.tagName)).length,failed:i.filter((e=>"IFRAME"!==e.element.tagName)).length}),i}))}createSecureIframe(e,t){var n;const i=document.createElement("iframe");return i.style.border="none",i.style.display="block",i.style.overflow="hidden",i.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),i.setAttribute("crossorigin","anonymous"),(null===(n=t.security)||void 0===n?void 0:n.enableCSP)&&i.setAttribute("csp",this.generateCSP(t.security.allowedOrigins)),i.setAttribute("data-widgetic-id",e),i.setAttribute("data-enhanced","true"),i}getDefaultSandboxPermissions(){return["allow-scripts","allow-same-origin","allow-forms","allow-popups","allow-presentation","allow-downloads"]}getDefaultAllowedFeatures(){return["autoplay","encrypted-media","picture-in-picture","fullscreen","clipboard-read","clipboard-write"]}applySandboxSecurity(e,t,n){e.setAttribute("sandbox",t.join(" ")),e.setAttribute("allow",n.join("; ")),e.setAttribute("fetchpriority","high")}generateCSP(e){const t=e||[r.CLIENT_URL];return[`default-src 'self' ${t.join(" ")}`,`script-src 'self' 'unsafe-inline' ${t.join(" ")}`,`style-src 'self' 'unsafe-inline' ${t.join(" ")}`,`img-src 'self' data: blob: ${t.join(" ")}`,`media-src 'self' blob: ${t.join(" ")}`,"object-src 'none'","base-uri 'self'","form-action 'self'"].join("; ")}buildSecureIframeUrl(t,n){return e(this,void 0,void 0,(function*(){var e;const i=`${r.CLIENT_URL}/embed/${t}`,o=new URLSearchParams;n.width&&o.set("width","number"==typeof n.width?n.width.toString():n.width),n.height&&o.set("height","number"==typeof n.height?n.height.toString():n.height),n.resize&&o.set("resize",n.resize),n.autoscale&&o.set("autoscale","true"),n.adaptive&&o.set("adaptive",n.adaptive.toString()),n.responsive&&"number"==typeof n.responsive&&o.set("responsive",n.responsive.toString()),(null===(e=n.security)||void 0===e?void 0:e.signatureValidation)&&o.set("validateSignature","true"),o.set("sdkVersion","1.0"),o.set("mode","iframe");try{const e=yield a();o.set("apiKey",e)}catch(e){s.warn("Failed to get auth token for iframe",e),r.API_KEY&&o.set("apiKey",r.API_KEY)}const d=`${i}?${o.toString()}`;return s.debug("Built secure iframe URL",{compositionId:t,url:d}),d}))}applyIframeStyling(e,t,n){const{width:i,height:o,resize:s,autoscale:r,adaptive:a}=n;if(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof o?`${o}px`:o,"fill-width"===s)e.style.width="100%",e.style.height="auto",e.style.minHeight="number"==typeof o?`${o}px`:o;r&&this.enableIframeAutoscale(e,t,r),a&&this.makeIframeResponsive(e,a)}makeIframeResponsive(e,t){const n=window.matchMedia(`(max-width: ${t}px)`),i=()=>{n.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};i(),n.addEventListener?n.addEventListener("change",i):n.addListener(i),e._responsiveCleanup=()=>{n.removeEventListener?n.removeEventListener("change",i):n.removeListener(i)}}enableIframeAutoscale(e,t,n){const i="boolean"==typeof n?{enabled:n}:n;i.enabled&&(this.autoScaleManager.enableAutoScale(e,t,i),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)},s.debug("AutoScale enabled for iframe",{compositionId:t,config:i}))}setupLoadingOptimization(e,t,n){if(!n.enabled)return;const i=n.timeout||1e4,o=n.retryCount||3;let r=0;const a=()=>{r<o?(r++,s.warn(`Iframe loading failed, retrying (${r}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+r}),1e3*r)):(s.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},d=setTimeout((()=>{s.warn("Iframe loading timeout",{compositionId:t,timeout:i}),a()}),i);this.loadingTimeouts.set(t,d),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),s.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{s.error("Iframe error occurred",{compositionId:t}),a()}))}handleIframeFallback(e,t){const n=document.createElement("div");n.className="widgetic-iframe-fallback",n.innerHTML='\n <div style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n text-align: center;\n padding: 20px;\n ">\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Unavailable</div>\n <small>The widget could not be loaded. Please try refreshing the page.</small>\n </div>\n </div>\n ',e.parentNode&&(e.parentNode.insertBefore(n,e),e.parentNode.removeChild(e)),n.dispatchEvent(new CustomEvent("widgetic:fallback",{detail:{compositionId:t,reason:"loading_failed"},bubbles:!0}))}setupEnhancedIframeMessaging(e,t,n={}){const i=p({enableSignatureValidation:n.signatureValidation||!1,allowedOrigins:n.allowedOrigins,enableHeartbeat:!0,heartbeatInterval:3e4});i.registerHandler(t,(t=>{this.handleEnhancedIframeMessage(e,t)})),e.addEventListener("load",(()=>{i.sendMessage(t,{type:"config",instanceId:t,payload:{compositionId:t,apiUrl:o(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),s.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=i,e.__messagingCompositionId=t,s.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(s.debug("Enhanced iframe message received",{type:t.type,instanceId:t.instanceId,sequence:t.sequence}),t.type){case"resize":this.handleResizeMessage(e,t);break;case"ready":this.handleReadyMessage(e,t);break;case"error":this.handleErrorMessage(e,t);break;case"data":this.handleDataMessage(e,t);break;case"event":this.handleEventMessage(e,t);break;default:s.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width:n,height:i}=t.payload;n&&i&&(e.style.width=`${n}px`,e.style.height=`${i}px`,e.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:n,height:i,instanceId:t.instanceId},bubbles:!0})),s.debug("Iframe resized",{width:n,height:i,instanceId:t.instanceId}))}handleReadyMessage(e,t){e.setAttribute("data-ready","true"),e.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,payload:t.payload},bubbles:!0})),s.info("Iframe widget ready",{instanceId:t.instanceId})}handleErrorMessage(e,t){e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,error:t.payload.error,code:t.payload.code},bubbles:!0})),s.error("Iframe widget error",{instanceId:t.instanceId,error:t.payload.error})}handleDataMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:data",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,data:t.payload},bubbles:!0})),s.debug("Iframe data received",{instanceId:t.instanceId,dataType:t.payload.type})}handleEventMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,eventType:t.payload.type,eventData:t.payload.data},bubbles:!0})),s.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,n){p().sendMessage(e,{type:t,instanceId:e,payload:n,timestamp:Date.now(),version:"1.0"})}addLoadingIndicator(e,t){const n=document.createElement("div");n.className="widgetic-loading-indicator",n.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${t.width}px;\n height: ${t.height}px;\n background: #f5f5f5;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #e0e0e0;\n border-radius: 4px;\n position: relative;\n `,n.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #666;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div>Loading widget...</div>\n </div>\n ';const i=document.createElement("style");i.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(i),e.appendChild(n)}removeLoadingIndicator(e){const t=e.querySelector(".widgetic-loading-indicator");t&&t.parentNode&&t.parentNode.removeChild(t)}createErrorElement(e,t){const n=document.createElement("div");return n.className="widgetic-error",n.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${e.width}px;\n height: ${e.height}px;\n background: #fff5f5;\n color: #e53e3e;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n text-align: center;\n padding: 16px;\n box-sizing: border-box;\n `,n.innerHTML=`\n <div>\n <div style="font-weight: 600; margin-bottom: 4px;">Widget Error</div>\n <div style="font-size: 12px; opacity: 0.8;">Failed to load composition: ${e.compositionId}</div>\n </div>\n `,n}cleanupWidget(e){const t=e.__resizeHandler,n=e.__widgetId;t&&n&&t.unregisterWidget(n);const i=e.__responsiveManager,o=e.__responsiveId;i&&o&&i.unregisterWidget(o);const r=e.__messenger,a=e.__messagingCompositionId;r&&a&&r.unregisterHandler(a);const d=this.loadingTimeouts.get(a);d&&(clearTimeout(d),this.loadingTimeouts.delete(a)),a&&this.iframeRegistry.delete(a),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),s.debug("Iframe cleanup complete",{compositionId:a})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,n,i){const o=he(),r=p(),a={breakpoint:i,debounceDelay:150},d=`responsive-${n}`;o.registerWidget(d,t,a,(t=>{s.debug("Responsive state changed, notifying iframe",{compositionId:n,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),r.sendMessage(n,{type:"responsive",instanceId:n,compositionId:n,payload:{mode:t.mode,breakpoint:t.breakpoint,width:t.width,timestamp:t.timestamp},timestamp:Date.now(),version:"1.0"}),e.dispatchEvent(new CustomEvent("widgetic:responsive",{detail:{instanceId:n,compositionId:n,mode:t.mode,breakpoint:t.breakpoint,width:t.width},bubbles:!0}))})),e.__responsiveId=d,e.__responsiveManager=o,s.info("Responsive monitoring enabled for iframe",{compositionId:n,breakpoint:i,containerId:d})}setupIframeMediaListener(e,t){const n=u(),i=i=>{var o,s;if(i.source===e.contentWindow&&(null===(s=null===(o=i.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:media:"))){const o=i.data.type.replace("widgetic:media:","");if(["play","pause","stop","ended","seeking","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"].includes(o)){const s=e.getAttribute("data-widget-config"),r=s?JSON.parse(s):{};n.handleMediaEvent({type:o,compositionId:t,config:r.media||{},data:i.data.detail||i.data.payload||i.data.data||{}})}}};window.addEventListener("message",i),e._mediaListenerCleanup=()=>{window.removeEventListener("message",i)}}setupIframeContentListener(e,t){const n=g(),i=i=>{var o,s;if(i.source===e.contentWindow&&(null===(s=null===(o=i.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:content:"))){const o=i.data.type.replace("widgetic:content:","");if(["position","navigate","complete","reset","metadata"].includes(o)){const s=e.getAttribute("data-widgetic-config");let r={};if(s)try{r=JSON.parse(s).content||{}}catch(e){r={contentType:"custom",persistState:!0}}n.handleContentPositionEvent({type:o,compositionId:t,config:r,data:i.data.payload||i.data.data||{}})}}};window.addEventListener("message",i),e._contentListenerCleanup=()=>{window.removeEventListener("message",i)}}}let be=null;var we=Object.freeze({__proto__:null,IframeRenderer:fe,getIframeRenderer:function(){return be||(be=new fe),be}});class ve{constructor(){this.batchClient=t(),this.moduleLoader=n(),this.customElementRenderer=new de,this.iframeRenderer=new fe,this.renderedWidgets=new Map}renderWidget(t){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId),n=this.createLoadingElement(t.container);t.container&&n&&t.container.appendChild(n);try{const i=yield this.batchClient.getComposition(t.compositionId),o=yield this.batchClient.getWidget(i.widgetId),s=this.determineRenderMode(t.renderMode,o);let r;if("custom-element"===s)try{r=yield this.moduleLoader.loadModule(o)}catch(s){const r=yield this.renderWithIframe(e,t,i,o);return this.removeLoadingElement(n),r}const a="iframe"===s?yield this.renderWithIframe(e,t,i,o):yield this.renderWithCustomElement(e,t,i,o,r);return this.removeLoadingElement(n),this.renderedWidgets.set(e,a),this.emitWidgetEvent("ready",{widgetId:e,compositionId:t.compositionId,renderMode:a.renderMode,loadTime:(null==r?void 0:r.loadTime)||0,cached:(null==r?void 0:r.cached)||!1}),a}catch(i){if(this.removeLoadingElement(n),this.emitWidgetEvent("error",{widgetId:e,compositionId:t.compositionId,error:i instanceof Error?i.message:String(i),fallback:"iframe"}),t.container){const e=this.createErrorElement(t.compositionId,i);t.container.appendChild(e)}try{const n=yield this.renderFallback(e,t);if(t.container){const e=t.container.querySelector(".widgetic-error");e&&e.remove()}return n}catch(e){throw new Error(`Widget rendering failed: ${i}. Fallback also failed: ${e}`)}}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){const n=t.map((e=>e.compositionId)),i=yield this.batchClient.getCompositions(n),o=new Map(i.map((e=>[e.id,e]))),s=new Set;for(const e of t)if("iframe"!==e.renderMode){const t=o.get(e.compositionId);t&&t.widgetId&&s.add(t.widgetId)}const r=s.size>0?yield this.batchClient.getWidgets(Array.from(s)):[],a=new Map(r.map((e=>[e.id,e]))),d=r.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));d.length>0&&(yield this.moduleLoader.preloadModules(d));const c=t.map((t=>e(this,void 0,void 0,(function*(){const e=o.get(t.compositionId)||{id:t.compositionId,widgetId:"default",name:"Composition",settings:{},config:{},version:"1.0.0"},n=a.get(e.widgetId)||{id:e.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(t,e,n)}))));return(yield Promise.allSettled(c)).filter((e=>"rejected"!==e.status)).map((e=>e.value))}))}getWidget(e){return this.renderedWidgets.get(e)||null}getAllWidgets(){return Array.from(this.renderedWidgets.values())}refreshWidget(t){return e(this,void 0,void 0,(function*(){const e=this.renderedWidgets.get(t);if(!e)return null;e.cleanup(),this.renderedWidgets.delete(t);const n={compositionId:e.compositionData.id,renderMode:e.renderMode,container:e.element.parentElement||void 0};return this.batchClient.clearCache(),this.moduleLoader.invalidateModule(e.widgetData.id),this.renderWidget(n)}))}cleanupWidget(e){const t=this.renderedWidgets.get(e);t&&(t.cleanup(),this.renderedWidgets.delete(e))}cleanupAll(){const e=Array.from(this.renderedWidgets.values());for(const t of e)t.cleanup();this.renderedWidgets.clear()}getStats(){return{renderedWidgets:this.renderedWidgets.size,batchCache:this.batchClient.getCacheStats(),moduleCache:this.moduleLoader.getCacheStats(),widgets:Array.from(this.renderedWidgets.entries()).map((([e,t])=>({id:e,compositionId:t.compositionData.id,widgetType:t.widgetData.type,renderMode:t.renderMode,hasModule:!!t.loadedModule})))}}renderSingleWidgetWithData(t,n,i){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId);if("custom-element"===this.determineRenderMode(t.renderMode,i))try{const o=yield this.moduleLoader.loadModule(i);return this.renderWithCustomElement(e,t,n,i,o)}catch(e){}return this.renderWithIframe(e,t,n,i)}))}renderWithCustomElement(t,n,i,o,s){return e(this,void 0,void 0,(function*(){const e=yield this.customElementRenderer.render({compositionId:n.compositionId,compositionData:i,widgetData:o,loadedModule:s,width:n.width,height:n.height,resize:n.resize,autoscale:n.autoscale,adaptive:n.adaptive});return n.container&&n.container.appendChild(e.element),{id:t,element:e.element,compositionData:i,widgetData:o,loadedModule:s,renderMode:"custom-element",cleanup:()=>{e.element.remove()}}}))}renderWithIframe(t,n,i,o){return e(this,void 0,void 0,(function*(){return yield this.iframeRenderer.renderWidget({compositionId:n.compositionId,compositionData:i,widgetData:o,width:n.width,height:n.height,resize:n.resize,autoscale:n.autoscale,adaptive:n.adaptive,container:n.container})}))}renderFallback(t,n){return e(this,void 0,void 0,(function*(){const e=document.createElement("div");return e.className="widgetic-fallback",e.innerHTML=`\n <div style="\n padding: 20px; \n text-align: center; \n background: #f5f5f5; \n border: 1px solid #ddd; \n border-radius: 4px;\n color: #666;\n ">\n <p>Widget temporarily unavailable</p>\n <small>Composition ID: ${n.compositionId}</small>\n </div>\n `,n.container&&n.container.appendChild(e),{id:t,element:e,compositionData:{id:n.compositionId,name:"Fallback",widgetId:"fallback",config:{}},widgetData:{id:"fallback",name:"Fallback Widget",type:"fallback",version:"1.0.0",moduleUrl:""},renderMode:"iframe",cleanup:()=>{e.remove()}}}))}determineRenderMode(e="auto",t){var n;if("auto"!==e)return e;const i="undefined"!=typeof customElements&&"function"==typeof customElements.define,o=(null==t?void 0:t.moduleUrl)||(null===(n=null==t?void 0:t.metadata)||void 0===n?void 0:n.supportsCustomElements);return i&&o?"custom-element":"iframe"}generateWidgetId(e){return`widget-${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}emitWidgetEvent(e,t){const n=new CustomEvent(`widgetic:${e}`,{detail:t,bubbles:!0});document.dispatchEvent(n)}createLoadingElement(e){if(!e)return null;const t=document.createElement("div");return t.className="widgetic-loading",t.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n ",t.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #f3f3f3;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div style="font-size: 14px;">Loading widget...</div>\n </div>\n ',this.addLoadingStyles(),t}removeLoadingElement(e){e&&e.parentNode&&e.parentNode.removeChild(e)}createErrorElement(e,t){const n=document.createElement("div");n.className="widgetic-error",n.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n padding: 20px;\n text-align: center;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #742a2a;\n ";const i=t instanceof Error?t.message:"Unknown error occurred",o=this.analyzeError(i,t);return n.innerHTML=`\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">${o.icon}</div>\n <div style="font-weight: 500; margin-bottom: 8px;">${o.title}</div>\n <div style="font-size: 14px; margin-bottom: 12px; color: #666;">\n ${o.description}\n </div>\n <div style="font-size: 12px; margin-bottom: 16px; color: #888;">\n Widget ID: ${e}\n </div>\n ${o.actionHtml}\n </div>\n `,n}analyzeError(e,t){const n=e.toLowerCase();return n.includes("composition not found")||n.includes("404")?{icon:"🔍",title:"Widget Not Found",description:"This widget may have been removed or the ID is incorrect.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Not%20Found%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThe%20widget%20could%20not%20be%20found.%20Please%20check%20if%20it%20was%20deleted%20or%20if%20the%20ID%20is%20correct.', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("unauthorized")||n.includes("forbidden")||n.includes("401")||n.includes("403")||n.includes("permission")||n.includes("access denied")?{icon:"🔒",title:"Access Restricted",description:"This widget requires an active subscription or has been restricted.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ Upgrade Plan\n </a>\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Access%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20am%20having%20trouble%20accessing%20this%20widget.%20Please%20check%20my%20account%20status%20and%20permissions.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("deleted")||n.includes("expired")||n.includes("no longer available")?{icon:"🗑️",title:"Widget Deleted",description:"This widget has been permanently removed.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Deleted%20Widget%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThis%20widget%20appears%20to%20have%20been%20deleted.%20Can%20you%20help%20me%20restore%20it%20or%20find%20an%20alternative?', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("subscription")||n.includes("billing")||n.includes("payment")||n.includes("plan")||n.includes("downgrade")?{icon:"💳",title:"Subscription Required",description:"This widget requires an active subscription to display.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ View Plans\n </a>\n <a \n href="https://widgetic.com/dashboard/billing" \n target="_blank"\n style="\n background: #6c757d;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#5a6268'"\n onmouseout="this.style.background='#6c757d'"\n >\n 💳 Billing\n </a>\n </div>\n <div style="font-size: 12px; color: #888; margin-top: 8px;">\n Need help? Contact support below\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Subscription%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20need%20help%20with%20my%20subscription%20to%20access%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 4px 8px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 11px;\n margin-top: 4px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:n.includes("timeout")||n.includes("network")||n.includes("connection")||n.includes("fetch")?{icon:"🌐",title:"Connection Issue",description:"Unable to load widget due to network connectivity.",actionHtml:`\n <button \n onclick="window.location.reload()"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n 🔄 Retry\n </button>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Connection%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}%0A%0AI%20am%20experiencing%20connection%20issues%20loading%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:{icon:"⚠️",title:"Widget Unavailable",description:e||"An unknown error occurred while loading this widget.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Error%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n <div style="margin-top: 8px;">\n <button \n onclick="window.location.reload()"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n margin-left: 8px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 🔄 Refresh Page\n </button>\n </div>\n `}}addLoadingStyles(){const e="widgetic-loading-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(t)}}let ye=null;function Ie(){return ye||(ye=new ve),ye}function ke(){ye&&ye.cleanupAll(),ye=null}var Ee=Object.freeze({__proto__:null,WidgetRenderer:ve,getWidgetRenderer:Ie,resetWidgetRenderer:ke});export{de as C,fe as I,ee as W,J as a,Z as b,Q as c,ge as d,te as e,ve as f,Ie as g,se as h,ke as i,ce as j,we as k,Ee as l,K as p,G as r,b as s,re as w};
@@ -1 +1 @@
1
- import{j as n,k as r,i as l,G as w,l as b,m as T,n as R,E as D}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,o as ModuleLoader,p as analyzeWidgetCSS,q as disableCSSDebug,t as enableCSSDebug,g as getBatchClient,a as getModuleLoader,u as monitorWidgetCSS,v as resetBatchClient,x as resetModuleLoader,y as sendWorkflowEvent}from"./chunks/api.js";import{l as _,g as O,C as W,V as N,u as V,e as z,t as P,a as Q,T as U,d as G}from"./chunks/core.js";export{v as AuthError,A as AuthManager,j as DefaultTokenProvider,E as EndpointTokenProvider,F as FunctionTokenProvider,S as StaticApiKeyProvider,m as getApiUrl,x as getAuthManager,c as getCdnUrl,h as getConfiguration,k as getTokenProvider,i as setApiKey,s as setTokenProvider}from"./chunks/core.js";import{e as K,W as $}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,f as WidgetRenderer,g as getWidgetRenderer,i as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as Y}from"./chunks/ABTestManager.js";import{_ as J}from"./chunks/vendor.js";import{k as X}from"./chunks/scanner.js";export{e as detectBrowserCapabilities,j as determineBestRenderMode,f as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";export{d as toCamel,t as toSnake}from"./chunks/advanced.js";import"./chunks/media.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";class Z{constructor(e){this.deviceDetector=n(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},e),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),_.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Z.instance&&e&&(Z.instance=new Z(e)),!Z.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Z.instance}static peekInstance(){var e;return null!==(e=Z.instance)&&void 0!==e?e:null}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){_.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){_.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(_.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),_.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):_.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return J(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),_.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){_.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return J(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void _.warn("[AnalyticsTracker] No API endpoint configured");const t=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),i=yield O(),n=new W({basePath:this.config.apiEndpoint,accessToken:()=>J(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${N}`}}),s=new V(n);yield s.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:t}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){_.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],_.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){_.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),_.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),_.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),Z.instance=null,_.debug("[AnalyticsTracker] Destroyed")}}const ee="undefined"!=typeof HTMLElement?HTMLElement:class{};class te extends ee{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.renderedVariantId=null,this.isRecording=!1,this.hasStarted=!1,this.currentRunId=0,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.manager=Y.getInstance(),this.widgetManager=r.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id","consent"]}connectedCallback(){return J(this,void 0,void 0,(function*(){this.hasStarted=!0,yield this.start()}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){this.hasStarted&&this.isConnected&&t!==i&&("experiment-id"===e?(this.cleanup(),this.start()):"consent"===e&&this.start())}readConsent(){const e=this.getAttribute("consent");return null===e||"granted"===e?"granted":"denied"===e?"denied":"pending"}start(){return J(this,void 0,void 0,(function*(){const e=++this.currentRunId,t=()=>e!==this.currentRunId;try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return z.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");"granted"===this.readConsent()?yield this.startRecorded(t):yield this.startUnrecorded(t)}catch(e){z.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}startRecorded(e){return J(this,void 0,void 0,(function*(){const t=this.experimentId;this.manager.resumeRecording(t);const i={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};this.renderedVariantId||this.renderLoading();const n=yield this.manager.getVariantAssignment(t,i);if(!e()){if(!n)return z.warn("No variant assignment received",{experimentId:t}),this.assignment=null,this.isRecording=!1,void this.renderError("Test not available");if(this.assignment=n,this.isRecording=!0,this.impressionTracked=!1,this.setupGoalListeners(),this.renderedVariantId===n.variantId)this.announceVariant();else if(yield this.renderVariant(),e())return;yield this.trackImpression(),this.setupConversionTracking(),this.applyWidgetReadiness(),z.info("A/B test element initialized",{experimentId:t,variantId:n.variantId})}}))}startUnrecorded(e){return J(this,void 0,void 0,(function*(){const t=this.experimentId,i=this.readConsent();this.isRecording=!1,this.removeConversionListeners(),this.impressionTracked=!1,this.manager.holdRecording(t),"denied"===i&&this.manager.forgetVisitor(t,{userId:this.getAttribute("user-id")||void 0}),this.renderedVariantId||this.renderLoading(),this.setupGoalListeners();const n=yield this.manager.getUnrecordedVariant(t);if(!e()){if(!n)return z.warn("No original version received for the A/B test",{experimentId:t}),this.assignment=null,void this.renderError("Test not available");this.assignment=n,this.renderedVariantId===n.variantId?this.announceVariant():yield this.renderVariant(),z.info("A/B test element shows the original version: analytics is not allowed",{experimentId:t,variantId:n.variantId,consent:i})}}))}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return J(this,void 0,void 0,(function*(){var e,t;if(!this.assignment||!this.shadowRoot)return;const i=this.assignment,n=this.currentRunId;try{this.removeWidgetInstance(),this.widgetReportsGoals=!1,this.readyWidgetHost=null;const s=document.createElement("div");s.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",i.variantId);const a=this.createEmbedElement(i.embedCode,i.variantId);if(a){s.appendChild(a);const r={compositionId:i.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};if(this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${i.variantId}_${Date.now()}`,r,a),n!==this.currentRunId)return void this.removeWidgetInstance();this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",i.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(s),this.renderedVariantId=i.variantId,a&&this.sendGoalToWidget(a),this.announceVariant()}catch(e){z.error("Failed to render variant",{experimentId:this.experimentId,variantId:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}announceVariant(){this.assignment&&this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId,recorded:this.isRecording},bubbles:!0}))}removeWidgetInstance(){if(this.widgetInstance){try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){z.warn("Failed to cleanup widget instance",{error:e})}this.widgetInstance=null}}createEmbedElement(e,t){try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return z.warn("No element found in embed code",{embedCode:e}),null;const s=n.cloneNode(!0);return s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",t),s}catch(t){return z.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),z.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){z.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target,n=this.assignment.goalTarget||null;(n?P(i,n):this.isClickableElement(i))&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",Object.assign(Object.assign({element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||""},n?{goalTarget:n}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"FORM"!==t.tagName||i&&!P(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",Object.assign(Object.assign({formId:t.id||"unknown"},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||i&&!P(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",Object.assign(Object.assign({mediaType:t.tagName.toLowerCase(),duration:t.duration||0},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}sendGoalToWidget(e){var t;if(this.experimentId&&this.assignment&&this.isRecording)try{const i=this.manager.getPrimaryMetric(this.experimentId);if(!i)return;null===(t=l(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){z.warn("Failed to tell the widget its A/B test goal",{experimentId:this.experimentId,error:e})}}applyWidgetReadiness(){this.experimentId&&this.assignment&&this.isRecording&&this.readyWidgetHost&&(this.manager.setWidgetReportsGoals(this.experimentId,this.widgetReportsGoals),this.assignment.goalTarget&&!this.widgetReportsGoals&&z.warn("This widget cannot report which element was used: the goal counts any use of its metric",{experimentId:this.experimentId,goalTarget:this.assignment.goalTarget}),this.sendGoalToWidget(this.readyWidgetHost))}setupGoalListeners(){if(!this.shadowRoot||this.conversionListeners.has("goal"))return;const e=this.shadowRoot,t=e=>{var t;const i=null===(t=e.detail)||void 0===t?void 0:t.capabilities;this.widgetReportsGoals=Array.isArray(i)&&i.includes(w),this.readyWidgetHost=e.target,this.applyWidgetReadiness()},i=e=>{if(!this.experimentId||!this.assignment||!this.isRecording)return;const t=e.detail||{},i=t.metric||this.manager.getPrimaryMetric(this.experimentId);i&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,i,{goalTarget:t.goalTarget,timestamp:Date.now()})},n=e=>t=>{var i;if(!this.experimentId||!this.assignment||!this.isRecording)return;const n=null===(i=t.detail)||void 0===i?void 0:i.type;"clicks"===e&&void 0!==n&&"click"!==n||this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,{timestamp:Date.now()})},s=n("clicks"),a=n("submissions"),r=n("plays");e.addEventListener("widgetic:ready",t),e.addEventListener("widgetic:goal",i),e.addEventListener("widgetic:interaction",s),e.addEventListener("widgetic:form-submit",a),e.addEventListener("widgetic:media:play",r),this.conversionListeners.set("goal",(()=>{e.removeEventListener("widgetic:ready",t),e.removeEventListener("widgetic:goal",i),e.removeEventListener("widgetic:interaction",s),e.removeEventListener("widgetic:form-submit",a),e.removeEventListener("widgetic:media:play",r)}))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return J(this,void 0,void 0,(function*(){var e;if(this.impressionTracked||!this.isRecording||!this.experimentId||!this.assignment)return;const t=this.experimentId,i=this.assignment;try{const n={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};this.impressionTracked=!0,yield this.manager.trackImpression(t,i.variantId,n),null===(e=Z.peekInstance())||void 0===e||e.trackCompositionView({experiment_id:t,variant_id:i.variantId,composition_id:i.compositionId}),z.debug("Impression tracked",{experimentId:t,variantId:i.variantId})}catch(e){z.error("Failed to track impression",{experimentId:t,error:e})}}))}handleConversionEvent(e){var t;this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),null===(t=Z.peekInstance())||void 0===t||t.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;z.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;z.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.renderedVariantId=null,this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}removeConversionListeners(e=!1){this.conversionListeners.forEach(((t,i)=>{("goal"!==i||e)&&(t(),this.conversionListeners.delete(i))}))}cleanup(){this.currentRunId++,this.removeConversionListeners(!0),this.removeWidgetInstance(),this.impressionTracked=!1,this.isRecording=!1,this.renderedVariantId=null,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.assignment=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.isRecording?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):(z.debug("Conversion not recorded: the visitor has not allowed analytics",{experimentId:this.experimentId}),Promise.resolve()):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",te))}}te.register();const ie="undefined"!=typeof HTMLElement?HTMLElement:class{};class ne extends ie{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.viewIsWaitingForConsent=!1,this.widgetManager=b(),_.debug("[TranslationElement] Created translation element")}static get observedAttributes(){return["consent"]}attributeChangedCallback(e,t,i){"consent"===e&&t!==i&&this.isAnalyticsAllowed()&&this.viewIsWaitingForConsent&&(this.viewIsWaitingForConsent=!1,this.trackTranslationView())}isAnalyticsAllowed(){const e=this.getAttribute("consent");return null===e||"granted"===e}connectedCallback(){if(this.isInitialized)_.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return _.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");_.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){_.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return J(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(_.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),_.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),_.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){_.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return J(this,void 0,void 0,(function*(){try{const t=Q(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw _.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";_.debug("[TranslationElement] Available languages:",i),_.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return _.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return _.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{_.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}_.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{_.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return J(this,void 0,void 0,(function*(){const t=X(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){if(!this.isAnalyticsAllowed())return this.viewIsWaitingForConsent=!0,void _.debug("[TranslationElement] View not reported: analytics is not allowed yet");try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{_.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){_.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return J(this,void 0,void 0,(function*(){if(this.isAnalyticsAllowed())try{const t=Q(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){_.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return J(this,void 0,void 0,(function*(){try{const n={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:i,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(n),_.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){_.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return J(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,_.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){_.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",ne),_.info("[TranslationElement] Custom element registered")))}catch(e){_.error("[TranslationElement] Failed to register custom element:",e)}}}ne.register();const se=T();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(K(),te.register(),ne.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=se,window.Widgetic={SDK:se,getSDK:T,EmbedSDK:D,config:{API_URL:G.API_URL,API_VERSION:G.API_VERSION,CLIENT_URL:G.CLIENT_URL,PRODUCTION_URL:G.PRODUCTION_URL,NODE_ENV:G.NODE_ENV},log:_,WidgeticWidget:$,registerWidgeticWidget:K,cssDebugger:R,enableCSSDebug:()=>R.enableDebugMode(),disableCSSDebug:()=>R.disableDebugMode(),analyzeWidget:e=>R.analyzeWidget(e),ABTestManager:Y,ABTestElement:te,TranslationElement:ne});export{te as ABTestElement,Y as ABTestManager,D as EmbedSDK,ne as TranslationElement,D as WidgeticEmbedSDK,$ as WidgeticWidget,G as config,R as cssDebugger,se as default,X as generateInstanceId,O as getAuthToken,T as getSDK,_ as log,K as registerWidgeticWidget};
1
+ import{j as n,k as r,i as l,G as w,l as b,m as T,n as R,E as D}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,o as ModuleLoader,p as analyzeWidgetCSS,q as disableCSSDebug,t as enableCSSDebug,g as getBatchClient,a as getModuleLoader,u as monitorWidgetCSS,v as resetBatchClient,x as resetModuleLoader,y as sendWorkflowEvent}from"./chunks/api.js";import{l as _,g as O,C as W,V as N,u as V,e as z,t as P,a as Q,T as U,d as G}from"./chunks/core.js";export{v as AuthError,A as AuthManager,j as DefaultTokenProvider,E as EndpointTokenProvider,F as FunctionTokenProvider,S as StaticApiKeyProvider,m as getApiUrl,x as getAuthManager,c as getCdnUrl,h as getConfiguration,k as getTokenProvider,i as setApiKey,s as setTokenProvider}from"./chunks/core.js";import{e as K,W as $}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,f as WidgetRenderer,g as getWidgetRenderer,i as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as Y}from"./chunks/ABTestManager.js";import{_ as J}from"./chunks/vendor.js";import{k as X}from"./chunks/scanner.js";export{e as detectBrowserCapabilities,j as determineBestRenderMode,f as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";export{t as toCamel,d as toSnake}from"./chunks/advanced.js";import"./chunks/media.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";class Z{constructor(e){this.deviceDetector=n(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},e),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),_.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Z.instance&&e&&(Z.instance=new Z(e)),!Z.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Z.instance}static peekInstance(){var e;return null!==(e=Z.instance)&&void 0!==e?e:null}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){_.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){_.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(_.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),_.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):_.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return J(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),_.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){_.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return J(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void _.warn("[AnalyticsTracker] No API endpoint configured");const t=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),i=yield O(),n=new W({basePath:this.config.apiEndpoint,accessToken:()=>J(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${N}`}}),s=new V(n);yield s.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:t}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){_.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],_.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){_.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),_.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),_.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),Z.instance=null,_.debug("[AnalyticsTracker] Destroyed")}}const ee="undefined"!=typeof HTMLElement?HTMLElement:class{};class te extends ee{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.renderedVariantId=null,this.isRecording=!1,this.hasStarted=!1,this.currentRunId=0,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.manager=Y.getInstance(),this.widgetManager=r.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id","consent"]}connectedCallback(){return J(this,void 0,void 0,(function*(){this.hasStarted=!0,yield this.start()}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){this.hasStarted&&this.isConnected&&t!==i&&("experiment-id"===e?(this.cleanup(),this.start()):"consent"===e&&this.start())}readConsent(){const e=this.getAttribute("consent");return null===e||"granted"===e?"granted":"denied"===e?"denied":"pending"}start(){return J(this,void 0,void 0,(function*(){const e=++this.currentRunId,t=()=>e!==this.currentRunId;try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return z.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");"granted"===this.readConsent()?yield this.startRecorded(t):yield this.startUnrecorded(t)}catch(e){z.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}startRecorded(e){return J(this,void 0,void 0,(function*(){const t=this.experimentId;this.manager.resumeRecording(t);const i={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};this.renderedVariantId||this.renderLoading();const n=yield this.manager.getVariantAssignment(t,i);if(!e()){if(!n)return z.warn("No variant assignment received",{experimentId:t}),this.assignment=null,this.isRecording=!1,void this.renderError("Test not available");if(this.assignment=n,this.isRecording=!0,this.impressionTracked=!1,this.setupGoalListeners(),this.renderedVariantId===n.variantId)this.announceVariant();else if(yield this.renderVariant(),e())return;yield this.trackImpression(),this.setupConversionTracking(),this.applyWidgetReadiness(),z.info("A/B test element initialized",{experimentId:t,variantId:n.variantId})}}))}startUnrecorded(e){return J(this,void 0,void 0,(function*(){const t=this.experimentId,i=this.readConsent();this.isRecording=!1,this.removeConversionListeners(),this.impressionTracked=!1,this.manager.holdRecording(t),"denied"===i&&this.manager.forgetVisitor(t,{userId:this.getAttribute("user-id")||void 0}),this.renderedVariantId||this.renderLoading(),this.setupGoalListeners();const n=yield this.manager.getUnrecordedVariant(t);if(!e()){if(!n)return z.warn("No original version received for the A/B test",{experimentId:t}),this.assignment=null,void this.renderError("Test not available");this.assignment=n,this.renderedVariantId===n.variantId?this.announceVariant():yield this.renderVariant(),z.info("A/B test element shows the original version: analytics is not allowed",{experimentId:t,variantId:n.variantId,consent:i})}}))}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return J(this,void 0,void 0,(function*(){var e,t;if(!this.assignment||!this.shadowRoot)return;const i=this.assignment,n=this.currentRunId;try{this.removeWidgetInstance(),this.widgetReportsGoals=!1,this.readyWidgetHost=null;const s=document.createElement("div");s.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",i.variantId);const a=this.createEmbedElement(i.embedCode,i.variantId);if(a){s.appendChild(a);const r={compositionId:i.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};if(this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${i.variantId}_${Date.now()}`,r,a),n!==this.currentRunId)return void this.removeWidgetInstance();this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",i.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(s),this.renderedVariantId=i.variantId,a&&this.sendGoalToWidget(a),this.announceVariant()}catch(e){z.error("Failed to render variant",{experimentId:this.experimentId,variantId:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}announceVariant(){this.assignment&&this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId,recorded:this.isRecording},bubbles:!0}))}removeWidgetInstance(){if(this.widgetInstance){try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){z.warn("Failed to cleanup widget instance",{error:e})}this.widgetInstance=null}}createEmbedElement(e,t){try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return z.warn("No element found in embed code",{embedCode:e}),null;const s=n.cloneNode(!0);return s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",t),s}catch(t){return z.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),z.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){z.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target,n=this.assignment.goalTarget||null;(n?P(i,n):this.isClickableElement(i))&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",Object.assign(Object.assign({element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||""},n?{goalTarget:n}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"FORM"!==t.tagName||i&&!P(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",Object.assign(Object.assign({formId:t.id||"unknown"},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||i&&!P(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",Object.assign(Object.assign({mediaType:t.tagName.toLowerCase(),duration:t.duration||0},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}sendGoalToWidget(e){var t;if(this.experimentId&&this.assignment&&this.isRecording)try{const i=this.manager.getPrimaryMetric(this.experimentId);if(!i)return;null===(t=l(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){z.warn("Failed to tell the widget its A/B test goal",{experimentId:this.experimentId,error:e})}}applyWidgetReadiness(){this.experimentId&&this.assignment&&this.isRecording&&this.readyWidgetHost&&(this.manager.setWidgetReportsGoals(this.experimentId,this.widgetReportsGoals),this.assignment.goalTarget&&!this.widgetReportsGoals&&z.warn("This widget cannot report which element was used: the goal counts any use of its metric",{experimentId:this.experimentId,goalTarget:this.assignment.goalTarget}),this.sendGoalToWidget(this.readyWidgetHost))}setupGoalListeners(){if(!this.shadowRoot||this.conversionListeners.has("goal"))return;const e=this.shadowRoot,t=e=>{var t;const i=null===(t=e.detail)||void 0===t?void 0:t.capabilities;this.widgetReportsGoals=Array.isArray(i)&&i.includes(w),this.readyWidgetHost=e.target,this.applyWidgetReadiness()},i=e=>{if(!this.experimentId||!this.assignment||!this.isRecording)return;const t=e.detail||{},i=t.metric||this.manager.getPrimaryMetric(this.experimentId);i&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,i,{goalTarget:t.goalTarget,timestamp:Date.now()})},n=e=>t=>{var i;if(!this.experimentId||!this.assignment||!this.isRecording)return;const n=null===(i=t.detail)||void 0===i?void 0:i.type;"clicks"===e&&void 0!==n&&"click"!==n||this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,{timestamp:Date.now()})},s=n("clicks"),a=n("submissions"),r=n("plays");e.addEventListener("widgetic:ready",t),e.addEventListener("widgetic:goal",i),e.addEventListener("widgetic:interaction",s),e.addEventListener("widgetic:form-submit",a),e.addEventListener("widgetic:media:play",r),this.conversionListeners.set("goal",(()=>{e.removeEventListener("widgetic:ready",t),e.removeEventListener("widgetic:goal",i),e.removeEventListener("widgetic:interaction",s),e.removeEventListener("widgetic:form-submit",a),e.removeEventListener("widgetic:media:play",r)}))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return J(this,void 0,void 0,(function*(){var e;if(this.impressionTracked||!this.isRecording||!this.experimentId||!this.assignment)return;const t=this.experimentId,i=this.assignment;try{const n={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};this.impressionTracked=!0,yield this.manager.trackImpression(t,i.variantId,n),null===(e=Z.peekInstance())||void 0===e||e.trackCompositionView({experiment_id:t,variant_id:i.variantId,composition_id:i.compositionId}),z.debug("Impression tracked",{experimentId:t,variantId:i.variantId})}catch(e){z.error("Failed to track impression",{experimentId:t,error:e})}}))}handleConversionEvent(e){var t;this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),null===(t=Z.peekInstance())||void 0===t||t.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;z.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;z.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.renderedVariantId=null,this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}removeConversionListeners(e=!1){this.conversionListeners.forEach(((t,i)=>{("goal"!==i||e)&&(t(),this.conversionListeners.delete(i))}))}cleanup(){this.currentRunId++,this.removeConversionListeners(!0),this.removeWidgetInstance(),this.impressionTracked=!1,this.isRecording=!1,this.renderedVariantId=null,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.assignment=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.isRecording?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):(z.debug("Conversion not recorded: the visitor has not allowed analytics",{experimentId:this.experimentId}),Promise.resolve()):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",te))}}te.register();const ie="undefined"!=typeof HTMLElement?HTMLElement:class{};class ne extends ie{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.viewIsWaitingForConsent=!1,this.widgetManager=b(),_.debug("[TranslationElement] Created translation element")}static get observedAttributes(){return["consent"]}attributeChangedCallback(e,t,i){"consent"===e&&t!==i&&this.isAnalyticsAllowed()&&this.viewIsWaitingForConsent&&(this.viewIsWaitingForConsent=!1,this.trackTranslationView())}isAnalyticsAllowed(){const e=this.getAttribute("consent");return null===e||"granted"===e}connectedCallback(){if(this.isInitialized)_.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return _.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");_.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){_.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return J(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(_.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),_.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),_.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){_.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return J(this,void 0,void 0,(function*(){try{const t=Q(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw _.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";_.debug("[TranslationElement] Available languages:",i),_.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return _.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return _.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{_.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}_.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{_.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return J(this,void 0,void 0,(function*(){const t=X(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){if(!this.isAnalyticsAllowed())return this.viewIsWaitingForConsent=!0,void _.debug("[TranslationElement] View not reported: analytics is not allowed yet");try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{_.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){_.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return J(this,void 0,void 0,(function*(){if(this.isAnalyticsAllowed())try{const t=Q(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){_.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return J(this,void 0,void 0,(function*(){try{const n={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:i,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(n),_.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){_.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return J(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,_.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){_.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",ne),_.info("[TranslationElement] Custom element registered")))}catch(e){_.error("[TranslationElement] Failed to register custom element:",e)}}}ne.register();const se=T();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(K(),te.register(),ne.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=se,window.Widgetic={SDK:se,getSDK:T,EmbedSDK:D,config:{API_URL:G.API_URL,API_VERSION:G.API_VERSION,CLIENT_URL:G.CLIENT_URL,PRODUCTION_URL:G.PRODUCTION_URL,NODE_ENV:G.NODE_ENV},log:_,WidgeticWidget:$,registerWidgeticWidget:K,cssDebugger:R,enableCSSDebug:()=>R.enableDebugMode(),disableCSSDebug:()=>R.disableDebugMode(),analyzeWidget:e=>R.analyzeWidget(e),ABTestManager:Y,ABTestElement:te,TranslationElement:ne});export{te as ABTestElement,Y as ABTestManager,D as EmbedSDK,ne as TranslationElement,D as WidgeticEmbedSDK,$ as WidgeticWidget,G as config,R as cssDebugger,se as default,X as generateInstanceId,O as getAuthToken,T as getSDK,_ as log,K as registerWidgeticWidget};