@widgetic/embed-sdk 2.0.11 → 2.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +122 -0
- package/README.md +3 -1
- package/dist/browser/chunks/advanced.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/display.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/advanced.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/display.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/utils/chrome-labels.d.ts +26 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +3 -2
- package/dist/esm/types/utils/mount-direct-widget.d.ts +25 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +6 -0
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as e}from"./core.js";import{_ as t}from"./vendor.js";import{c as i}from"./advanced.js";class n{constructor(e={}){this.options=e,this.resizeObserver=null,this.instances=new Map,this.debounceTimers=new Map,this.options=Object.assign({observeResize:!0,debounceMs:100,enableAdaptive:!0},e),this.options.observeResize&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.handleResize.bind(this)))}registerWidget(t,i,n,s){const o={widgetId:t,element:i,container:n,config:s,originalWidth:s.width,originalHeight:s.height,aspectRatio:s.width/s.height,isObserving:!1};this.instances.set(t,o),this.applyResizeMode(o),this.resizeObserver&&this.options.observeResize&&(this.resizeObserver.observe(n),o.isObserving=!0),e.debug("Widget registered for resize handling",{widgetId:t,resizeMode:s.resize,originalSize:{width:s.width,height:s.height}})}unregisterWidget(t){const i=this.instances.get(t);if(!i)return;this.resizeObserver&&i.isObserving&&this.resizeObserver.unobserve(i.container);const n=this.debounceTimers.get(t);n&&(clearTimeout(n),this.debounceTimers.delete(t)),this.instances.delete(t),e.debug("Widget unregistered from resize handling",{widgetId:t})}static generateIframeCSS(e){const{resize:t,width:i,height:n,autoscale:s}=e;let o="";switch(t){case"fill-width":o=`\n width: 100% !important;\n height: ${n/i*100}vw !important;\n max-height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fill-height":o=`\n height: 100% !important;\n width: ${i/n*100}vh !important;\n max-width: ${i}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed":default:o=`\n width: ${i}px !important;\n height: ${n}px !important;\n flex-shrink: 0;\n object-fit: cover;\n `;break;case"fixed-height":o=`\n width: 100% !important;\n height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed-width":o=`\n width: ${i}px !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"allow-scale-down":o=`\n max-width: ${i}px !important;\n max-height: ${n}px !important;\n width: 100% !important;\n height: auto !important;\n object-fit: contain;\n `;break;case"fill":o=`\n width: 100% !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `}return o.trim()}applyResizeMode(t){const{element:i,container:n,config:s}=t,{resize:o,autoscale:r}=s,a=n.getBoundingClientRect(),l=a.width,d=a.height;let c,h;switch(o){case"fill-width":c=l,h=c/t.aspectRatio,r&&h>d&&(h=d,c=h*t.aspectRatio);break;case"fill-height":h=d,c=h*t.aspectRatio,r&&c>l&&(c=l,h=c/t.aspectRatio);break;case"fixed":default:c=t.originalWidth,h=t.originalHeight;break;case"fixed-height":c=l,h=t.originalHeight;break;case"fixed-width":c=t.originalWidth,h=d;break;case"allow-scale-down":const e=l/t.originalWidth,i=d/t.originalHeight,n=Math.min(1,Math.min(e,i));c=t.originalWidth*n,h=t.originalHeight*n;break;case"fill":c=l,h=d}this.setElementSize(i,c,h,s),this.options.enableAdaptive&&s.adaptive&&this.handleAdaptiveBreakpoint(t,l),e.debug("Resize mode applied",{widgetId:t.widgetId,resizeMode:o,containerSize:{width:l,height:d},newSize:{width:c,height:h}})}setElementSize(e,t,i,n){switch(e.style.width=`${Math.round(t)}px`,e.style.height=`${Math.round(i)}px`,n.resize){case"fill":case"fill-width":case"fill-height":e.style.objectFit=n.autoscale?"contain":"cover";break;default:e.style.objectFit="contain"}e.style.boxSizing="border-box",e.style.display="block"}handleAdaptiveBreakpoint(e,t){if(!e.config.adaptive)return;const i=t<=e.config.adaptive,n=e.element;i?(n.classList.add("widgetic-adaptive-mobile"),n.classList.remove("widgetic-adaptive-desktop"),n.style.maxWidth="100%",n.style.fontSize="14px"):(n.classList.add("widgetic-adaptive-desktop"),n.classList.remove("widgetic-adaptive-mobile"),n.style.fontSize="")}handleResize(e){for(const t of e){const e=t.target;for(const[t,i]of this.instances)if(i.container===e){const e=this.debounceTimers.get(t);e&&clearTimeout(e);const n=window.setTimeout((()=>{this.applyResizeMode(i),this.debounceTimers.delete(t)}),this.options.debounceMs);this.debounceTimers.set(t,n)}}}forceResize(e){const t=this.instances.get(e);t&&this.applyResizeMode(t)}forceResizeAll(){for(const e of this.instances.values())this.applyResizeMode(e)}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.instances.clear()}}let s=null;function o(e){return s||(s=new n(e)),s}class r{constructor(e={}){this.options=e,this.instances=new Map,this.widgetElements=new Map,this.widgetConfigs=new Map,this.fullscreenListeners=new Map,this.keyboardListeners=new Map,this.options=Object.assign({enableFullscreen:!0,enableOverlay:!0,enablePopup:!0,defaultOverlayZIndex:5e4,defaultPopupFeatures:"width=800,height=600,scrollbars=yes,resizable=yes"},e),this.setupGlobalKeyHandlers()}initializeWidget(e,t,i){const n={mode:t.displayMode||"inline",isFullscreen:!1,isOverlay:!1,isPopup:!1};return this.instances.set(e,n),this.widgetElements.set(e,i),this.widgetConfigs.set(e,t),this.setupDisplayMode(e,t,i),n}setupDisplayMode(e,t,i){const{displayMode:n}=t;switch(n){case"fullscreen":this.setupFullscreenMode(e,t,i);break;case"overlay":case"modal":this.setupOverlayMode(e,t,i);break;case"popup":this.setupPopupMode(e,t,i)}}setupFullscreenMode(e,t,i){var n;if(!this.options.enableFullscreen||!(null===(n=t.fullscreen)||void 0===n?void 0:n.enabled))return;const s=t.fullscreen.trigger||"click";"manual"!==s&&this.addFullscreenTrigger(e,i,s),t.fullscreen.showControls&&this.addFullscreenControls(e,i)}setupOverlayMode(e,t,i){var n;if(!this.options.enableOverlay||!(null===(n=t.overlay)||void 0===n?void 0:n.enabled))return;const s=t.overlay.trigger||"click";"auto"===s?setTimeout((()=>this.showOverlay(e)),100):"manual"!==s&&this.addOverlayTrigger(e,i,s)}setupPopupMode(e,t,i){var n;if(!this.options.enablePopup||!(null===(n=t.popup)||void 0===n?void 0:n.enabled))return;const s=t.popup.trigger||"click";"manual"!==s&&this.addPopupTrigger(e,i,s)}enterFullscreen(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isFullscreen)try{const s=this.getWidgetElement(n);if(!s)throw new Error(`Widget element not found: ${n}`);const o=i({target:"widgetic-fullscreen",zIndex:100001,className:"fullscreen-widget"}),r=document.createElement("div");r.className="widgetic-fullscreen-container",r.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #000;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 100001;\n ",t.originalStyle=s.style.cssText;const a=document.createComment(`widgetic-fullscreen-placeholder-${n}`);s.parentNode&&(s.parentNode.replaceChild(a,s),t.originalPlaceholder=a),s.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100vw;\n max-height: 100vh;\n border: none;\n ",r.appendChild(s);const l=this.createExitButton((()=>this.exitFullscreen(n)));if(r.appendChild(l),o.mount(r),t.isFullscreen=!0,t.overlayPortal=o,t.fullscreenElement=r,this.setupFullscreenKeyHandler(n),document.documentElement.requestFullscreen)try{yield document.documentElement.requestFullscreen()}catch(t){e.warn("Native fullscreen failed, using CSS fullscreen",{error:t})}e.info("Widget entered fullscreen mode",{widgetId:n})}catch(t){throw e.error("Failed to enter fullscreen",{widgetId:n,error:t}),t}}))}exitFullscreen(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isFullscreen)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),document.fullscreenElement&&document.exitFullscreen&&(yield document.exitFullscreen()),t.isFullscreen=!1,t.overlayPortal=void 0,t.fullscreenElement=void 0,this.removeFullscreenKeyHandler(i),e.info("Widget exited fullscreen mode",{widgetId:i})}catch(t){throw e.error("Failed to exit fullscreen",{widgetId:i,error:t}),t}}))}showOverlay(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isOverlay)try{const s=this.getWidgetConfig(n),o=null==s?void 0:s.overlay;if(!o)throw new Error(`No overlay configuration for widget: ${n}`);const r=i({target:"widgetic-overlay",zIndex:o.zIndex||this.options.defaultOverlayZIndex,className:"overlay-widget"}),a=this.createOverlayContainer(n,o),l=this.getWidgetElement(n);if(l){t.originalStyle=l.style.cssText;const e=document.createComment(`widgetic-overlay-placeholder-${n}`);l.parentNode&&(l.parentNode.replaceChild(e,l),t.originalPlaceholder=e),this.styleOverlayWidget(l,o);a.querySelector(".overlay-content").appendChild(l)}r.mount(a),t.isOverlay=!0,t.overlayPortal=r,this.setupOverlayCloseHandlers(n,a,o),e.info("Widget shown in overlay mode",{widgetId:n})}catch(t){throw e.error("Failed to show overlay",{widgetId:n,error:t}),t}}))}hideOverlay(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isOverlay)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),t.isOverlay=!1,t.overlayPortal=void 0,this.removeOverlayKeyHandler(i),e.info("Widget overlay hidden",{widgetId:i})}catch(t){throw e.error("Failed to hide overlay",{widgetId:i,error:t}),t}}))}openPopup(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(!t||t.isPopup)return(null==t?void 0:t.popupWindow)||null;try{const n=this.getWidgetConfig(i),s=null==n?void 0:n.popup;if(!s)throw new Error(`No popup configuration for widget: ${i}`);const o=this.buildPopupFeatures(s),r=this.generatePopupUrl(i),a=window.open(r,s.target||`widgetic_${i}`,o);if(!a)throw new Error("Popup blocked by browser");return t.isPopup=!0,t.popupWindow=a,this.monitorPopupClose(i,a),e.info("Widget opened in popup",{widgetId:i}),a}catch(t){throw e.error("Failed to open popup",{widgetId:i,error:t}),t}}))}closePopup(t){const i=this.instances.get(t);if(i&&i.isPopup&&i.popupWindow)try{i.popupWindow.close(),i.isPopup=!1,i.popupWindow=null,e.info("Widget popup closed",{widgetId:t})}catch(i){e.error("Failed to close popup",{widgetId:t,error:i})}}getDisplayState(e){return this.instances.get(e)||null}cleanup(e){const t=this.instances.get(e);t&&(t.isFullscreen&&this.exitFullscreen(e),t.isOverlay&&this.hideOverlay(e),t.isPopup&&this.closePopup(e),this.instances.delete(e),this.removeFullscreenKeyHandler(e),this.removeOverlayKeyHandler(e))}cleanupAll(){for(const e of this.instances.keys())this.cleanup(e)}getWidgetElement(e){return this.widgetElements.has(e)?this.widgetElements.get(e):document.querySelector(`[data-widget-id="${e}"]`)||document.querySelector(`[data-widgetic-id="${e}"]`)||document.querySelector(`[composition-id="${e}"]`)||null}getWidgetConfig(e){return this.widgetConfigs.get(e)||null}addFullscreenTrigger(e,t,i){const n=()=>this.enterFullscreen(e);switch(i){case"click":t.addEventListener("click",n);break;case"double-click":t.addEventListener("dblclick",n);break;case"hover":t.addEventListener("mouseenter",n)}}addOverlayTrigger(e,t,i){const n=()=>this.showOverlay(e);switch(i){case"click":t.addEventListener("click",n);break;case"hover":t.addEventListener("mouseenter",n)}}addPopupTrigger(e,t,i){const n=()=>this.openPopup(e);"click"===i&&t.addEventListener("click",n)}createExitButton(e){const t=document.createElement("button");return t.className="widgetic-exit-fullscreen",t.innerHTML="✕",t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",s=t.height||"100%";i&&(t.overlayWidth||t.overlayHeight)&&(n=t.overlayWidth||n,s=t.overlayHeight||s),e.style.cssText=`\n width: ${n};\n height: ${s};\n border: none;\n display: block;\n `,i&&t.overlayResize&&this.applyOverlayResizeMode(e,t.overlayResize)}applyOverlayResizeMode(e,t){if(e.parentElement)switch(t){case"fill-width":e.style.width="100%",e.style.height="auto",e.style.aspectRatio="auto";break;case"fill-height":e.style.height="100%",e.style.width="auto",e.style.aspectRatio="auto";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="100%";break;case"fixed-width":e.style.height="100%";break;case"allow-scale-down":e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.objectFit="contain";break;case"fill":e.style.width="100%",e.style.height="100%",e.style.objectFit="cover"}}buildPopupFeatures(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.centerScreen&&t.push("location=center"),e.allowResize&&t.push("resizable=yes"),e.showToolbar&&t.push("toolbar=yes"),t.length>0?t.join(","):this.options.defaultPopupFeatures||""}generatePopupUrl(e){return"about:blank"}setupGlobalKeyHandlers(){"undefined"!=typeof document&&document.addEventListener("keydown",(e=>{if("Escape"===e.key)for(const[e,t]of this.instances)t.isFullscreen?this.exitFullscreen(e):t.isOverlay&&this.hideOverlay(e)}))}setupFullscreenKeyHandler(e){const t=t=>{"Escape"===t.key&&this.exitFullscreen(e)};this.keyboardListeners.set(`${e}-fullscreen`,t),document.addEventListener("keydown",t)}removeFullscreenKeyHandler(e){const t=this.keyboardListeners.get(`${e}-fullscreen`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-fullscreen`))}setupOverlayCloseHandlers(e,t,i){if(i.closeOnBackdropClick&&t.addEventListener("click",(i=>{i.target===t&&this.hideOverlay(e)})),i.closeOnEscape){const t=t=>{"Escape"===t.key&&this.hideOverlay(e)};this.keyboardListeners.set(`${e}-overlay`,t),document.addEventListener("keydown",t)}}removeOverlayKeyHandler(e){const t=this.keyboardListeners.get(`${e}-overlay`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-overlay`))}monitorPopupClose(e,t){const i=()=>{if(t.closed){const t=this.instances.get(e);t&&(t.isPopup=!1,t.popupWindow=null)}else setTimeout(i,1e3)};setTimeout(i,1e3)}addFullscreenControls(e,t){const i=document.createElement("div");i.className="widgetic-fullscreen-controls",i.style.cssText="\n position: absolute;\n bottom: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.7);\n border-radius: 4px;\n padding: 5px;\n z-index: 1000;\n ";const n=document.createElement("button");n.innerHTML="⛶",n.style.cssText="\n background: none;\n border: none;\n color: white;\n cursor: pointer;\n font-size: 16px;\n ",n.addEventListener("click",(()=>this.enterFullscreen(e))),i.appendChild(n),t.style.position="relative",t.appendChild(i)}}let a=null;function l(e){return a||(a=new r(e)),a}var d=Object.freeze({__proto__:null,DisplayManager:r,getDisplayManager:l,resetDisplayManager:function(){a&&(a.cleanupAll(),a=null)}});const c={mobile:480,tablet:768,desktop:1024},h={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},g={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,DEFAULT_MOBILE_BREAKPOINT:768,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class p{constructor(t={enabled:!0}){var i;this.isEnabled=!1,this.activeOverlay=null,this.exitIntentListener=null,this.scrollListener=null,this.engagementStartTime=null,this.timeoutId=null,this.config=Object.assign(Object.assign({exitIntentEnabled:!0,scrollTriggerEnabled:!0,timeTriggerEnabled:!0,engagementThresholdEnabled:!0,externalTriggerEnabled:!0},t),{enabled:null===(i=t.enabled)||void 0===i||i}),this.config.breakpoints||(this.config.breakpoints={useBreakpoints:!1,mobile:c.mobile,tablet:c.tablet,desktop:c.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),e.debug("OverlayManager initialized",{config:this.config})}initializeEventListeners(){"undefined"!=typeof window&&(this.config.exitIntentEnabled&&this.initializeExitIntent(),this.config.scrollTriggerEnabled&&this.initializeScrollTrigger(),this.config.engagementThresholdEnabled&&this.startEngagementTracking())}initializeExitIntent(){"undefined"!=typeof document&&(this.exitIntentListener=e=>{e.clientY<=0&&e.movementY<0&&this.emitOverlayTrigger("exit-intent",{mousePosition:{x:e.clientX,y:e.clientY},movementY:e.movementY})},document.addEventListener("mouseleave",this.exitIntentListener))}initializeScrollTrigger(){"undefined"!=typeof window&&(this.scrollListener=()=>{const e=window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100;e>=25&&e<30?this.emitOverlayTrigger("scroll-25",{scrollPercentage:e}):e>=50&&e<55?this.emitOverlayTrigger("scroll-50",{scrollPercentage:e}):e>=75&&e<80&&this.emitOverlayTrigger("scroll-75",{scrollPercentage:e})},window.addEventListener("scroll",this.scrollListener,{passive:!0}))}startEngagementTracking(){this.engagementStartTime=Date.now();setInterval((()=>{if(!this.engagementStartTime)return;const e=Date.now()-this.engagementStartTime;e>=3e4?this.emitOverlayTrigger("engagement-30s",{engagementTimeMs:e}):e>=6e4?this.emitOverlayTrigger("engagement-1m",{engagementTimeMs:e}):e>=12e4&&this.emitOverlayTrigger("engagement-2m",{engagementTimeMs:e})}),1e4)}showOverlay(t){if(this.isEnabled){this.activeOverlay&&(e.debug("Overlay already active, closing previous"),this.hideOverlay());try{const i=this.validateOverlayConfig(t),n=this.createOverlayElement(i);document.body.appendChild(n),this.activeOverlay=n,setTimeout((()=>{n.classList.add("widgetic-overlay-visible")}),50),i.autoClose&&i.autoClose>0&&(this.timeoutId=window.setTimeout((()=>{this.hideOverlay()}),i.autoClose)),e.info("Overlay displayed",{displayMode:i.displayMode,animation:i.animation,autoClose:i.autoClose}),this.emitOverlayEvent("overlay-shown",i)}catch(i){e.error("Failed to show overlay",{error:i,config:t})}}else e.warn("Overlay manager is disabled")}validateOverlayConfig(t){const i=Object.assign({},t);return i.displayMode&&Object.values(h).includes(i.displayMode)||(i.displayMode=h.MANUAL),i.animation&&g.SUPPORTED_ANIMATIONS.includes(i.animation)||(i.animation=g.DEFAULT_ANIMATION,e.debug("Using default animation for overlay",{provided:t.animation,defaultUsed:g.DEFAULT_ANIMATION})),i.delay||(i.delay=g.DEFAULT_DELAY_MS),void 0===i.showBackdrop&&(i.showBackdrop=!0),i}hideOverlay(){if(!this.activeOverlay)return;this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=this.activeOverlay;t.classList.remove("widgetic-overlay-visible"),t.classList.add("widgetic-overlay-hiding"),setTimeout((()=>{t.parentNode&&t.parentNode.removeChild(t)}),300),this.activeOverlay=null,e.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||g.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close" aria-label="Close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&i.addEventListener("click",(()=>this.hideOverlay())),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const n=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",n))};return document.addEventListener("keydown",n),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||c.mobile;return`\n /* Mobile responsive styles */\n @media (max-width: ${t}px) {\n .widgetic-overlay-content {\n max-width: 95vw;\n margin: 10px;\n }\n \n .widgetic-overlay-body {\n padding: 15px;\n }\n }\n \n /* Tablet responsive styles */\n @media (min-width: ${t+1}px) and (max-width: ${e.tablet||c.tablet}px) {\n .widgetic-overlay-content {\n max-width: 90vw;\n margin: 15px;\n }\n \n .widgetic-overlay-body {\n padding: 18px;\n }\n }\n `}addOverlayStyles(){const e="widgetic-overlay-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .widgetic-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n }\n \n .widgetic-overlay-backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n \n .widgetic-overlay-visible {\n opacity: 1;\n }\n \n .widgetic-overlay-hiding {\n opacity: 0;\n }\n \n .widgetic-overlay-content {\n position: relative;\n background: white;\n border-radius: 8px;\n max-width: 90vw;\n max-height: 90vh;\n overflow: auto;\n transition: all 0.3s ease;\n }\n \n .widgetic-overlay-close {\n position: absolute;\n top: 10px;\n right: 15px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n z-index: 1;\n color: #6b7280;\n line-height: 1;\n padding: 4px;\n }\n \n .widgetic-overlay-close:hover {\n color: #374151;\n }\n \n .widgetic-overlay-body {\n padding: 20px;\n }\n \n /* Fade animation (default) */\n .widgetic-overlay-fade .widgetic-overlay-content {\n transform: scale(0.95);\n opacity: 0;\n }\n \n .widgetic-overlay-fade.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Slide animations */\n .widgetic-overlay-slide-up .widgetic-overlay-content {\n transform: translateY(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-up.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-down .widgetic-overlay-content {\n transform: translateY(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-down.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-left .widgetic-overlay-content {\n transform: translateX(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-left.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-right .widgetic-overlay-content {\n transform: translateX(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-right.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n /* Zoom animation */\n .widgetic-overlay-zoom .widgetic-overlay-content {\n transform: scale(0.7);\n opacity: 0;\n }\n \n .widgetic-overlay-zoom.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Bounce animation */\n .widgetic-overlay-bounce .widgetic-overlay-content {\n transform: scale(0.3);\n opacity: 0;\n transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n \n .widgetic-overlay-bounce.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Mobile responsive */\n ${this.generateResponsiveCSS()}\n `,document.head.appendChild(t)}emitOverlayTrigger(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-trigger",{detail:{triggerType:e,data:t,timestamp:(new Date).toISOString()}}))}emitOverlayEvent(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-event",{detail:{eventType:e,data:t,timestamp:(new Date).toISOString()}}))}triggerOverlay(e,t={}){const i=Object.assign({displayMode:e,animation:g.DEFAULT_ANIMATION,delay:g.DEFAULT_DELAY_MS,content:"Default overlay content"},t);i.delay&&i.delay>0?setTimeout((()=>{this.showOverlay(i)}),i.delay):this.showOverlay(i)}isOverlayActive(){return null!==this.activeOverlay}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t),this.isEnabled=this.config.enabled,e.debug("OverlayManager config updated",{config:this.config})}destroy(){this.activeOverlay&&this.hideOverlay(),this.exitIntentListener&&document.removeEventListener("mouseleave",this.exitIntentListener),this.scrollListener&&window.removeEventListener("scroll",this.scrollListener),this.timeoutId&&clearTimeout(this.timeoutId),e.debug("OverlayManager destroyed")}}let u=null;function v(e){return u||(u=new p(e)),u}export{r as D,n as R,o as a,v as b,d,l as g};
|
|
1
|
+
import{l as e}from"./core.js";import{_ as t}from"./vendor.js";import{c as i}from"./advanced.js";import{c as n}from"./api.js";class s{constructor(e={}){this.options=e,this.resizeObserver=null,this.instances=new Map,this.debounceTimers=new Map,this.options=Object.assign({observeResize:!0,debounceMs:100,enableAdaptive:!0},e),this.options.observeResize&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.handleResize.bind(this)))}registerWidget(t,i,n,s){const o={widgetId:t,element:i,container:n,config:s,originalWidth:s.width,originalHeight:s.height,aspectRatio:s.width/s.height,isObserving:!1};this.instances.set(t,o),this.applyResizeMode(o),this.resizeObserver&&this.options.observeResize&&(this.resizeObserver.observe(n),o.isObserving=!0),e.debug("Widget registered for resize handling",{widgetId:t,resizeMode:s.resize,originalSize:{width:s.width,height:s.height}})}unregisterWidget(t){const i=this.instances.get(t);if(!i)return;this.resizeObserver&&i.isObserving&&this.resizeObserver.unobserve(i.container);const n=this.debounceTimers.get(t);n&&(clearTimeout(n),this.debounceTimers.delete(t)),this.instances.delete(t),e.debug("Widget unregistered from resize handling",{widgetId:t})}static generateIframeCSS(e){const{resize:t,width:i,height:n,autoscale:s}=e;let o="";switch(t){case"fill-width":o=`\n width: 100% !important;\n height: ${n/i*100}vw !important;\n max-height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fill-height":o=`\n height: 100% !important;\n width: ${i/n*100}vh !important;\n max-width: ${i}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed":default:o=`\n width: ${i}px !important;\n height: ${n}px !important;\n flex-shrink: 0;\n object-fit: cover;\n `;break;case"fixed-height":o=`\n width: 100% !important;\n height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed-width":o=`\n width: ${i}px !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"allow-scale-down":o=`\n max-width: ${i}px !important;\n max-height: ${n}px !important;\n width: 100% !important;\n height: auto !important;\n object-fit: contain;\n `;break;case"fill":o=`\n width: 100% !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `}return o.trim()}applyResizeMode(t){const{element:i,container:n,config:s}=t,{resize:o,autoscale:r}=s,a=n.getBoundingClientRect(),l=a.width,d=a.height;let c,h;switch(o){case"fill-width":c=l,h=c/t.aspectRatio,r&&h>d&&(h=d,c=h*t.aspectRatio);break;case"fill-height":h=d,c=h*t.aspectRatio,r&&c>l&&(c=l,h=c/t.aspectRatio);break;case"fixed":default:c=t.originalWidth,h=t.originalHeight;break;case"fixed-height":c=l,h=t.originalHeight;break;case"fixed-width":c=t.originalWidth,h=d;break;case"allow-scale-down":const e=l/t.originalWidth,i=d/t.originalHeight,n=Math.min(1,Math.min(e,i));c=t.originalWidth*n,h=t.originalHeight*n;break;case"fill":c=l,h=d}this.setElementSize(i,c,h,s),this.options.enableAdaptive&&s.adaptive&&this.handleAdaptiveBreakpoint(t,l),e.debug("Resize mode applied",{widgetId:t.widgetId,resizeMode:o,containerSize:{width:l,height:d},newSize:{width:c,height:h}})}setElementSize(e,t,i,n){switch(e.style.width=`${Math.round(t)}px`,e.style.height=`${Math.round(i)}px`,n.resize){case"fill":case"fill-width":case"fill-height":e.style.objectFit=n.autoscale?"contain":"cover";break;default:e.style.objectFit="contain"}e.style.boxSizing="border-box",e.style.display="block"}handleAdaptiveBreakpoint(e,t){if(!e.config.adaptive)return;const i=t<=e.config.adaptive,n=e.element;i?(n.classList.add("widgetic-adaptive-mobile"),n.classList.remove("widgetic-adaptive-desktop"),n.style.maxWidth="100%",n.style.fontSize="14px"):(n.classList.add("widgetic-adaptive-desktop"),n.classList.remove("widgetic-adaptive-mobile"),n.style.fontSize="")}handleResize(e){for(const t of e){const e=t.target;for(const[t,i]of this.instances)if(i.container===e){const e=this.debounceTimers.get(t);e&&clearTimeout(e);const n=window.setTimeout((()=>{this.applyResizeMode(i),this.debounceTimers.delete(t)}),this.options.debounceMs);this.debounceTimers.set(t,n)}}}forceResize(e){const t=this.instances.get(e);t&&this.applyResizeMode(t)}forceResizeAll(){for(const e of this.instances.values())this.applyResizeMode(e)}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.instances.clear()}}let o=null;function r(e){return o||(o=new s(e)),o}class a{constructor(e={}){this.options=e,this.instances=new Map,this.widgetElements=new Map,this.widgetConfigs=new Map,this.fullscreenListeners=new Map,this.keyboardListeners=new Map,this.options=Object.assign({enableFullscreen:!0,enableOverlay:!0,enablePopup:!0,defaultOverlayZIndex:5e4,defaultPopupFeatures:"width=800,height=600,scrollbars=yes,resizable=yes"},e),this.setupGlobalKeyHandlers()}initializeWidget(e,t,i){const n={mode:t.displayMode||"inline",isFullscreen:!1,isOverlay:!1,isPopup:!1};return this.instances.set(e,n),this.widgetElements.set(e,i),this.widgetConfigs.set(e,t),this.setupDisplayMode(e,t,i),n}setupDisplayMode(e,t,i){const{displayMode:n}=t;switch(n){case"fullscreen":this.setupFullscreenMode(e,t,i);break;case"overlay":case"modal":this.setupOverlayMode(e,t,i);break;case"popup":this.setupPopupMode(e,t,i)}}setupFullscreenMode(e,t,i){var n;if(!this.options.enableFullscreen||!(null===(n=t.fullscreen)||void 0===n?void 0:n.enabled))return;const s=t.fullscreen.trigger||"click";"manual"!==s&&this.addFullscreenTrigger(e,i,s),t.fullscreen.showControls&&this.addFullscreenControls(e,i)}setupOverlayMode(e,t,i){var n;if(!this.options.enableOverlay||!(null===(n=t.overlay)||void 0===n?void 0:n.enabled))return;const s=t.overlay.trigger||"click";"auto"===s?setTimeout((()=>this.showOverlay(e)),100):"manual"!==s&&this.addOverlayTrigger(e,i,s)}setupPopupMode(e,t,i){var n;if(!this.options.enablePopup||!(null===(n=t.popup)||void 0===n?void 0:n.enabled))return;const s=t.popup.trigger||"click";"manual"!==s&&this.addPopupTrigger(e,i,s)}enterFullscreen(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isFullscreen)try{const s=this.getWidgetElement(n);if(!s)throw new Error(`Widget element not found: ${n}`);const o=i({target:"widgetic-fullscreen",zIndex:100001,className:"fullscreen-widget"}),r=document.createElement("div");r.className="widgetic-fullscreen-container",r.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #000;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 100001;\n ",t.originalStyle=s.style.cssText;const a=document.createComment(`widgetic-fullscreen-placeholder-${n}`);s.parentNode&&(s.parentNode.replaceChild(a,s),t.originalPlaceholder=a),s.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100vw;\n max-height: 100vh;\n border: none;\n ",r.appendChild(s);const l=this.createExitButton((()=>this.exitFullscreen(n)));if(r.appendChild(l),o.mount(r),t.isFullscreen=!0,t.overlayPortal=o,t.fullscreenElement=r,this.setupFullscreenKeyHandler(n),document.documentElement.requestFullscreen)try{yield document.documentElement.requestFullscreen()}catch(t){e.warn("Native fullscreen failed, using CSS fullscreen",{error:t})}e.info("Widget entered fullscreen mode",{widgetId:n})}catch(t){throw e.error("Failed to enter fullscreen",{widgetId:n,error:t}),t}}))}exitFullscreen(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isFullscreen)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),document.fullscreenElement&&document.exitFullscreen&&(yield document.exitFullscreen()),t.isFullscreen=!1,t.overlayPortal=void 0,t.fullscreenElement=void 0,this.removeFullscreenKeyHandler(i),e.info("Widget exited fullscreen mode",{widgetId:i})}catch(t){throw e.error("Failed to exit fullscreen",{widgetId:i,error:t}),t}}))}showOverlay(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isOverlay)try{const s=this.getWidgetConfig(n),o=null==s?void 0:s.overlay;if(!o)throw new Error(`No overlay configuration for widget: ${n}`);const r=i({target:"widgetic-overlay",zIndex:o.zIndex||this.options.defaultOverlayZIndex,className:"overlay-widget"}),a=this.createOverlayContainer(n,o),l=this.getWidgetElement(n);if(l){t.originalStyle=l.style.cssText;const e=document.createComment(`widgetic-overlay-placeholder-${n}`);l.parentNode&&(l.parentNode.replaceChild(e,l),t.originalPlaceholder=e),this.styleOverlayWidget(l,o);a.querySelector(".overlay-content").appendChild(l)}r.mount(a),t.isOverlay=!0,t.overlayPortal=r,this.setupOverlayCloseHandlers(n,a,o),e.info("Widget shown in overlay mode",{widgetId:n})}catch(t){throw e.error("Failed to show overlay",{widgetId:n,error:t}),t}}))}hideOverlay(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isOverlay)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),t.isOverlay=!1,t.overlayPortal=void 0,this.removeOverlayKeyHandler(i),e.info("Widget overlay hidden",{widgetId:i})}catch(t){throw e.error("Failed to hide overlay",{widgetId:i,error:t}),t}}))}openPopup(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(!t||t.isPopup)return(null==t?void 0:t.popupWindow)||null;try{const n=this.getWidgetConfig(i),s=null==n?void 0:n.popup;if(!s)throw new Error(`No popup configuration for widget: ${i}`);const o=this.buildPopupFeatures(s),r=this.generatePopupUrl(i),a=window.open(r,s.target||`widgetic_${i}`,o);if(!a)throw new Error("Popup blocked by browser");return t.isPopup=!0,t.popupWindow=a,this.monitorPopupClose(i,a),e.info("Widget opened in popup",{widgetId:i}),a}catch(t){throw e.error("Failed to open popup",{widgetId:i,error:t}),t}}))}closePopup(t){const i=this.instances.get(t);if(i&&i.isPopup&&i.popupWindow)try{i.popupWindow.close(),i.isPopup=!1,i.popupWindow=null,e.info("Widget popup closed",{widgetId:t})}catch(i){e.error("Failed to close popup",{widgetId:t,error:i})}}getDisplayState(e){return this.instances.get(e)||null}cleanup(e){const t=this.instances.get(e);t&&(t.isFullscreen&&this.exitFullscreen(e),t.isOverlay&&this.hideOverlay(e),t.isPopup&&this.closePopup(e),this.instances.delete(e),this.removeFullscreenKeyHandler(e),this.removeOverlayKeyHandler(e))}cleanupAll(){for(const e of this.instances.keys())this.cleanup(e)}getWidgetElement(e){return this.widgetElements.has(e)?this.widgetElements.get(e):document.querySelector(`[data-widget-id="${e}"]`)||document.querySelector(`[data-widgetic-id="${e}"]`)||document.querySelector(`[composition-id="${e}"]`)||null}getWidgetConfig(e){return this.widgetConfigs.get(e)||null}addFullscreenTrigger(e,t,i){const n=()=>this.enterFullscreen(e);switch(i){case"click":t.addEventListener("click",n);break;case"double-click":t.addEventListener("dblclick",n);break;case"hover":t.addEventListener("mouseenter",n)}}addOverlayTrigger(e,t,i){const n=()=>this.showOverlay(e);switch(i){case"click":t.addEventListener("click",n);break;case"hover":t.addEventListener("mouseenter",n)}}addPopupTrigger(e,t,i){const n=()=>this.openPopup(e);"click"===i&&t.addEventListener("click",n)}createExitButton(e){const t=document.createElement("button");return t.className="widgetic-exit-fullscreen",t.innerHTML="✕",t.setAttribute("aria-label",n("close")),t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",s=t.height||"100%";i&&(t.overlayWidth||t.overlayHeight)&&(n=t.overlayWidth||n,s=t.overlayHeight||s),e.style.cssText=`\n width: ${n};\n height: ${s};\n border: none;\n display: block;\n `,i&&t.overlayResize&&this.applyOverlayResizeMode(e,t.overlayResize)}applyOverlayResizeMode(e,t){if(e.parentElement)switch(t){case"fill-width":e.style.width="100%",e.style.height="auto",e.style.aspectRatio="auto";break;case"fill-height":e.style.height="100%",e.style.width="auto",e.style.aspectRatio="auto";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="100%";break;case"fixed-width":e.style.height="100%";break;case"allow-scale-down":e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.objectFit="contain";break;case"fill":e.style.width="100%",e.style.height="100%",e.style.objectFit="cover"}}buildPopupFeatures(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.centerScreen&&t.push("location=center"),e.allowResize&&t.push("resizable=yes"),e.showToolbar&&t.push("toolbar=yes"),t.length>0?t.join(","):this.options.defaultPopupFeatures||""}generatePopupUrl(e){return"about:blank"}setupGlobalKeyHandlers(){"undefined"!=typeof document&&document.addEventListener("keydown",(e=>{if("Escape"===e.key)for(const[e,t]of this.instances)t.isFullscreen?this.exitFullscreen(e):t.isOverlay&&this.hideOverlay(e)}))}setupFullscreenKeyHandler(e){const t=t=>{"Escape"===t.key&&this.exitFullscreen(e)};this.keyboardListeners.set(`${e}-fullscreen`,t),document.addEventListener("keydown",t)}removeFullscreenKeyHandler(e){const t=this.keyboardListeners.get(`${e}-fullscreen`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-fullscreen`))}setupOverlayCloseHandlers(e,t,i){if(i.closeOnBackdropClick&&t.addEventListener("click",(i=>{i.target===t&&this.hideOverlay(e)})),i.closeOnEscape){const t=t=>{"Escape"===t.key&&this.hideOverlay(e)};this.keyboardListeners.set(`${e}-overlay`,t),document.addEventListener("keydown",t)}}removeOverlayKeyHandler(e){const t=this.keyboardListeners.get(`${e}-overlay`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-overlay`))}monitorPopupClose(e,t){const i=()=>{if(t.closed){const t=this.instances.get(e);t&&(t.isPopup=!1,t.popupWindow=null)}else setTimeout(i,1e3)};setTimeout(i,1e3)}addFullscreenControls(e,t){const i=document.createElement("div");i.className="widgetic-fullscreen-controls",i.style.cssText="\n position: absolute;\n bottom: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.7);\n border-radius: 4px;\n padding: 5px;\n z-index: 1000;\n ";const n=document.createElement("button");n.innerHTML="⛶",n.style.cssText="\n background: none;\n border: none;\n color: white;\n cursor: pointer;\n font-size: 16px;\n ",n.addEventListener("click",(()=>this.enterFullscreen(e))),i.appendChild(n),t.style.position="relative",t.appendChild(i)}}let l=null;function d(e){return l||(l=new a(e)),l}var c=Object.freeze({__proto__:null,DisplayManager:a,getDisplayManager:d,resetDisplayManager:function(){l&&(l.cleanupAll(),l=null)}});const h={mobile:480,tablet:768,desktop:1024},g={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},p={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,DEFAULT_MOBILE_BREAKPOINT:768,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class u{constructor(t={enabled:!0}){var i;this.isEnabled=!1,this.activeOverlay=null,this.exitIntentListener=null,this.scrollListener=null,this.engagementStartTime=null,this.timeoutId=null,this.config=Object.assign(Object.assign({exitIntentEnabled:!0,scrollTriggerEnabled:!0,timeTriggerEnabled:!0,engagementThresholdEnabled:!0,externalTriggerEnabled:!0},t),{enabled:null===(i=t.enabled)||void 0===i||i}),this.config.breakpoints||(this.config.breakpoints={useBreakpoints:!1,mobile:h.mobile,tablet:h.tablet,desktop:h.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),e.debug("OverlayManager initialized",{config:this.config})}initializeEventListeners(){"undefined"!=typeof window&&(this.config.exitIntentEnabled&&this.initializeExitIntent(),this.config.scrollTriggerEnabled&&this.initializeScrollTrigger(),this.config.engagementThresholdEnabled&&this.startEngagementTracking())}initializeExitIntent(){"undefined"!=typeof document&&(this.exitIntentListener=e=>{e.clientY<=0&&e.movementY<0&&this.emitOverlayTrigger("exit-intent",{mousePosition:{x:e.clientX,y:e.clientY},movementY:e.movementY})},document.addEventListener("mouseleave",this.exitIntentListener))}initializeScrollTrigger(){"undefined"!=typeof window&&(this.scrollListener=()=>{const e=window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100;e>=25&&e<30?this.emitOverlayTrigger("scroll-25",{scrollPercentage:e}):e>=50&&e<55?this.emitOverlayTrigger("scroll-50",{scrollPercentage:e}):e>=75&&e<80&&this.emitOverlayTrigger("scroll-75",{scrollPercentage:e})},window.addEventListener("scroll",this.scrollListener,{passive:!0}))}startEngagementTracking(){this.engagementStartTime=Date.now();setInterval((()=>{if(!this.engagementStartTime)return;const e=Date.now()-this.engagementStartTime;e>=3e4?this.emitOverlayTrigger("engagement-30s",{engagementTimeMs:e}):e>=6e4?this.emitOverlayTrigger("engagement-1m",{engagementTimeMs:e}):e>=12e4&&this.emitOverlayTrigger("engagement-2m",{engagementTimeMs:e})}),1e4)}showOverlay(t){if(this.isEnabled){this.activeOverlay&&(e.debug("Overlay already active, closing previous"),this.hideOverlay());try{const i=this.validateOverlayConfig(t),n=this.createOverlayElement(i);document.body.appendChild(n),this.activeOverlay=n,setTimeout((()=>{n.classList.add("widgetic-overlay-visible")}),50),i.autoClose&&i.autoClose>0&&(this.timeoutId=window.setTimeout((()=>{this.hideOverlay()}),i.autoClose)),e.info("Overlay displayed",{displayMode:i.displayMode,animation:i.animation,autoClose:i.autoClose}),this.emitOverlayEvent("overlay-shown",i)}catch(i){e.error("Failed to show overlay",{error:i,config:t})}}else e.warn("Overlay manager is disabled")}validateOverlayConfig(t){const i=Object.assign({},t);return i.displayMode&&Object.values(g).includes(i.displayMode)||(i.displayMode=g.MANUAL),i.animation&&p.SUPPORTED_ANIMATIONS.includes(i.animation)||(i.animation=p.DEFAULT_ANIMATION,e.debug("Using default animation for overlay",{provided:t.animation,defaultUsed:p.DEFAULT_ANIMATION})),i.delay||(i.delay=p.DEFAULT_DELAY_MS),void 0===i.showBackdrop&&(i.showBackdrop=!0),i}hideOverlay(){if(!this.activeOverlay)return;this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=this.activeOverlay;t.classList.remove("widgetic-overlay-visible"),t.classList.add("widgetic-overlay-hiding"),setTimeout((()=>{t.parentNode&&t.parentNode.removeChild(t)}),300),this.activeOverlay=null,e.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||p.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&(i.setAttribute("aria-label",n("close")),i.addEventListener("click",(()=>this.hideOverlay()))),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const s=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",s))};return document.addEventListener("keydown",s),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||h.mobile;return`\n /* Mobile responsive styles */\n @media (max-width: ${t}px) {\n .widgetic-overlay-content {\n max-width: 95vw;\n margin: 10px;\n }\n \n .widgetic-overlay-body {\n padding: 15px;\n }\n }\n \n /* Tablet responsive styles */\n @media (min-width: ${t+1}px) and (max-width: ${e.tablet||h.tablet}px) {\n .widgetic-overlay-content {\n max-width: 90vw;\n margin: 15px;\n }\n \n .widgetic-overlay-body {\n padding: 18px;\n }\n }\n `}addOverlayStyles(){const e="widgetic-overlay-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .widgetic-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n }\n \n .widgetic-overlay-backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n \n .widgetic-overlay-visible {\n opacity: 1;\n }\n \n .widgetic-overlay-hiding {\n opacity: 0;\n }\n \n .widgetic-overlay-content {\n position: relative;\n background: white;\n border-radius: 8px;\n max-width: 90vw;\n max-height: 90vh;\n overflow: auto;\n transition: all 0.3s ease;\n }\n \n .widgetic-overlay-close {\n position: absolute;\n top: 10px;\n right: 15px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n z-index: 1;\n color: #6b7280;\n line-height: 1;\n padding: 4px;\n }\n \n .widgetic-overlay-close:hover {\n color: #374151;\n }\n \n .widgetic-overlay-body {\n padding: 20px;\n }\n \n /* Fade animation (default) */\n .widgetic-overlay-fade .widgetic-overlay-content {\n transform: scale(0.95);\n opacity: 0;\n }\n \n .widgetic-overlay-fade.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Slide animations */\n .widgetic-overlay-slide-up .widgetic-overlay-content {\n transform: translateY(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-up.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-down .widgetic-overlay-content {\n transform: translateY(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-down.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-left .widgetic-overlay-content {\n transform: translateX(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-left.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-right .widgetic-overlay-content {\n transform: translateX(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-right.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n /* Zoom animation */\n .widgetic-overlay-zoom .widgetic-overlay-content {\n transform: scale(0.7);\n opacity: 0;\n }\n \n .widgetic-overlay-zoom.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Bounce animation */\n .widgetic-overlay-bounce .widgetic-overlay-content {\n transform: scale(0.3);\n opacity: 0;\n transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n \n .widgetic-overlay-bounce.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Mobile responsive */\n ${this.generateResponsiveCSS()}\n `,document.head.appendChild(t)}emitOverlayTrigger(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-trigger",{detail:{triggerType:e,data:t,timestamp:(new Date).toISOString()}}))}emitOverlayEvent(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-event",{detail:{eventType:e,data:t,timestamp:(new Date).toISOString()}}))}triggerOverlay(e,t={}){const i=Object.assign({displayMode:e,animation:p.DEFAULT_ANIMATION,delay:p.DEFAULT_DELAY_MS,content:"Default overlay content"},t);i.delay&&i.delay>0?setTimeout((()=>{this.showOverlay(i)}),i.delay):this.showOverlay(i)}isOverlayActive(){return null!==this.activeOverlay}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t),this.isEnabled=this.config.enabled,e.debug("OverlayManager config updated",{config:this.config})}destroy(){this.activeOverlay&&this.hideOverlay(),this.exitIntentListener&&document.removeEventListener("mouseleave",this.exitIntentListener),this.scrollListener&&window.removeEventListener("scroll",this.scrollListener),this.timeoutId&&clearTimeout(this.timeoutId),e.debug("OverlayManager destroyed")}}let v=null;function y(e){return v||(v=new u(e)),v}export{a as D,s as R,r as a,y as b,c as d,d as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e}from"./vendor.js";import{r as t,a as i,E as n,c as o,g as s,b as a}from"./api.js";import{l as d,a as r,b as c,d as l}from"./core.js";import{g as u,a as g}from"./media.js";import{getMessenger as h}from"./messaging.js";import{R as m}from"./display.js";const p="undefined"!=typeof HTMLElement?HTMLElement:class{};class b extends p{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(),d.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){if(!this.isWidgetConnected){this.isWidgetConnected=!0,d.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const e=this.getAttribute("composition-id");if(!e)throw new Error("composition-id attribute is required");const s=yield t(e);if("refused"===s.status)throw i(e,s.refusal),new Error(n);const a="found"===s.status?s.payload:null;if(null==a?void 0:a.embedUrl)return this.innerHTML="",this.appendChild(o(a.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",e,a)),void this.setWidgetReady();yield this.loadWidgetData(e),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){d.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(d.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(d.debug("WidgeticWidget attribute changed",{instanceId:this.instanceId,attribute:e,oldValue:t,newValue:i}),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){d.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(t){return e(this,void 0,void 0,(function*(){const e=s();this.compositionData=yield e.getComposition(t),this.widgetData=yield e.getWidget(this.compositionData.widgetId),d.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:t,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=a();this.loadedModule=yield e.loadModule(this.widgetData),d.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,d.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw d.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,i){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,n=window.ReactDOM,o=this.getWidgetProps(),s=e.createElement(i,o);n.render(s,t)}}))}initializeVueComponent(t,i){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,n=this.getWidgetProps();new e({el:t,render:e=>e(i,{props:n})})}}))}initializeSvelteOrVanillaComponent(t,i){return e(this,void 0,void 0,(function*(){var e;const n=this.getWidgetProps();if(i.$$prop_def||(null===(e=i.prototype)||void 0===e?void 0:e.$$prop_def))this.svelteComponent=new i({target:t,props:n});else if(i.prototype&&i.prototype.constructor===i){const e=new i(t,n);"function"==typeof e.render&&(yield e.render())}else if("function"==typeof i)yield i(t,n);else{if(!i||"function"!=typeof i.init)throw new Error("Unknown component type");yield i.init(t,n)}}))}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 i=this.getAttribute("width")||"100%",n=this.getAttribute("height")||"400",o=this.getAttribute("resize")||"responsive";switch(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof n?`${n}px`:n,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"),i=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"!==i&&"fill-width"!==i||this.setupAdaptiveBehavior(e)}setupAdaptiveBehavior(e){const t=window.matchMedia(`(max-width: ${e}px)`),i=t=>{this.setAttribute("data-mobile",t.matches?"true":"false"),this.dispatchEvent(new CustomEvent("widgetic:adaptive",{detail:{isMobile:t.matches,breakpoint:e}}))};i(t),t.addEventListener("change",i),this.eventListeners.set("adaptive",(()=>{t.removeEventListener("change",i)}))}handleAutoscale(e){const{width:t,height:i}=e.contentRect;this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:t,height:i}})),this.widgetState.data.dimensions={width:t,height:i}}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,i=new FormData(t),n={};i.forEach(((e,t)=>{n[t]=e})),this.widgetState.data.formData=n,this.dispatchEvent(new CustomEvent("widgetic:form-submit",{detail:{data:n,form:t},bubbles:!0})),d.debug("Form submitted",{instanceId:this.instanceId,data:n})}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})),d.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})),d.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){d.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(),d.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function f(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",b),d.info("WidgeticWidget custom element registered")))}class w{constructor(){this.observers=new Map,this.mutationObservers=new Map,this.timeouts=new Map,this.animationIds=new Map,this.storageKey="widgetic_autoscale_heights"}static getInstance(){return w.instance||(w.instance=new w),w.instance}enableAutoScale(e,t,i={enabled:!0}){if(!i.enabled)return;const n=Object.assign({minHeight:i.minHeight||50,maxHeight:i.maxHeight||2e3,debounceDelay:i.debounceDelay||150,threshold:i.threshold||5,animate:!1!==i.animate,animationDuration:i.animationDuration||300},i),o=e.offsetHeight,s=this.getStoredHeight(t);s&&s!==o&&this.setElementHeight(e,s,n.animate,n.animationDuration),this.setupContentMonitoring(e,t,n,o)}disableAutoScale(e){const t=this.observers.get(e);t&&(t.disconnect(),this.observers.delete(e));const i=this.mutationObservers.get(e);i&&(i.disconnect(),this.mutationObservers.delete(e));const n=this.timeouts.get(e);n&&(clearTimeout(n),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){try{const t=localStorage.getItem(this.storageKey);if(!t)return null;const i=JSON.parse(t),n=i[e];if(!n)return null;const o=864e5;return Date.now()-n.lastUpdated>o?(delete i[e],localStorage.setItem(this.storageKey,JSON.stringify(i)),null):n.height}catch(e){return null}}storeHeight(e,t,i){try{const n=localStorage.getItem(this.storageKey),o=n?JSON.parse(n):{};o[e]={compositionId:e,height:t,originalHeight:i,lastUpdated:Date.now()},localStorage.setItem(this.storageKey,JSON.stringify(o))}catch(e){}}setupContentMonitoring(e,t,i,n){const o=this.findContentElement(e);if(!o)return void e.tagName.toLowerCase();const s=this.createDebouncedHeightUpdate(e,t,i,n);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 a=new MutationObserver((()=>{const e=o.scrollHeight;s(e)}));a.observe(o,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,a);const d=o.scrollHeight;s(d)}findContentElement(e){var t;if("iframe"===e.tagName.toLowerCase())try{const i=e,n=i.contentDocument||(null===(t=i.contentWindow)||void 0===t?void 0:t.document);if(null==n?void 0:n.body)return n.body}catch(t){return this.setupIframePostMessageListener(e),null}const i=e.tagName.toLowerCase();if("widgetic"===i||"widgetic-widget"===i||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",i=i=>{var n,o;if(i.source===e.contentWindow&&("widgetic:autoscale"===(null===(n=i.data)||void 0===n?void 0:n.type)||"autoscale"===(null===(o=i.data)||void 0===o?void 0:o.type))){const{height:n,contentHeight:o}=i.data.payload||i.data;if("number"==typeof n&&n>0){const i=this.getConfigForWidget(t),s=Math.max(i.minHeight||50,Math.min(i.maxHeight||2e3,n));this.setElementHeight(e,s,i.animate,i.animationDuration),this.storeHeight(t,s,e.offsetHeight),e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:e.offsetHeight,newHeight:s,contentHeight:o||n}}))}}};window.addEventListener("message",i),e._autoscaleMessageCleanup=()=>{window.removeEventListener("message",i)}}getConfigForWidget(e){return{enabled:!0,minHeight:50,maxHeight:2e3,animate:!0,animationDuration:300,debounceDelay:150,threshold:5}}createDebouncedHeightUpdate(e,t,i,n){let o=e.offsetHeight;return s=>{const a=this.timeouts.get(t);a&&clearTimeout(a);const d=setTimeout((()=>{const a=Math.max(i.minHeight,Math.min(i.maxHeight,s));Math.abs(a-o)>=i.threshold&&(this.setElementHeight(e,a,i.animate,i.animationDuration),this.storeHeight(t,a,n),o=a,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:o,newHeight:a,contentHeight:s}}))),this.timeouts.delete(t)}),i.debounceDelay);this.timeouts.set(t,d)}}setElementHeight(e,t,i=!0,n=300){if(!i)return void(e.style.height=`${t}px`);const o=e.offsetHeight,s=t-o;if(Math.abs(s)<1)return;const a=this.animationIds.get(e.id||e.tagName);a&&cancelAnimationFrame(a);const d=performance.now(),r=o,c=i=>{const o=i-d,a=Math.min(o/n,1),l=1-Math.pow(1-a,3),u=r+s*l;if(e.style.height=`${u}px`,a<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 v{constructor(){this.autoScaleManager=w.getInstance(),f()}render(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i="100%",height:n="400",resize:o="responsive",autoscale:s=!0,adaptive:a=768,media:d,content:r}=t,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",e),c.setAttribute("width",String(i)),c.setAttribute("height",String(n)),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(a)),d&&Object.keys(d).length>0){u().registerWidget(e,d),this.setupCustomElementMediaListener(c,e)}if(r&&Object.keys(r).length>0){g().registerWidget(e,r),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,i,n){return e(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(t,i,n){return e(this,void 0,void 0,(function*(){if(i.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const e=window.React,o=window.ReactDOM,s=e.createElement(i,{config:n.config,metadata:n.metadata});o.render(s,t)}else{if(!i._isVue&&!i.__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(i,{props:{config:n.config,metadata:n.metadata}})})}}))}applyElementStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;switch(e.style.width="number"==typeof n?`${n}px`:n,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,d||768)}if(a){("boolean"==typeof a?a:a&&"object"==typeof a&&a.enabled)&&this.enableAutoscale(e,t,a)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),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 i=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;">${i}</small>\n </div>\n </div>\n `,e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:i}}))}setupCustomElementMediaListener(e,t){const i=u(),n=t=>{const{command:i}=t.detail;if("pause"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");t.forEach((e=>{e.paused||e.pause()})),i.forEach((e=>{e.paused||e.pause()}))}else if("play"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video"),n=Array.from(t).concat(Array.from(i)).find((e=>e.currentTime>0&&!e.ended));n&&n.play().catch((()=>{}))}};e.addEventListener("widgetic:media:command",n),e._mediaCommandCleanup=()=>{e.removeEventListener("widgetic:media:command",n)};const o=(n,o)=>s=>{const a=(e.__widgetConfig||{}).media||{},d="audio"===n.tagName.toLowerCase()?"audio":"video";i.handleMediaEvent({type:o,compositionId:t,config:a,data:{position:n.currentTime,duration:n.duration,volume:n.volume,mediaType:d,title:n.title||n.getAttribute("data-title")||void 0}})},s=()=>{const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");Array.from(t).concat(Array.from(i)).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 a=new MutationObserver((()=>{s()}));a.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{a.disconnect()}}setupCustomElementContentListener(e,t){const i=g(),n=n=>{if(n.detail&&n.detail.type){const o=n.detail.type,s=n.detail.data||n.detail;let a={};try{const t=e.getAttribute("data-content-config");t&&(a=JSON.parse(t))}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:s})}};e.addEventListener("widgetic:content:position",n),e.addEventListener("widgetic:content:navigate",n),e.addEventListener("widgetic:content:complete",n),e.addEventListener("widgetic:content:reset",n),e.addEventListener("widgetic:content:metadata",n),e._contentPositionCleanup=()=>{e.removeEventListener("widgetic:content:position",n),e.removeEventListener("widgetic:content:navigate",n),e.removeEventListener("widgetic:content:complete",n),e.removeEventListener("widgetic:content:reset",n),e.removeEventListener("widgetic:content:metadata",n)}}}var y=Object.freeze({__proto__:null,CustomElementRenderer:v});class I{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&d.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void d.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,s=i.initialMode||(o<i.breakpoint?"mobile":"desktop"),a={mode:s,breakpoint:i.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,a),this.callbacks.set(e,n);const r=new ResizeObserver((t=>{this.handleResize(e,t,i)}));r.observe(t),this.observers.set(e,r),n(a),d.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:s,containerWidth:o})}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e));const i=this.observers.get(e);i&&(i.disconnect(),this.observers.delete(e)),this.callbacks.delete(e),this.currentStates.delete(e),d.debug("Widget unregistered from responsive monitoring",{widgetId:e})}getCurrentState(e){return this.currentStates.get(e)||null}checkResponsiveState(e,t){const i=this.currentStates.get(e),n=this.callbacks.get(e);if(!i||!n)return void d.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<i.breakpoint?"mobile":"desktop";if(o!==i.mode){const s={mode:o,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,s),n(s),d.info("Responsive state changed manually",{widgetId:e,from:i.mode,to:o,width:t,breakpoint:i.breakpoint})}}handleResize(e,t,i){const n=this.debounceTimers.get(e);n&&clearTimeout(n);const o=setTimeout((()=>{this.processResize(e,t,i),this.debounceTimers.delete(e)}),i.debounceDelay||150);this.debounceTimers.set(e,o)}processResize(e,t,i){const n=this.currentStates.get(e),o=this.callbacks.get(e);if(!n||!o)return;const s=t[t.length-1];if(!s)return;const a=s.contentRect.width,r=a<i.breakpoint?"mobile":"desktop";if(r!==n.mode){const t={mode:r,breakpoint:i.breakpoint,width:a,timestamp:Date.now()};this.currentStates.set(e,t),o(t),d.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:r,width:a,breakpoint:i.breakpoint})}else if(Math.abs(a-n.width)>10){const t=Object.assign(Object.assign({},n),{width:a,timestamp:Date.now()});this.currentStates.set(e,t),d.debug("Container width updated",{widgetId:e,width:a,mode:n.mode,breakpoint:i.breakpoint})}}getRegisteredWidgets(){return Array.from(this.observers.keys())}cleanup(){const e=this.getRegisteredWidgets();for(const t of e)this.unregisterWidget(t);d.debug("ResponsiveManager cleanup complete")}}let E=null;function x(){return E||(E=new I),E}class k{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=w.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i,height:n,resize:o="fixed",autoscale:s=!1,adaptive:a,responsive:r,container:c,allowFullscreen:l=!0,sandbox:h=this.getDefaultSandboxPermissions(),allowedFeatures:p=this.getDefaultAllowedFeatures(),loading:b="lazy",enableResize:f=!0,compositionData:w,widgetData:v,security:y={},fallback:I={enabled:!0,timeout:1e4,retryCount:3},media:E}=t;if(!i||!n||!c)throw new Error("Missing required parameters: width, height, and container are required");const x=w||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},k=v||{id:x.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: ${x.name||e}`,w.loading=b,this.applySandboxSecurity(w,h,p),w.width=i.toString(),w.height=n.toString(),w.frameBorder="0",w.scrolling="no",l&&(w.allowFullscreen=!0,w.setAttribute("allowfullscreen","")),w.title=`Widgetic Widget ${e}`,w.setAttribute("aria-label",`Interactive widget: ${e}`);const v={compositionId:e,renderMode:"iframe",displayMode:"inline",resize:o,width:"number"==typeof i?i:parseInt(i.toString()),height:"number"==typeof n?n:parseInt(n.toString()),autoscale:s,adaptive:a,responsive:r,media:E},C=m.generateIframeCSS(v);C&&(w.style.cssText+=C),this.applyIframeStyling(w,e,{width:i,height:n,resize:o,autoscale:s,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"===b,W=new Promise(((t,i)=>{let n=null;S||(n=setTimeout((()=>{i(new Error(`Iframe load timeout for composition: ${e}`))}),I.timeout||1e4)),w.onload=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(c),w.style.visibility="visible",w.style.opacity="1",t()},w.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(c),i(new Error(`Failed to load iframe for composition: ${e}`))}}));if(c.appendChild(w),f&&"undefined"!=typeof ResizeObserver){const t=new m({observeResize:!0}),i=`iframe-${e}-${Date.now()}`;w.setAttribute("data-widget-id",i),t.registerWidget(i,w,c,v),w.__resizeHandler=t,w.__widgetId=i}r&&"number"==typeof r&&r>0&&this.setupResponsiveMonitoring(w,c,e,r),this.iframeRegistry.set(e,w),w.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),S||(yield W);const M=`iframe-${e}-${Date.now()}`;if(d.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:i,height:n},resize:o,autoscale:s,responsive:r,sandbox:h.join(" "),features:p.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:M,element:w,compositionData:x,widgetData:k,renderMode:"iframe",cleanup:()=>this.cleanupWidget(w)}}catch(t){throw d.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(c),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){d.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(e),n=[];for(let e=0;e<i.length;e++){const o=i[e],s=t[e];if("fulfilled"===o.status)n.push(o.value);else{d.error("Iframe widget rendering failed in batch",{compositionId:s.compositionId,error:o.reason});const e=`error-${s.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(s,o.reason),compositionData:{id:s.compositionId,name:`Composition ${s.compositionId}`,widgetId:`widget-${s.compositionId}`,config:{}},widgetData:{id:`widget-${s.compositionId}`,name:`Widget ${s.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return d.info("Iframe batch rendering complete",{total:t.length,successful:n.filter((e=>"IFRAME"===e.element.tagName)).length,failed:n.filter((e=>"IFRAME"!==e.element.tagName)).length}),n}))}createSecureIframe(e,t){var i;const n=document.createElement("iframe");return n.style.border="none",n.style.display="block",n.style.overflow="hidden",n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("crossorigin","anonymous"),(null===(i=t.security)||void 0===i?void 0:i.enableCSP)&&n.setAttribute("csp",this.generateCSP(t.security.allowedOrigins)),n.setAttribute("data-widgetic-id",e),n.setAttribute("data-enhanced","true"),n}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,i){e.setAttribute("sandbox",t.join(" ")),e.setAttribute("allow",i.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,i){return e(this,void 0,void 0,(function*(){var e;const n=`${r.CLIENT_URL}/embed/${t}`,o=new URLSearchParams;i.width&&o.set("width","number"==typeof i.width?i.width.toString():i.width),i.height&&o.set("height","number"==typeof i.height?i.height.toString():i.height),i.resize&&o.set("resize",i.resize),i.autoscale&&o.set("autoscale","true"),i.adaptive&&o.set("adaptive",i.adaptive.toString()),i.responsive&&"number"==typeof i.responsive&&o.set("responsive",i.responsive.toString()),(null===(e=i.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 l();o.set("apiKey",e)}catch(e){d.warn("Failed to get auth token for iframe",e),r.API_KEY&&o.set("apiKey",r.API_KEY)}const s=`${n}?${o.toString()}`;return d.debug("Built secure iframe URL",{compositionId:t,url:s}),s}))}applyIframeStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;if(e.style.width="number"==typeof n?`${n}px`:n,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;a&&this.enableIframeAutoscale(e,t,a),d&&this.makeIframeResponsive(e,d)}makeIframeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableIframeAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)},d.debug("AutoScale enabled for iframe",{compositionId:t,config:n}))}setupLoadingOptimization(e,t,i){if(!i.enabled)return;const n=i.timeout||1e4,o=i.retryCount||3;let s=0;const a=()=>{s<o?(s++,d.warn(`Iframe loading failed, retrying (${s}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+s}),1e3*s)):(d.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},r=setTimeout((()=>{d.warn("Iframe loading timeout",{compositionId:t,timeout:n}),a()}),n);this.loadingTimeouts.set(t,r),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),d.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{d.error("Iframe error occurred",{compositionId:t}),a()}))}handleIframeFallback(e,t){const i=document.createElement("div");i.className="widgetic-iframe-fallback",i.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(i,e),e.parentNode.removeChild(e)),i.dispatchEvent(new CustomEvent("widgetic:fallback",{detail:{compositionId:t,reason:"loading_failed"},bubbles:!0}))}setupEnhancedIframeMessaging(e,t,i={}){const n=h({enableSignatureValidation:i.signatureValidation||!1,allowedOrigins:i.allowedOrigins,enableHeartbeat:!0,heartbeatInterval:3e4});n.registerHandler(t,(t=>{this.handleEnhancedIframeMessage(e,t)})),e.addEventListener("load",(()=>{n.sendMessage(t,{type:"config",instanceId:t,payload:{compositionId:t,apiUrl:c(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),d.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,d.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(d.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:d.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width:i,height:n}=t.payload;i&&n&&(e.style.width=`${i}px`,e.style.height=`${n}px`,e.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:i,height:n,instanceId:t.instanceId},bubbles:!0})),d.debug("Iframe resized",{width:i,height:n,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})),d.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})),d.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})),d.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})),d.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){h().sendMessage(e,{type:t,instanceId:e,payload:i,timestamp:Date.now(),version:"1.0"})}addLoadingIndicator(e,t){const i=document.createElement("div");i.className="widgetic-loading-indicator",i.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 `,i.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 n=document.createElement("style");n.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(n),e.appendChild(i)}removeLoadingIndicator(e){const t=e.querySelector(".widgetic-loading-indicator");t&&t.parentNode&&t.parentNode.removeChild(t)}createErrorElement(e,t){const i=document.createElement("div");return i.className="widgetic-error",i.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 `,i.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 `,i}cleanupWidget(e){const t=e.__resizeHandler,i=e.__widgetId;t&&i&&t.unregisterWidget(i);const n=e.__responsiveManager,o=e.__responsiveId;n&&o&&n.unregisterWidget(o);const s=e.__messenger,a=e.__messagingCompositionId;s&&a&&s.unregisterHandler(a);const r=this.loadingTimeouts.get(a);r&&(clearTimeout(r),this.loadingTimeouts.delete(a)),a&&this.iframeRegistry.delete(a),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),d.debug("Iframe cleanup complete",{compositionId:a})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,i,n){const o=x(),s=h(),a={breakpoint:n,debounceDelay:150},r=`responsive-${i}`;o.registerWidget(r,t,a,(t=>{d.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),s.sendMessage(i,{type:"responsive",instanceId:i,compositionId:i,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:i,compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width},bubbles:!0}))})),e.__responsiveId=r,e.__responsiveManager=o,d.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:r})}setupIframeMediaListener(e,t){const i=u(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:media:"))){const o=n.data.type.replace("widgetic:media:","");if(["play","pause","stop","ended","seeking","volumechange"].includes(o)){const s=e.getAttribute("data-widget-config"),a=s?JSON.parse(s):{};i.handleMediaEvent({type:o,compositionId:t,config:a.media||{},data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=g(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:content:"))){const o=n.data.type.replace("widgetic:content:","");if(["position","navigate","complete","reset","metadata"].includes(o)){const s=e.getAttribute("data-widgetic-config");let a={};if(s)try{a=JSON.parse(s).content||{}}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._contentListenerCleanup=()=>{window.removeEventListener("message",n)}}}let C=null;var S=Object.freeze({__proto__:null,IframeRenderer:k,getIframeRenderer:function(){return C||(C=new k),C}});class W{constructor(){this.batchClient=s(),this.moduleLoader=a(),this.customElementRenderer=new v,this.iframeRenderer=new k,this.renderedWidgets=new Map}renderWidget(t){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId),i=this.createLoadingElement(t.container);t.container&&i&&t.container.appendChild(i);try{const n=yield this.batchClient.getComposition(t.compositionId),o=yield this.batchClient.getWidget(n.widgetId),s=this.determineRenderMode(t.renderMode,o);let a;if("custom-element"===s)try{a=yield this.moduleLoader.loadModule(o)}catch(s){const a=yield this.renderWithIframe(e,t,n,o);return this.removeLoadingElement(i),a}const d="iframe"===s?yield this.renderWithIframe(e,t,n,o):yield this.renderWithCustomElement(e,t,n,o,a);return this.removeLoadingElement(i),this.renderedWidgets.set(e,d),this.emitWidgetEvent("ready",{widgetId:e,compositionId:t.compositionId,renderMode:d.renderMode,loadTime:(null==a?void 0:a.loadTime)||0,cached:(null==a?void 0:a.cached)||!1}),d}catch(n){if(this.removeLoadingElement(i),this.emitWidgetEvent("error",{widgetId:e,compositionId:t.compositionId,error:n instanceof Error?n.message:String(n),fallback:"iframe"}),t.container){const e=this.createErrorElement(t.compositionId,n);t.container.appendChild(e)}try{const i=yield this.renderFallback(e,t);if(t.container){const e=t.container.querySelector(".widgetic-error");e&&e.remove()}return i}catch(e){throw new Error(`Widget rendering failed: ${n}. Fallback also failed: ${e}`)}}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){const i=t.map((e=>e.compositionId)),n=yield this.batchClient.getCompositions(i),o=new Map(n.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 a=s.size>0?yield this.batchClient.getWidgets(Array.from(s)):[],d=new Map(a.map((e=>[e.id,e]))),r=a.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));r.length>0&&(yield this.moduleLoader.preloadModules(r));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"},i=d.get(e.widgetId)||{id:e.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(t,e,i)}))));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 i={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(i)}))}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,i,n){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId);if("custom-element"===this.determineRenderMode(t.renderMode,n))try{const o=yield this.moduleLoader.loadModule(n);return this.renderWithCustomElement(e,t,i,n,o)}catch(e){}return this.renderWithIframe(e,t,i,n)}))}renderWithCustomElement(t,i,n,o,s){return e(this,void 0,void 0,(function*(){const e=yield this.customElementRenderer.render({compositionId:i.compositionId,compositionData:n,widgetData:o,loadedModule:s,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive});return i.container&&i.container.appendChild(e.element),{id:t,element:e.element,compositionData:n,widgetData:o,loadedModule:s,renderMode:"custom-element",cleanup:()=>{e.element.remove()}}}))}renderWithIframe(t,i,n,o){return e(this,void 0,void 0,(function*(){return yield this.iframeRenderer.renderWidget({compositionId:i.compositionId,compositionData:n,widgetData:o,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:i.container})}))}renderFallback(t,i){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: ${i.compositionId}</small>\n </div>\n `,i.container&&i.container.appendChild(e),{id:t,element:e,compositionData:{id:i.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 i;if("auto"!==e)return e;const n="undefined"!=typeof customElements&&"function"==typeof customElements.define,o=(null==t?void 0:t.moduleUrl)||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.supportsCustomElements);return n&&o?"custom-element":"iframe"}generateWidgetId(e){return`widget-${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}emitWidgetEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:t,bubbles:!0});document.dispatchEvent(i)}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 i=document.createElement("div");i.className="widgetic-error",i.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 n=t instanceof Error?t.message:"Unknown error occurred",o=this.analyzeError(n,t);return i.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 `,i}analyzeError(e,t){const i=e.toLowerCase();return i.includes("composition not found")||i.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 `}:i.includes("unauthorized")||i.includes("forbidden")||i.includes("401")||i.includes("403")||i.includes("permission")||i.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 `}:i.includes("deleted")||i.includes("expired")||i.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 `}:i.includes("subscription")||i.includes("billing")||i.includes("payment")||i.includes("plan")||i.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 `}:i.includes("timeout")||i.includes("network")||i.includes("connection")||i.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 M=null;function L(){return M||(M=new W),M}function $(){M&&M.cleanupAll(),M=null}var A=Object.freeze({__proto__:null,WidgetRenderer:W,getWidgetRenderer:L,resetWidgetRenderer:$});export{v as C,k as I,b as W,W as a,$ as b,y as c,L as g,S as i,f as r,A as w};
|
|
1
|
+
import{_ as e}from"./vendor.js";import{r as t,a as i,E as n,b as o,g as s,d as a,c as d}from"./api.js";import{l as r,a as c,b as l,d as u}from"./core.js";import{g,a as h}from"./media.js";import{getMessenger as m}from"./messaging.js";import{R as p}from"./display.js";const b="undefined"!=typeof HTMLElement?HTMLElement:class{};class f extends b{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(),r.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){if(!this.isWidgetConnected){this.isWidgetConnected=!0,r.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const e=this.getAttribute("composition-id");if(!e)throw new Error("composition-id attribute is required");const s=yield t(e);if("refused"===s.status)throw i(e,s.refusal),new Error(n);const a="found"===s.status?s.payload:null;if(null==a?void 0:a.embedUrl)return this.innerHTML="",this.appendChild(o(a.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",e,a)),void this.setWidgetReady();yield this.loadWidgetData(e),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){r.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(r.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(r.debug("WidgeticWidget attribute changed",{instanceId:this.instanceId,attribute:e,oldValue:t,newValue:i}),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){r.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(t){return e(this,void 0,void 0,(function*(){const e=s();this.compositionData=yield e.getComposition(t),this.widgetData=yield e.getWidget(this.compositionData.widgetId),r.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:t,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=a();this.loadedModule=yield e.loadModule(this.widgetData),r.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,r.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw r.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,i){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,n=window.ReactDOM,o=this.getWidgetProps(),s=e.createElement(i,o);n.render(s,t)}}))}initializeVueComponent(t,i){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,n=this.getWidgetProps();new e({el:t,render:e=>e(i,{props:n})})}}))}initializeSvelteOrVanillaComponent(t,i){return e(this,void 0,void 0,(function*(){var e;const n=this.getWidgetProps();if(i.$$prop_def||(null===(e=i.prototype)||void 0===e?void 0:e.$$prop_def))this.svelteComponent=new i({target:t,props:n});else if(i.prototype&&i.prototype.constructor===i){const e=new i(t,n);"function"==typeof e.render&&(yield e.render())}else if("function"==typeof i)yield i(t,n);else{if(!i||"function"!=typeof i.init)throw new Error("Unknown component type");yield i.init(t,n)}}))}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 i=this.getAttribute("width")||"100%",n=this.getAttribute("height")||"400",o=this.getAttribute("resize")||"responsive";switch(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof n?`${n}px`:n,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"),i=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"!==i&&"fill-width"!==i||this.setupAdaptiveBehavior(e)}setupAdaptiveBehavior(e){const t=window.matchMedia(`(max-width: ${e}px)`),i=t=>{this.setAttribute("data-mobile",t.matches?"true":"false"),this.dispatchEvent(new CustomEvent("widgetic:adaptive",{detail:{isMobile:t.matches,breakpoint:e}}))};i(t),t.addEventListener("change",i),this.eventListeners.set("adaptive",(()=>{t.removeEventListener("change",i)}))}handleAutoscale(e){const{width:t,height:i}=e.contentRect;this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:t,height:i}})),this.widgetState.data.dimensions={width:t,height:i}}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,i=new FormData(t),n={};i.forEach(((e,t)=>{n[t]=e})),this.widgetState.data.formData=n,this.dispatchEvent(new CustomEvent("widgetic:form-submit",{detail:{data:n,form:t},bubbles:!0})),r.debug("Form submitted",{instanceId:this.instanceId,data:n})}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})),r.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})),r.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){r.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(),r.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function w(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",f),r.info("WidgeticWidget custom element registered")))}class v{constructor(){this.observers=new Map,this.mutationObservers=new Map,this.timeouts=new Map,this.animationIds=new Map,this.storageKey="widgetic_autoscale_heights"}static getInstance(){return v.instance||(v.instance=new v),v.instance}enableAutoScale(e,t,i={enabled:!0}){if(!i.enabled)return;const n=Object.assign({minHeight:i.minHeight||50,maxHeight:i.maxHeight||2e3,debounceDelay:i.debounceDelay||150,threshold:i.threshold||5,animate:!1!==i.animate,animationDuration:i.animationDuration||300},i),o=e.offsetHeight,s=this.getStoredHeight(t);s&&s!==o&&this.setElementHeight(e,s,n.animate,n.animationDuration),this.setupContentMonitoring(e,t,n,o)}disableAutoScale(e){const t=this.observers.get(e);t&&(t.disconnect(),this.observers.delete(e));const i=this.mutationObservers.get(e);i&&(i.disconnect(),this.mutationObservers.delete(e));const n=this.timeouts.get(e);n&&(clearTimeout(n),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){try{const t=localStorage.getItem(this.storageKey);if(!t)return null;const i=JSON.parse(t),n=i[e];if(!n)return null;const o=864e5;return Date.now()-n.lastUpdated>o?(delete i[e],localStorage.setItem(this.storageKey,JSON.stringify(i)),null):n.height}catch(e){return null}}storeHeight(e,t,i){try{const n=localStorage.getItem(this.storageKey),o=n?JSON.parse(n):{};o[e]={compositionId:e,height:t,originalHeight:i,lastUpdated:Date.now()},localStorage.setItem(this.storageKey,JSON.stringify(o))}catch(e){}}setupContentMonitoring(e,t,i,n){const o=this.findContentElement(e);if(!o)return void e.tagName.toLowerCase();const s=this.createDebouncedHeightUpdate(e,t,i,n);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 a=new MutationObserver((()=>{const e=o.scrollHeight;s(e)}));a.observe(o,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,a);const d=o.scrollHeight;s(d)}findContentElement(e){var t;if("iframe"===e.tagName.toLowerCase())try{const i=e,n=i.contentDocument||(null===(t=i.contentWindow)||void 0===t?void 0:t.document);if(null==n?void 0:n.body)return n.body}catch(t){return this.setupIframePostMessageListener(e),null}const i=e.tagName.toLowerCase();if("widgetic"===i||"widgetic-widget"===i||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",i=i=>{var n,o;if(i.source===e.contentWindow&&("widgetic:autoscale"===(null===(n=i.data)||void 0===n?void 0:n.type)||"autoscale"===(null===(o=i.data)||void 0===o?void 0:o.type))){const{height:n,contentHeight:o}=i.data.payload||i.data;if("number"==typeof n&&n>0){const i=this.getConfigForWidget(t),s=Math.max(i.minHeight||50,Math.min(i.maxHeight||2e3,n));this.setElementHeight(e,s,i.animate,i.animationDuration),this.storeHeight(t,s,e.offsetHeight),e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:e.offsetHeight,newHeight:s,contentHeight:o||n}}))}}};window.addEventListener("message",i),e._autoscaleMessageCleanup=()=>{window.removeEventListener("message",i)}}getConfigForWidget(e){return{enabled:!0,minHeight:50,maxHeight:2e3,animate:!0,animationDuration:300,debounceDelay:150,threshold:5}}createDebouncedHeightUpdate(e,t,i,n){let o=e.offsetHeight;return s=>{const a=this.timeouts.get(t);a&&clearTimeout(a);const d=setTimeout((()=>{const a=Math.max(i.minHeight,Math.min(i.maxHeight,s));Math.abs(a-o)>=i.threshold&&(this.setElementHeight(e,a,i.animate,i.animationDuration),this.storeHeight(t,a,n),o=a,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:o,newHeight:a,contentHeight:s}}))),this.timeouts.delete(t)}),i.debounceDelay);this.timeouts.set(t,d)}}setElementHeight(e,t,i=!0,n=300){if(!i)return void(e.style.height=`${t}px`);const o=e.offsetHeight,s=t-o;if(Math.abs(s)<1)return;const a=this.animationIds.get(e.id||e.tagName);a&&cancelAnimationFrame(a);const d=performance.now(),r=o,c=i=>{const o=i-d,a=Math.min(o/n,1),l=1-Math.pow(1-a,3),u=r+s*l;if(e.style.height=`${u}px`,a<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 y{constructor(){this.autoScaleManager=v.getInstance(),w()}render(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i="100%",height:n="400",resize:o="responsive",autoscale:s=!0,adaptive:a=768,media:d,content:r}=t,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",e),c.setAttribute("width",String(i)),c.setAttribute("height",String(n)),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(a)),d&&Object.keys(d).length>0){g().registerWidget(e,d),this.setupCustomElementMediaListener(c,e)}if(r&&Object.keys(r).length>0){h().registerWidget(e,r),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,i,n){return e(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(t,i,n){return e(this,void 0,void 0,(function*(){if(i.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const e=window.React,o=window.ReactDOM,s=e.createElement(i,{config:n.config,metadata:n.metadata});o.render(s,t)}else{if(!i._isVue&&!i.__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(i,{props:{config:n.config,metadata:n.metadata}})})}}))}applyElementStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;switch(e.style.width="number"==typeof n?`${n}px`:n,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,d||768)}if(a){("boolean"==typeof a?a:a&&"object"==typeof a&&a.enabled)&&this.enableAutoscale(e,t,a)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),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 i=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;">${i}</small>\n </div>\n </div>\n `,e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:i}}))}setupCustomElementMediaListener(e,t){const i=g(),n=t=>{const{command:i}=t.detail;if("pause"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");t.forEach((e=>{e.paused||e.pause()})),i.forEach((e=>{e.paused||e.pause()}))}else if("play"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video"),n=Array.from(t).concat(Array.from(i)).find((e=>e.currentTime>0&&!e.ended));n&&n.play().catch((()=>{}))}};e.addEventListener("widgetic:media:command",n),e._mediaCommandCleanup=()=>{e.removeEventListener("widgetic:media:command",n)};const o=(n,o)=>s=>{const a=(e.__widgetConfig||{}).media||{},d="audio"===n.tagName.toLowerCase()?"audio":"video";i.handleMediaEvent({type:o,compositionId:t,config:a,data:{position:n.currentTime,duration:n.duration,volume:n.volume,mediaType:d,title:n.title||n.getAttribute("data-title")||void 0}})},s=()=>{const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");Array.from(t).concat(Array.from(i)).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 a=new MutationObserver((()=>{s()}));a.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{a.disconnect()}}setupCustomElementContentListener(e,t){const i=h(),n=n=>{if(n.detail&&n.detail.type){const o=n.detail.type,s=n.detail.data||n.detail;let a={};try{const t=e.getAttribute("data-content-config");t&&(a=JSON.parse(t))}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:s})}};e.addEventListener("widgetic:content:position",n),e.addEventListener("widgetic:content:navigate",n),e.addEventListener("widgetic:content:complete",n),e.addEventListener("widgetic:content:reset",n),e.addEventListener("widgetic:content:metadata",n),e._contentPositionCleanup=()=>{e.removeEventListener("widgetic:content:position",n),e.removeEventListener("widgetic:content:navigate",n),e.removeEventListener("widgetic:content:complete",n),e.removeEventListener("widgetic:content:reset",n),e.removeEventListener("widgetic:content:metadata",n)}}}var I=Object.freeze({__proto__:null,CustomElementRenderer:y});class E{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&r.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void r.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,s=i.initialMode||(o<i.breakpoint?"mobile":"desktop"),a={mode:s,breakpoint:i.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,a),this.callbacks.set(e,n);const d=new ResizeObserver((t=>{this.handleResize(e,t,i)}));d.observe(t),this.observers.set(e,d),n(a),r.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:s,containerWidth:o})}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e));const i=this.observers.get(e);i&&(i.disconnect(),this.observers.delete(e)),this.callbacks.delete(e),this.currentStates.delete(e),r.debug("Widget unregistered from responsive monitoring",{widgetId:e})}getCurrentState(e){return this.currentStates.get(e)||null}checkResponsiveState(e,t){const i=this.currentStates.get(e),n=this.callbacks.get(e);if(!i||!n)return void r.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<i.breakpoint?"mobile":"desktop";if(o!==i.mode){const s={mode:o,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,s),n(s),r.info("Responsive state changed manually",{widgetId:e,from:i.mode,to:o,width:t,breakpoint:i.breakpoint})}}handleResize(e,t,i){const n=this.debounceTimers.get(e);n&&clearTimeout(n);const o=setTimeout((()=>{this.processResize(e,t,i),this.debounceTimers.delete(e)}),i.debounceDelay||150);this.debounceTimers.set(e,o)}processResize(e,t,i){const n=this.currentStates.get(e),o=this.callbacks.get(e);if(!n||!o)return;const s=t[t.length-1];if(!s)return;const a=s.contentRect.width,d=a<i.breakpoint?"mobile":"desktop";if(d!==n.mode){const t={mode:d,breakpoint:i.breakpoint,width:a,timestamp:Date.now()};this.currentStates.set(e,t),o(t),r.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:d,width:a,breakpoint:i.breakpoint})}else if(Math.abs(a-n.width)>10){const t=Object.assign(Object.assign({},n),{width:a,timestamp:Date.now()});this.currentStates.set(e,t),r.debug("Container width updated",{widgetId:e,width:a,mode:n.mode,breakpoint:i.breakpoint})}}getRegisteredWidgets(){return Array.from(this.observers.keys())}cleanup(){const e=this.getRegisteredWidgets();for(const t of e)this.unregisterWidget(t);r.debug("ResponsiveManager cleanup complete")}}let x=null;function k(){return x||(x=new E),x}class C{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=v.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i,height:n,resize:o="fixed",autoscale:s=!1,adaptive:a,responsive:c,container:l,allowFullscreen:u=!0,sandbox:m=this.getDefaultSandboxPermissions(),allowedFeatures:b=this.getDefaultAllowedFeatures(),loading:f="lazy",enableResize:w=!0,compositionData:v,widgetData:y,security:I={},fallback:E={enabled:!0,timeout:1e4,retryCount:3},media:x}=t;if(!i||!n||!l)throw new Error("Missing required parameters: width, height, and container are required");const k=v||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},C=y||{id:k.widgetId,name:`Widget ${e}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]};try{const v=this.createSecureIframe(e,t);v.src=yield this.buildSecureIframeUrl(e,t),v.title=`Widgetic Widget: ${k.name||e}`,v.loading=f,this.applySandboxSecurity(v,m,b),v.width=i.toString(),v.height=n.toString(),v.frameBorder="0",v.scrolling="no",u&&(v.allowFullscreen=!0,v.setAttribute("allowfullscreen","")),v.title=`Widgetic Widget ${e}`,v.setAttribute("aria-label",`${d("interactiveWidget")}: ${e}`);const y={compositionId:e,renderMode:"iframe",displayMode:"inline",resize:o,width:"number"==typeof i?i:parseInt(i.toString()),height:"number"==typeof n?n:parseInt(n.toString()),autoscale:s,adaptive:a,responsive:c,media:x},S=p.generateIframeCSS(y);S&&(v.style.cssText+=S),this.applyIframeStyling(v,e,{width:i,height:n,resize:o,autoscale:s,adaptive:a}),v.style.visibility="hidden",v.style.opacity="0",v.style.transition="opacity 0.3s ease",this.addLoadingIndicator(l,y),this.setupEnhancedIframeMessaging(v,e,I),this.setupLoadingOptimization(v,e,E);const W="lazy"===f,M=new Promise(((t,i)=>{let n=null;W||(n=setTimeout((()=>{i(new Error(`Iframe load timeout for composition: ${e}`))}),E.timeout||1e4)),v.onload=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(l),v.style.visibility="visible",v.style.opacity="1",t()},v.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(l),i(new Error(`Failed to load iframe for composition: ${e}`))}}));if(l.appendChild(v),w&&"undefined"!=typeof ResizeObserver){const t=new p({observeResize:!0}),i=`iframe-${e}-${Date.now()}`;v.setAttribute("data-widget-id",i),t.registerWidget(i,v,l,y),v.__resizeHandler=t,v.__widgetId=i}c&&"number"==typeof c&&c>0&&this.setupResponsiveMonitoring(v,l,e,c),this.iframeRegistry.set(e,v),v.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),W||(yield M);const L=`iframe-${e}-${Date.now()}`;if(r.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:i,height:n},resize:o,autoscale:s,responsive:c,sandbox:m.join(" "),features:b.join("; ")}),y.media&&Object.keys(y.media).length>0){g().registerWidget(e,y.media),this.setupIframeMediaListener(v,e)}if(t.content&&Object.keys(t.content).length>0){h().registerWidget(e,t.content),this.setupIframeContentListener(v,e)}return{id:L,element:v,compositionData:k,widgetData:C,renderMode:"iframe",cleanup:()=>this.cleanupWidget(v)}}catch(t){throw r.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(l),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){r.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(e),n=[];for(let e=0;e<i.length;e++){const o=i[e],s=t[e];if("fulfilled"===o.status)n.push(o.value);else{r.error("Iframe widget rendering failed in batch",{compositionId:s.compositionId,error:o.reason});const e=`error-${s.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(s,o.reason),compositionData:{id:s.compositionId,name:`Composition ${s.compositionId}`,widgetId:`widget-${s.compositionId}`,config:{}},widgetData:{id:`widget-${s.compositionId}`,name:`Widget ${s.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return r.info("Iframe batch rendering complete",{total:t.length,successful:n.filter((e=>"IFRAME"===e.element.tagName)).length,failed:n.filter((e=>"IFRAME"!==e.element.tagName)).length}),n}))}createSecureIframe(e,t){var i;const n=document.createElement("iframe");return n.style.border="none",n.style.display="block",n.style.overflow="hidden",n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("crossorigin","anonymous"),(null===(i=t.security)||void 0===i?void 0:i.enableCSP)&&n.setAttribute("csp",this.generateCSP(t.security.allowedOrigins)),n.setAttribute("data-widgetic-id",e),n.setAttribute("data-enhanced","true"),n}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,i){e.setAttribute("sandbox",t.join(" ")),e.setAttribute("allow",i.join("; ")),e.setAttribute("fetchpriority","high")}generateCSP(e){const t=e||[c.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,i){return e(this,void 0,void 0,(function*(){var e;const n=`${c.CLIENT_URL}/embed/${t}`,o=new URLSearchParams;i.width&&o.set("width","number"==typeof i.width?i.width.toString():i.width),i.height&&o.set("height","number"==typeof i.height?i.height.toString():i.height),i.resize&&o.set("resize",i.resize),i.autoscale&&o.set("autoscale","true"),i.adaptive&&o.set("adaptive",i.adaptive.toString()),i.responsive&&"number"==typeof i.responsive&&o.set("responsive",i.responsive.toString()),(null===(e=i.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 u();o.set("apiKey",e)}catch(e){r.warn("Failed to get auth token for iframe",e),c.API_KEY&&o.set("apiKey",c.API_KEY)}const s=`${n}?${o.toString()}`;return r.debug("Built secure iframe URL",{compositionId:t,url:s}),s}))}applyIframeStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;if(e.style.width="number"==typeof n?`${n}px`:n,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;a&&this.enableIframeAutoscale(e,t,a),d&&this.makeIframeResponsive(e,d)}makeIframeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableIframeAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)},r.debug("AutoScale enabled for iframe",{compositionId:t,config:n}))}setupLoadingOptimization(e,t,i){if(!i.enabled)return;const n=i.timeout||1e4,o=i.retryCount||3;let s=0;const a=()=>{s<o?(s++,r.warn(`Iframe loading failed, retrying (${s}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+s}),1e3*s)):(r.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},d=setTimeout((()=>{r.warn("Iframe loading timeout",{compositionId:t,timeout:n}),a()}),n);this.loadingTimeouts.set(t,d),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),r.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{r.error("Iframe error occurred",{compositionId:t}),a()}))}handleIframeFallback(e,t){const i=document.createElement("div");i.className="widgetic-iframe-fallback",i.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(i,e),e.parentNode.removeChild(e)),i.dispatchEvent(new CustomEvent("widgetic:fallback",{detail:{compositionId:t,reason:"loading_failed"},bubbles:!0}))}setupEnhancedIframeMessaging(e,t,i={}){const n=m({enableSignatureValidation:i.signatureValidation||!1,allowedOrigins:i.allowedOrigins,enableHeartbeat:!0,heartbeatInterval:3e4});n.registerHandler(t,(t=>{this.handleEnhancedIframeMessage(e,t)})),e.addEventListener("load",(()=>{n.sendMessage(t,{type:"config",instanceId:t,payload:{compositionId:t,apiUrl:l(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),r.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,r.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(r.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:r.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width:i,height:n}=t.payload;i&&n&&(e.style.width=`${i}px`,e.style.height=`${n}px`,e.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:i,height:n,instanceId:t.instanceId},bubbles:!0})),r.debug("Iframe resized",{width:i,height:n,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})),r.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})),r.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})),r.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})),r.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){m().sendMessage(e,{type:t,instanceId:e,payload:i,timestamp:Date.now(),version:"1.0"})}addLoadingIndicator(e,t){const i=document.createElement("div");i.className="widgetic-loading-indicator",i.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 `,i.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 n=document.createElement("style");n.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(n),e.appendChild(i)}removeLoadingIndicator(e){const t=e.querySelector(".widgetic-loading-indicator");t&&t.parentNode&&t.parentNode.removeChild(t)}createErrorElement(e,t){const i=document.createElement("div");return i.className="widgetic-error",i.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 `,i.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 `,i}cleanupWidget(e){const t=e.__resizeHandler,i=e.__widgetId;t&&i&&t.unregisterWidget(i);const n=e.__responsiveManager,o=e.__responsiveId;n&&o&&n.unregisterWidget(o);const s=e.__messenger,a=e.__messagingCompositionId;s&&a&&s.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),r.debug("Iframe cleanup complete",{compositionId:a})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,i,n){const o=k(),s=m(),a={breakpoint:n,debounceDelay:150},d=`responsive-${i}`;o.registerWidget(d,t,a,(t=>{r.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),s.sendMessage(i,{type:"responsive",instanceId:i,compositionId:i,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:i,compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width},bubbles:!0}))})),e.__responsiveId=d,e.__responsiveManager=o,r.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:d})}setupIframeMediaListener(e,t){const i=g(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:media:"))){const o=n.data.type.replace("widgetic:media:","");if(["play","pause","stop","ended","seeking","volumechange"].includes(o)){const s=e.getAttribute("data-widget-config"),a=s?JSON.parse(s):{};i.handleMediaEvent({type:o,compositionId:t,config:a.media||{},data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=h(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:content:"))){const o=n.data.type.replace("widgetic:content:","");if(["position","navigate","complete","reset","metadata"].includes(o)){const s=e.getAttribute("data-widgetic-config");let a={};if(s)try{a=JSON.parse(s).content||{}}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._contentListenerCleanup=()=>{window.removeEventListener("message",n)}}}let S=null;var W=Object.freeze({__proto__:null,IframeRenderer:C,getIframeRenderer:function(){return S||(S=new C),S}});class M{constructor(){this.batchClient=s(),this.moduleLoader=a(),this.customElementRenderer=new y,this.iframeRenderer=new C,this.renderedWidgets=new Map}renderWidget(t){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId),i=this.createLoadingElement(t.container);t.container&&i&&t.container.appendChild(i);try{const n=yield this.batchClient.getComposition(t.compositionId),o=yield this.batchClient.getWidget(n.widgetId),s=this.determineRenderMode(t.renderMode,o);let a;if("custom-element"===s)try{a=yield this.moduleLoader.loadModule(o)}catch(s){const a=yield this.renderWithIframe(e,t,n,o);return this.removeLoadingElement(i),a}const d="iframe"===s?yield this.renderWithIframe(e,t,n,o):yield this.renderWithCustomElement(e,t,n,o,a);return this.removeLoadingElement(i),this.renderedWidgets.set(e,d),this.emitWidgetEvent("ready",{widgetId:e,compositionId:t.compositionId,renderMode:d.renderMode,loadTime:(null==a?void 0:a.loadTime)||0,cached:(null==a?void 0:a.cached)||!1}),d}catch(n){if(this.removeLoadingElement(i),this.emitWidgetEvent("error",{widgetId:e,compositionId:t.compositionId,error:n instanceof Error?n.message:String(n),fallback:"iframe"}),t.container){const e=this.createErrorElement(t.compositionId,n);t.container.appendChild(e)}try{const i=yield this.renderFallback(e,t);if(t.container){const e=t.container.querySelector(".widgetic-error");e&&e.remove()}return i}catch(e){throw new Error(`Widget rendering failed: ${n}. Fallback also failed: ${e}`)}}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){const i=t.map((e=>e.compositionId)),n=yield this.batchClient.getCompositions(i),o=new Map(n.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 a=s.size>0?yield this.batchClient.getWidgets(Array.from(s)):[],d=new Map(a.map((e=>[e.id,e]))),r=a.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));r.length>0&&(yield this.moduleLoader.preloadModules(r));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"},i=d.get(e.widgetId)||{id:e.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(t,e,i)}))));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 i={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(i)}))}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,i,n){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId);if("custom-element"===this.determineRenderMode(t.renderMode,n))try{const o=yield this.moduleLoader.loadModule(n);return this.renderWithCustomElement(e,t,i,n,o)}catch(e){}return this.renderWithIframe(e,t,i,n)}))}renderWithCustomElement(t,i,n,o,s){return e(this,void 0,void 0,(function*(){const e=yield this.customElementRenderer.render({compositionId:i.compositionId,compositionData:n,widgetData:o,loadedModule:s,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive});return i.container&&i.container.appendChild(e.element),{id:t,element:e.element,compositionData:n,widgetData:o,loadedModule:s,renderMode:"custom-element",cleanup:()=>{e.element.remove()}}}))}renderWithIframe(t,i,n,o){return e(this,void 0,void 0,(function*(){return yield this.iframeRenderer.renderWidget({compositionId:i.compositionId,compositionData:n,widgetData:o,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:i.container})}))}renderFallback(t,i){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: ${i.compositionId}</small>\n </div>\n `,i.container&&i.container.appendChild(e),{id:t,element:e,compositionData:{id:i.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 i;if("auto"!==e)return e;const n="undefined"!=typeof customElements&&"function"==typeof customElements.define,o=(null==t?void 0:t.moduleUrl)||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.supportsCustomElements);return n&&o?"custom-element":"iframe"}generateWidgetId(e){return`widget-${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}emitWidgetEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:t,bubbles:!0});document.dispatchEvent(i)}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 i=document.createElement("div");i.className="widgetic-error",i.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 n=t instanceof Error?t.message:"Unknown error occurred",o=this.analyzeError(n,t);return i.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 `,i}analyzeError(e,t){const i=e.toLowerCase();return i.includes("composition not found")||i.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 `}:i.includes("unauthorized")||i.includes("forbidden")||i.includes("401")||i.includes("403")||i.includes("permission")||i.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 `}:i.includes("deleted")||i.includes("expired")||i.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 `}:i.includes("subscription")||i.includes("billing")||i.includes("payment")||i.includes("plan")||i.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 `}:i.includes("timeout")||i.includes("network")||i.includes("connection")||i.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 L=null;function $(){return L||(L=new M),L}function A(){L&&L.cleanupAll(),L=null}var z=Object.freeze({__proto__:null,WidgetRenderer:M,getWidgetRenderer:$,resetWidgetRenderer:A});export{y as C,C as I,f as W,M as a,A as b,I as c,$ as g,W as i,w as r,z as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as t}from"./core.js";import{M as e,d as i,e as a,f as r}from"./api.js";function s(e){const i=e.getAttribute("composition-id");if(!i)throw new Error("Missing required composition-id attribute");return{compositionId:i,renderMode:n(e.getAttribute("render-mode")),displayMode:o(e.getAttribute("display-mode")),resize:u(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||t.width,height:parseInt(e.getAttribute("height")||"")||t.height,autoscale:S(e),adaptive:l(e.getAttribute("adaptive")),responsive:c(e.getAttribute("responsive")),device:R(e),fullscreen:d(e),triggers:T(e),overlay:g(e),popup:w(e),media:I(e),content:E(e)}}function n(t){switch(t){case"iframe":case"custom-element":return t;default:return"auto"}}function o(t){switch(t){case"overlay":case"popup":case"fullscreen":case"modal":return t;default:return"inline"}}function u(t){switch(t){case"fill-width":case"fill-height":case"fixed":case"fixed-height":case"fixed-width":case"allow-scale-down":case"fill":return t;default:return"fixed"}}function l(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function c(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function d(t){if("enabled"===t.getAttribute("fullscreen")||"true"===t.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:p(t.getAttribute("fullscreen-trigger")),showControls:"false"!==t.getAttribute("fullscreen-controls"),exitOnEscape:"false"!==t.getAttribute("fullscreen-exit-on-escape"),allowAutoEnter:"true"===t.getAttribute("fullscreen-auto-enter")}}function p(t){switch(t){case"click":case"double-click":case"hover":case"auto":case"manual":return t;default:return"click"}}function g(t){if("enabled"===t.getAttribute("overlay")||"true"===t.getAttribute("overlay-enabled"))return{enabled:!0,position:v(t.getAttribute("overlay-position")),backdrop:m(t),background:f(t,m(t)),closeOnBackdropClick:"false"!==t.getAttribute("overlay-close-on-backdrop"),closeOnEscape:"false"!==t.getAttribute("overlay-close-on-escape"),showCloseButton:"false"!==t.getAttribute("overlay-close-button"),trigger:h(t.getAttribute("overlay-trigger")),width:t.getAttribute("overlay-width")||void 0,height:t.getAttribute("overlay-height")||void 0,maxWidth:t.getAttribute("overlay-max-width")||void 0,maxHeight:t.getAttribute("overlay-max-height")||void 0,zIndex:parseInt(t.getAttribute("overlay-z-index")||"")||void 0,animation:y(t.getAttribute("overlay-animation")),overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:A(t.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==t.getAttribute("keep-dimensions"),embedTarget:t.getAttribute("embed-target")||void 0}}function b(t){return"true"===t.getAttribute("overlay-backdrop")}function m(t){return"false"!==t.getAttribute("overlay-backdrop")}function f(t,e){if(!e)return;const i=t.getAttribute("overlay-background-color")||void 0,a=t.getAttribute("overlay-background-opacity"),r=null===a?Number.NaN:Number(a);return{enabled:!0,color:i,opacity:Number.isFinite(r)?r:void 0}}function h(t){switch(t){case"click":case"hover":case"manual":case"auto":return t;default:return"click"}}function y(t){switch(t){case"fade":case"slide-up":case"slide-down":case"slide-left":case"slide-right":case"zoom":case"bounce":case"none":return t;case"scale":return"zoom";case"slide":return"slide-up";default:return"fade"}}function v(t){switch(t){case"top":case"bottom":case"left":case"right":case"top-left":case"top-right":case"bottom-left":case"bottom-right":return t;case"top-center":return"top";case"center-left":return"left";case"center-right":return"right";case"bottom-center":return"bottom";default:return"center"}}function A(t){switch(t){case"fillWidth":return"fill-width";case"fillHeight":return"fill-height";case"fixedSize":return"fixed";case"fixedHeight":return"fixed-height";case"fixedWidth":return"fixed-width";case"allowScaleDown":return"allow-scale-down";case"fill":return"fill";default:return}}function w(t){if("enabled"===t.getAttribute("popup")||"true"===t.getAttribute("popup-enabled"))return{enabled:!0,trigger:k(t.getAttribute("popup-trigger")),width:parseInt(t.getAttribute("popup-width")||"")||void 0,height:parseInt(t.getAttribute("popup-height")||"")||void 0,centerScreen:"false"!==t.getAttribute("popup-center"),allowResize:"true"===t.getAttribute("popup-resizable"),showToolbar:"true"===t.getAttribute("popup-toolbar"),target:t.getAttribute("popup-target")||void 0}}function k(t){switch(t){case"click":case"manual":return t;default:return"click"}}function S(t){const e=t.getAttribute("autoscale");return!!e&&(("true"===e||""===e||"false"!==e)&&(z(t)||!0))}function z(t){return t.getAttribute("autoscale-min-height")||t.getAttribute("autoscale-max-height")||t.getAttribute("autoscale-debounce")||t.getAttribute("autoscale-threshold")||t.getAttribute("autoscale-animate")||t.getAttribute("autoscale-animation-duration")?{enabled:!0,minHeight:parseInt(t.getAttribute("autoscale-min-height")||"")||void 0,maxHeight:parseInt(t.getAttribute("autoscale-max-height")||"")||void 0,debounceDelay:parseInt(t.getAttribute("autoscale-debounce")||"")||void 0,threshold:parseInt(t.getAttribute("autoscale-threshold")||"")||void 0,animate:"false"!==t.getAttribute("autoscale-animate"),animationDuration:parseInt(t.getAttribute("autoscale-animation-duration")||"")||void 0}:null}function C(t){return`${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function x(t){return"widgetic"===t.tagName.toLowerCase()&&t.hasAttribute("composition-id")}function I(t){const e={},i=t.getAttribute("media-auto-pause")||t.getAttribute("data-media-auto-pause");null!==i&&(e.autoPause="true"===i||""===i);const a=t.getAttribute("media-type")||t.getAttribute("data-media-type");a&&["audio","video","both"].includes(a)&&(e.mediaType=a);const r=t.getAttribute("media-priority")||t.getAttribute("data-media-priority");if(r){const t=parseInt(r,10);!isNaN(t)&&t>=0&&t<=10&&(e.priority=t)}const s=t.getAttribute("media-persist-state")||t.getAttribute("data-media-persist-state");null!==s&&(e.persistState="true"===s||""===s);const n=t.getAttribute("media-allow-simultaneous")||t.getAttribute("data-media-allow-simultaneous");if(n){const t=n.split(",").map((t=>t.trim())).filter((t=>["audio","video"].includes(t)));t.length>0&&(e.allowSimultaneous=t)}const o=t.getAttribute("media-auto-resume")||t.getAttribute("data-media-auto-resume");null!==o&&(e.autoResume="true"===o||""===o);const u=t.getAttribute("media-auto-resume-timeout")||t.getAttribute("data-media-auto-resume-timeout");if(u){const t=parseInt(u,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const l=t.getAttribute("media-global-volume")||t.getAttribute("data-media-global-volume");return null!==l&&(e.globalVolume="true"===l||""===l),e}function E(t){const e={},i=t.getAttribute("content-type")||t.getAttribute("data-content-type");i&&["gallery","carousel","slider","stepper","tabs","list","custom"].includes(i)&&(e.contentType=i);const a=t.getAttribute("content-persist-state")||t.getAttribute("data-content-persist-state");null!==a&&(e.persistState="true"===a||""===a);const r=t.getAttribute("content-auto-resume")||t.getAttribute("data-content-auto-resume");null!==r&&(e.autoResume="true"===r||""===r);const s=t.getAttribute("content-auto-resume-timeout")||t.getAttribute("data-content-auto-resume-timeout");if(s){const t=parseInt(s,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const n=t.getAttribute("content-track-metadata")||t.getAttribute("data-content-track-metadata");return null!==n&&(e.trackMetadata="true"===n||""===n),Object.keys(e).length>0?e:void 0}function T(t){const e=t.getAttribute("embed-target");if("overlay"!==e&&"mixed"!==e)return;const i=function(t){switch(t){case"page-load":return"pageLoad";case"exit-intent":return"exitIntent";case"delay":return"delay";case"scroll":return"scroll";default:return}}(t.getAttribute("event-trigger")),a=parseInt(t.getAttribute("max-views")||""),r=parseInt(t.getAttribute("time-period")||""),s=Number.isFinite(a)&&a>0||Number.isFinite(r)&&r>0;return Object.assign(Object.assign(Object.assign({mode:e,eventTrigger:i},"overlay"===e&&"delay"===i?{delay:{enabled:!0,delayMs:N(t)}}:{}),"overlay"===e&&"scroll"===i?{scroll:{enabled:!0,threshold:.1,distance:L(t),direction:"down"}}:{}),{overlay:{position:t.getAttribute("overlay-position")||void 0,keepDimensions:"false"!==t.getAttribute("keep-dimensions"),zIndex:q(t),fullWidth:"true"===t.getAttribute("overlay-full-width")||void 0,overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:A(t.getAttribute("overlay-resize-mode")),backdrop:b(t),background:f(t,b(t)),closeButton:!0},recurrence:s?{enabled:!0,maxViews:Number.isFinite(a)&&a>0?a:Number.MAX_SAFE_INTEGER,timePeriodHours:Number.isFinite(r)&&r>0?r:24}:void 0})}function q(t){const i=parseInt(t.getAttribute("overlay-z-index")||"");if(Number.isFinite(i)&&!(i<=0))return Math.min(i,e)}function N(t){const e=parseInt(t.getAttribute("trigger-delay")||"");return!Number.isFinite(e)||e<0?i:Math.min(e,a)}function L(t){const e=parseInt(t.getAttribute("trigger-scroll-distance")||"");return Number.isFinite(e)&&e>0?e:r}function R(t){const e=t.getAttribute("device-mobile-enabled")||t.getAttribute("data-device-mobile-enabled"),i=t.getAttribute("device-desktop-enabled")||t.getAttribute("data-device-desktop-enabled");if(e||i)return{mobileEnabled:"false"!==e,desktopEnabled:"false"!==i}}var F=Object.freeze({__proto__:null,generateInstanceId:C,isValidWidgetElement:x,parseTriggerConfig:T,parseWidgetConfig:s});function O(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:_(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:M(),popupBlocking:P()}}function _(){if("undefined"==typeof performance||!performance.getEntriesByType)return!1;try{const t=performance.getEntriesByType("navigation");if(t.length>0){const e=t[0];return"h3"===e.nextHopProtocol||"h3-29"===e.nextHopProtocol}return!1}catch(t){return!1}}function M(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function P(){if("undefined"==typeof window||!window.open)return!1;try{const t=window.open("","widgetic-popup-test","width=1,height=1");return!t||(t.close(),!1)}catch(t){return!0}}function H(t,e){switch(t){case"custom-element":case"auto":default:return e.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function B(){if("undefined"==typeof localStorage)return!1;try{const t="widgetic-test";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch(t){return!1}}var j=Object.freeze({__proto__:null,checkSdkInitialization:function(){if("undefined"==typeof window)return!1;const t="widgetic-sdk-initialized";return B()?!!localStorage.getItem(t)||(localStorage.setItem(t,Date.now().toString()),!1):!!window.__widgeticInitialized},clearSdkInitialization:function(){B()&&localStorage.removeItem("widgetic-sdk-initialized"),delete window.__widgeticInitialized},detectBrowserCapabilities:O,determineBestRenderMode:H,hasIntersectionObserver:function(){return"undefined"!=typeof IntersectionObserver},isLocalStorageAvailable:B});class W{static analyzeElement(t){try{const e=this.getExplicitMetadata(t);return e||this.analyzeHeuristically(t)}catch(t){return null}}static getExplicitMetadata(t){const e=t.getAttribute("data-widget-meta");if(e)try{return JSON.parse(e)}catch(t){}const i=t.getAttribute("data-capabilities");if(i)return this.parseCapabilitiesString(i);const a=t.querySelector('script[type="application/json"]');if(a&&a.textContent)try{const t=JSON.parse(a.textContent);return t.capabilities||t.metadata}catch(t){}return null}static analyzeHeuristically(t){const e={type:"custom",version:"1.0.0"},i=t.getAttribute("data-widget-type")||t.getAttribute("data-type")||this.inferTypeFromStructure(t);switch(i&&(e.type=i),e.type){case"media":e.mediaCapabilities=this.analyzeMediaCapabilities(t);break;case"gallery":e.contentCapabilities=this.analyzeContentCapabilities(t);break;case"form":e.textCapabilities=this.analyzeTextCapabilities(t);break;case"interactive":e.interactionCapabilities=this.analyzeInteractionCapabilities(t)}return e.supportsResponsive=this.checkResponsiveSupport(t),e.supportsAutoscale=this.checkAutoscaleSupport(t),e.supportsThemes=this.checkThemeSupport(t),e.displayCapabilities=this.analyzeDisplayCapabilities(t),e.abTestingCapabilities=this.analyzeABTestingCapabilities(t),e}static inferTypeFromStructure(t){var e;return t.querySelector("video, audio")||t.classList.contains("media-widget")||(null===(e=t.getAttribute("data-widget-id"))||void 0===e?void 0:e.includes("video"))?"media":t.querySelector("form, input, textarea")||t.classList.contains("form-widget")?"form":t.querySelector(".gallery, .carousel")||t.classList.contains("gallery-widget")||t.querySelectorAll("img").length>1?"gallery":t.querySelector("button, .interactive")||t.classList.contains("quiz-widget")||t.classList.contains("poll-widget")?"interactive":"custom"}static analyzeMediaCapabilities(t){const e=t.querySelectorAll("video"),i=t.querySelectorAll("audio"),a=null!==t.querySelector("[controls]"),r=null!==t.querySelector("[data-volume], .volume-control");let s="audio";return e.length>0&&i.length>0?s="mixed":e.length>0&&(s="video"),{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:r||a,supportsSeek:a,supportsGlobalVolume:t.hasAttribute("data-global-volume"),mediaType:s}}static analyzeContentCapabilities(t){const e=t.querySelectorAll(".item, .slide, img, .content-item"),i=null!==t.querySelector(".nav, .navigation, button"),a=t.hasAttribute("data-position")||t.hasAttribute("data-track-position");let r="gallery";return t.classList.contains("carousel")&&(r="carousel"),t.classList.contains("list")&&(r="list"),t.classList.contains("grid")&&(r="grid"),{supportsPositionTracking:a,supportsNavigation:i,contentType:r,totalItems:e.length}}static analyzeTextCapabilities(t){const e=t.querySelectorAll("input, textarea, select"),i=Array.from(e).map((t=>t.getAttribute("name")||t.getAttribute("id")||"unknown"));return{supportsTextPersistence:t.hasAttribute("data-persist")||t.hasAttribute("data-autosave"),supportsSanitization:!0,fields:i}}static analyzeInteractionCapabilities(t){const e=t.querySelectorAll("button").length>0,i=t.querySelectorAll("form").length>0,a=t.hasAttribute("data-events")||t.hasAttribute("data-track-interactions"),r=[],s=t.getAttribute("data-events");return s&&r.push(...s.split(",").map((t=>t.trim()))),{supportsClicks:e||null!==t.querySelector("[onclick]"),supportsFormSubmission:i,supportsCustomEvents:a,customEventTypes:r.length>0?r:void 0}}static analyzeDisplayCapabilities(t){return{supportsFullscreen:t.hasAttribute("data-fullscreen")||t.classList.contains("fullscreen-capable"),supportsOverlay:t.hasAttribute("data-overlay")||t.classList.contains("overlay-capable"),supportsPopup:t.hasAttribute("data-popup")||t.classList.contains("popup-capable"),supportsInline:!0}}static analyzeABTestingCapabilities(t){if(!("widgetic-abtest"===t.tagName.toLowerCase()||t.hasAttribute("experiment-id")||t.hasAttribute("data-ab-test")))return;const e=[],i=[];return t.querySelector("button, a, [onclick]")&&(e.push("clicks"),i.push("clicks")),t.querySelector("form")&&(e.push("submissions"),i.push("conversions")),t.querySelector("video, audio")&&(e.push("plays"),i.push("plays")),e.push("impressions"),{supportsTracking:!0,trackableEvents:e,conversionGoals:i}}static checkResponsiveSupport(t){return t.hasAttribute("data-responsive")||t.hasAttribute("data-breakpoints")||t.classList.contains("responsive")}static checkAutoscaleSupport(t){return t.hasAttribute("data-autoscale")||t.hasAttribute("data-auto-height")||t.classList.contains("autoscale")}static checkThemeSupport(t){return t.hasAttribute("data-theme")||t.classList.contains("themeable")||null!==t.querySelector("[data-theme]")}static parseCapabilitiesString(t){const e=t.split(",").map((t=>t.trim()));return{type:"custom",version:"1.0.0",mediaCapabilities:e.includes("media")?{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:e.includes("volume"),supportsSeek:e.includes("seek"),supportsGlobalVolume:e.includes("global-volume"),mediaType:"mixed"}:void 0,textCapabilities:e.includes("forms")?{supportsTextPersistence:e.includes("persist"),supportsSanitization:!0,fields:[]}:void 0,interactionCapabilities:e.includes("interactive")?{supportsClicks:!0,supportsFormSubmission:e.includes("forms"),supportsCustomEvents:e.includes("events")}:void 0,supportsResponsive:e.includes("responsive"),supportsAutoscale:e.includes("autoscale"),supportsThemes:e.includes("themes")}}}function D(t){var e,i,a,r;const s=new Set;return s.add("rendering"),s.add("api"),t.mediaCapabilities&&s.add("media"),t.textCapabilities&&s.add("security"),t.interactionCapabilities&&s.add("messaging"),((null===(e=t.displayCapabilities)||void 0===e?void 0:e.supportsFullscreen)||(null===(i=t.displayCapabilities)||void 0===i?void 0:i.supportsOverlay)||(null===(a=t.displayCapabilities)||void 0===a?void 0:a.supportsPopup))&&s.add("display"),t.abTestingCapabilities&&(s.add("abTesting"),s.add("messaging")),(null===(r=t.performanceRequirements)||void 0===r?void 0:r.requiresLazyLoading)&&s.add("performance"),Array.from(s)}var V=Object.freeze({__proto__:null,WidgetMetadataAnalyzer:W,analyzeWidgetRequirementsEnhanced:function(t){const e=new Set;for(const i of t){const t=W.analyzeElement(i);if(t){D(t).forEach((t=>e.add(t)))}}return Array.from(e)},getRequiredChunks:D});export{H as a,B as b,F as c,O as d,j as e,C as g,x as i,s as p,V as w};
|
|
1
|
+
import{m as t}from"./core.js";import{M as e,e as i,f as a,h as r}from"./api.js";function s(e){const i=e.getAttribute("composition-id");if(!i)throw new Error("Missing required composition-id attribute");return{compositionId:i,renderMode:n(e.getAttribute("render-mode")),displayMode:o(e.getAttribute("display-mode")),resize:u(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||t.width,height:parseInt(e.getAttribute("height")||"")||t.height,autoscale:S(e),adaptive:l(e.getAttribute("adaptive")),responsive:c(e.getAttribute("responsive")),device:R(e),fullscreen:d(e),triggers:T(e),overlay:g(e),popup:w(e),media:I(e),content:E(e)}}function n(t){switch(t){case"iframe":case"custom-element":return t;default:return"auto"}}function o(t){switch(t){case"overlay":case"popup":case"fullscreen":case"modal":return t;default:return"inline"}}function u(t){switch(t){case"fill-width":case"fill-height":case"fixed":case"fixed-height":case"fixed-width":case"allow-scale-down":case"fill":return t;default:return"fixed"}}function l(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function c(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function d(t){if("enabled"===t.getAttribute("fullscreen")||"true"===t.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:p(t.getAttribute("fullscreen-trigger")),showControls:"false"!==t.getAttribute("fullscreen-controls"),exitOnEscape:"false"!==t.getAttribute("fullscreen-exit-on-escape"),allowAutoEnter:"true"===t.getAttribute("fullscreen-auto-enter")}}function p(t){switch(t){case"click":case"double-click":case"hover":case"auto":case"manual":return t;default:return"click"}}function g(t){if("enabled"===t.getAttribute("overlay")||"true"===t.getAttribute("overlay-enabled"))return{enabled:!0,position:v(t.getAttribute("overlay-position")),backdrop:m(t),background:f(t,m(t)),closeOnBackdropClick:"false"!==t.getAttribute("overlay-close-on-backdrop"),closeOnEscape:"false"!==t.getAttribute("overlay-close-on-escape"),showCloseButton:"false"!==t.getAttribute("overlay-close-button"),trigger:h(t.getAttribute("overlay-trigger")),width:t.getAttribute("overlay-width")||void 0,height:t.getAttribute("overlay-height")||void 0,maxWidth:t.getAttribute("overlay-max-width")||void 0,maxHeight:t.getAttribute("overlay-max-height")||void 0,zIndex:parseInt(t.getAttribute("overlay-z-index")||"")||void 0,animation:y(t.getAttribute("overlay-animation")),overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:A(t.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==t.getAttribute("keep-dimensions"),embedTarget:t.getAttribute("embed-target")||void 0}}function b(t){return"true"===t.getAttribute("overlay-backdrop")}function m(t){return"false"!==t.getAttribute("overlay-backdrop")}function f(t,e){if(!e)return;const i=t.getAttribute("overlay-background-color")||void 0,a=t.getAttribute("overlay-background-opacity"),r=null===a?Number.NaN:Number(a);return{enabled:!0,color:i,opacity:Number.isFinite(r)?r:void 0}}function h(t){switch(t){case"click":case"hover":case"manual":case"auto":return t;default:return"click"}}function y(t){switch(t){case"fade":case"slide-up":case"slide-down":case"slide-left":case"slide-right":case"zoom":case"bounce":case"none":return t;case"scale":return"zoom";case"slide":return"slide-up";default:return"fade"}}function v(t){switch(t){case"top":case"bottom":case"left":case"right":case"top-left":case"top-right":case"bottom-left":case"bottom-right":return t;case"top-center":return"top";case"center-left":return"left";case"center-right":return"right";case"bottom-center":return"bottom";default:return"center"}}function A(t){switch(t){case"fillWidth":return"fill-width";case"fillHeight":return"fill-height";case"fixedSize":return"fixed";case"fixedHeight":return"fixed-height";case"fixedWidth":return"fixed-width";case"allowScaleDown":return"allow-scale-down";case"fill":return"fill";default:return}}function w(t){if("enabled"===t.getAttribute("popup")||"true"===t.getAttribute("popup-enabled"))return{enabled:!0,trigger:k(t.getAttribute("popup-trigger")),width:parseInt(t.getAttribute("popup-width")||"")||void 0,height:parseInt(t.getAttribute("popup-height")||"")||void 0,centerScreen:"false"!==t.getAttribute("popup-center"),allowResize:"true"===t.getAttribute("popup-resizable"),showToolbar:"true"===t.getAttribute("popup-toolbar"),target:t.getAttribute("popup-target")||void 0}}function k(t){switch(t){case"click":case"manual":return t;default:return"click"}}function S(t){const e=t.getAttribute("autoscale");return!!e&&(("true"===e||""===e||"false"!==e)&&(z(t)||!0))}function z(t){return t.getAttribute("autoscale-min-height")||t.getAttribute("autoscale-max-height")||t.getAttribute("autoscale-debounce")||t.getAttribute("autoscale-threshold")||t.getAttribute("autoscale-animate")||t.getAttribute("autoscale-animation-duration")?{enabled:!0,minHeight:parseInt(t.getAttribute("autoscale-min-height")||"")||void 0,maxHeight:parseInt(t.getAttribute("autoscale-max-height")||"")||void 0,debounceDelay:parseInt(t.getAttribute("autoscale-debounce")||"")||void 0,threshold:parseInt(t.getAttribute("autoscale-threshold")||"")||void 0,animate:"false"!==t.getAttribute("autoscale-animate"),animationDuration:parseInt(t.getAttribute("autoscale-animation-duration")||"")||void 0}:null}function C(t){return`${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function x(t){return"widgetic"===t.tagName.toLowerCase()&&t.hasAttribute("composition-id")}function I(t){const e={},i=t.getAttribute("media-auto-pause")||t.getAttribute("data-media-auto-pause");null!==i&&(e.autoPause="true"===i||""===i);const a=t.getAttribute("media-type")||t.getAttribute("data-media-type");a&&["audio","video","both"].includes(a)&&(e.mediaType=a);const r=t.getAttribute("media-priority")||t.getAttribute("data-media-priority");if(r){const t=parseInt(r,10);!isNaN(t)&&t>=0&&t<=10&&(e.priority=t)}const s=t.getAttribute("media-persist-state")||t.getAttribute("data-media-persist-state");null!==s&&(e.persistState="true"===s||""===s);const n=t.getAttribute("media-allow-simultaneous")||t.getAttribute("data-media-allow-simultaneous");if(n){const t=n.split(",").map((t=>t.trim())).filter((t=>["audio","video"].includes(t)));t.length>0&&(e.allowSimultaneous=t)}const o=t.getAttribute("media-auto-resume")||t.getAttribute("data-media-auto-resume");null!==o&&(e.autoResume="true"===o||""===o);const u=t.getAttribute("media-auto-resume-timeout")||t.getAttribute("data-media-auto-resume-timeout");if(u){const t=parseInt(u,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const l=t.getAttribute("media-global-volume")||t.getAttribute("data-media-global-volume");return null!==l&&(e.globalVolume="true"===l||""===l),e}function E(t){const e={},i=t.getAttribute("content-type")||t.getAttribute("data-content-type");i&&["gallery","carousel","slider","stepper","tabs","list","custom"].includes(i)&&(e.contentType=i);const a=t.getAttribute("content-persist-state")||t.getAttribute("data-content-persist-state");null!==a&&(e.persistState="true"===a||""===a);const r=t.getAttribute("content-auto-resume")||t.getAttribute("data-content-auto-resume");null!==r&&(e.autoResume="true"===r||""===r);const s=t.getAttribute("content-auto-resume-timeout")||t.getAttribute("data-content-auto-resume-timeout");if(s){const t=parseInt(s,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const n=t.getAttribute("content-track-metadata")||t.getAttribute("data-content-track-metadata");return null!==n&&(e.trackMetadata="true"===n||""===n),Object.keys(e).length>0?e:void 0}function T(t){const e=t.getAttribute("embed-target");if("overlay"!==e&&"mixed"!==e)return;const i=function(t){switch(t){case"page-load":return"pageLoad";case"exit-intent":return"exitIntent";case"delay":return"delay";case"scroll":return"scroll";default:return}}(t.getAttribute("event-trigger")),a=parseInt(t.getAttribute("max-views")||""),r=parseInt(t.getAttribute("time-period")||""),s=Number.isFinite(a)&&a>0||Number.isFinite(r)&&r>0;return Object.assign(Object.assign(Object.assign({mode:e,eventTrigger:i},"overlay"===e&&"delay"===i?{delay:{enabled:!0,delayMs:N(t)}}:{}),"overlay"===e&&"scroll"===i?{scroll:{enabled:!0,threshold:.1,distance:L(t),direction:"down"}}:{}),{overlay:{position:t.getAttribute("overlay-position")||void 0,keepDimensions:"false"!==t.getAttribute("keep-dimensions"),zIndex:q(t),fullWidth:"true"===t.getAttribute("overlay-full-width")||void 0,overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:A(t.getAttribute("overlay-resize-mode")),backdrop:b(t),background:f(t,b(t)),closeButton:!0},recurrence:s?{enabled:!0,maxViews:Number.isFinite(a)&&a>0?a:Number.MAX_SAFE_INTEGER,timePeriodHours:Number.isFinite(r)&&r>0?r:24}:void 0})}function q(t){const i=parseInt(t.getAttribute("overlay-z-index")||"");if(Number.isFinite(i)&&!(i<=0))return Math.min(i,e)}function N(t){const e=parseInt(t.getAttribute("trigger-delay")||"");return!Number.isFinite(e)||e<0?i:Math.min(e,a)}function L(t){const e=parseInt(t.getAttribute("trigger-scroll-distance")||"");return Number.isFinite(e)&&e>0?e:r}function R(t){const e=t.getAttribute("device-mobile-enabled")||t.getAttribute("data-device-mobile-enabled"),i=t.getAttribute("device-desktop-enabled")||t.getAttribute("data-device-desktop-enabled");if(e||i)return{mobileEnabled:"false"!==e,desktopEnabled:"false"!==i}}var F=Object.freeze({__proto__:null,generateInstanceId:C,isValidWidgetElement:x,parseTriggerConfig:T,parseWidgetConfig:s});function O(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:_(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:M(),popupBlocking:P()}}function _(){if("undefined"==typeof performance||!performance.getEntriesByType)return!1;try{const t=performance.getEntriesByType("navigation");if(t.length>0){const e=t[0];return"h3"===e.nextHopProtocol||"h3-29"===e.nextHopProtocol}return!1}catch(t){return!1}}function M(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function P(){if("undefined"==typeof window||!window.open)return!1;try{const t=window.open("","widgetic-popup-test","width=1,height=1");return!t||(t.close(),!1)}catch(t){return!0}}function H(t,e){switch(t){case"custom-element":case"auto":default:return e.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function B(){if("undefined"==typeof localStorage)return!1;try{const t="widgetic-test";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch(t){return!1}}var j=Object.freeze({__proto__:null,checkSdkInitialization:function(){if("undefined"==typeof window)return!1;const t="widgetic-sdk-initialized";return B()?!!localStorage.getItem(t)||(localStorage.setItem(t,Date.now().toString()),!1):!!window.__widgeticInitialized},clearSdkInitialization:function(){B()&&localStorage.removeItem("widgetic-sdk-initialized"),delete window.__widgeticInitialized},detectBrowserCapabilities:O,determineBestRenderMode:H,hasIntersectionObserver:function(){return"undefined"!=typeof IntersectionObserver},isLocalStorageAvailable:B});class W{static analyzeElement(t){try{const e=this.getExplicitMetadata(t);return e||this.analyzeHeuristically(t)}catch(t){return null}}static getExplicitMetadata(t){const e=t.getAttribute("data-widget-meta");if(e)try{return JSON.parse(e)}catch(t){}const i=t.getAttribute("data-capabilities");if(i)return this.parseCapabilitiesString(i);const a=t.querySelector('script[type="application/json"]');if(a&&a.textContent)try{const t=JSON.parse(a.textContent);return t.capabilities||t.metadata}catch(t){}return null}static analyzeHeuristically(t){const e={type:"custom",version:"1.0.0"},i=t.getAttribute("data-widget-type")||t.getAttribute("data-type")||this.inferTypeFromStructure(t);switch(i&&(e.type=i),e.type){case"media":e.mediaCapabilities=this.analyzeMediaCapabilities(t);break;case"gallery":e.contentCapabilities=this.analyzeContentCapabilities(t);break;case"form":e.textCapabilities=this.analyzeTextCapabilities(t);break;case"interactive":e.interactionCapabilities=this.analyzeInteractionCapabilities(t)}return e.supportsResponsive=this.checkResponsiveSupport(t),e.supportsAutoscale=this.checkAutoscaleSupport(t),e.supportsThemes=this.checkThemeSupport(t),e.displayCapabilities=this.analyzeDisplayCapabilities(t),e.abTestingCapabilities=this.analyzeABTestingCapabilities(t),e}static inferTypeFromStructure(t){var e;return t.querySelector("video, audio")||t.classList.contains("media-widget")||(null===(e=t.getAttribute("data-widget-id"))||void 0===e?void 0:e.includes("video"))?"media":t.querySelector("form, input, textarea")||t.classList.contains("form-widget")?"form":t.querySelector(".gallery, .carousel")||t.classList.contains("gallery-widget")||t.querySelectorAll("img").length>1?"gallery":t.querySelector("button, .interactive")||t.classList.contains("quiz-widget")||t.classList.contains("poll-widget")?"interactive":"custom"}static analyzeMediaCapabilities(t){const e=t.querySelectorAll("video"),i=t.querySelectorAll("audio"),a=null!==t.querySelector("[controls]"),r=null!==t.querySelector("[data-volume], .volume-control");let s="audio";return e.length>0&&i.length>0?s="mixed":e.length>0&&(s="video"),{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:r||a,supportsSeek:a,supportsGlobalVolume:t.hasAttribute("data-global-volume"),mediaType:s}}static analyzeContentCapabilities(t){const e=t.querySelectorAll(".item, .slide, img, .content-item"),i=null!==t.querySelector(".nav, .navigation, button"),a=t.hasAttribute("data-position")||t.hasAttribute("data-track-position");let r="gallery";return t.classList.contains("carousel")&&(r="carousel"),t.classList.contains("list")&&(r="list"),t.classList.contains("grid")&&(r="grid"),{supportsPositionTracking:a,supportsNavigation:i,contentType:r,totalItems:e.length}}static analyzeTextCapabilities(t){const e=t.querySelectorAll("input, textarea, select"),i=Array.from(e).map((t=>t.getAttribute("name")||t.getAttribute("id")||"unknown"));return{supportsTextPersistence:t.hasAttribute("data-persist")||t.hasAttribute("data-autosave"),supportsSanitization:!0,fields:i}}static analyzeInteractionCapabilities(t){const e=t.querySelectorAll("button").length>0,i=t.querySelectorAll("form").length>0,a=t.hasAttribute("data-events")||t.hasAttribute("data-track-interactions"),r=[],s=t.getAttribute("data-events");return s&&r.push(...s.split(",").map((t=>t.trim()))),{supportsClicks:e||null!==t.querySelector("[onclick]"),supportsFormSubmission:i,supportsCustomEvents:a,customEventTypes:r.length>0?r:void 0}}static analyzeDisplayCapabilities(t){return{supportsFullscreen:t.hasAttribute("data-fullscreen")||t.classList.contains("fullscreen-capable"),supportsOverlay:t.hasAttribute("data-overlay")||t.classList.contains("overlay-capable"),supportsPopup:t.hasAttribute("data-popup")||t.classList.contains("popup-capable"),supportsInline:!0}}static analyzeABTestingCapabilities(t){if(!("widgetic-abtest"===t.tagName.toLowerCase()||t.hasAttribute("experiment-id")||t.hasAttribute("data-ab-test")))return;const e=[],i=[];return t.querySelector("button, a, [onclick]")&&(e.push("clicks"),i.push("clicks")),t.querySelector("form")&&(e.push("submissions"),i.push("conversions")),t.querySelector("video, audio")&&(e.push("plays"),i.push("plays")),e.push("impressions"),{supportsTracking:!0,trackableEvents:e,conversionGoals:i}}static checkResponsiveSupport(t){return t.hasAttribute("data-responsive")||t.hasAttribute("data-breakpoints")||t.classList.contains("responsive")}static checkAutoscaleSupport(t){return t.hasAttribute("data-autoscale")||t.hasAttribute("data-auto-height")||t.classList.contains("autoscale")}static checkThemeSupport(t){return t.hasAttribute("data-theme")||t.classList.contains("themeable")||null!==t.querySelector("[data-theme]")}static parseCapabilitiesString(t){const e=t.split(",").map((t=>t.trim()));return{type:"custom",version:"1.0.0",mediaCapabilities:e.includes("media")?{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:e.includes("volume"),supportsSeek:e.includes("seek"),supportsGlobalVolume:e.includes("global-volume"),mediaType:"mixed"}:void 0,textCapabilities:e.includes("forms")?{supportsTextPersistence:e.includes("persist"),supportsSanitization:!0,fields:[]}:void 0,interactionCapabilities:e.includes("interactive")?{supportsClicks:!0,supportsFormSubmission:e.includes("forms"),supportsCustomEvents:e.includes("events")}:void 0,supportsResponsive:e.includes("responsive"),supportsAutoscale:e.includes("autoscale"),supportsThemes:e.includes("themes")}}}function D(t){var e,i,a,r;const s=new Set;return s.add("rendering"),s.add("api"),t.mediaCapabilities&&s.add("media"),t.textCapabilities&&s.add("security"),t.interactionCapabilities&&s.add("messaging"),((null===(e=t.displayCapabilities)||void 0===e?void 0:e.supportsFullscreen)||(null===(i=t.displayCapabilities)||void 0===i?void 0:i.supportsOverlay)||(null===(a=t.displayCapabilities)||void 0===a?void 0:a.supportsPopup))&&s.add("display"),t.abTestingCapabilities&&(s.add("abTesting"),s.add("messaging")),(null===(r=t.performanceRequirements)||void 0===r?void 0:r.requiresLazyLoading)&&s.add("performance"),Array.from(s)}var V=Object.freeze({__proto__:null,WidgetMetadataAnalyzer:W,analyzeWidgetRequirementsEnhanced:function(t){const e=new Set;for(const i of t){const t=W.analyzeElement(i);if(t){D(t).forEach((t=>e.add(t)))}}return Array.from(e)},getRequiredChunks:D});export{H as a,B as b,F as c,O as d,j as e,C as g,x as i,s as p,V as w};
|