@widgetic/embed-sdk 2.0.7 โ†’ 2.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{P as t}from"./core.js";class i{constructor(e={}){this.metrics=[],this.webVitals={},this.widgetMetrics=new Map,this.isTracking=!1,this.config=Object.assign({enableTracking:t.ENABLE_PERFORMANCE_TRACKING,enableWebVitals:!0,enableWidgetMetrics:!0,enableResourceTracking:!0,enableBudgetMonitoring:!0,sampleRate:t.PERFORMANCE_SAMPLE_RATE,maxMetricsBuffer:t.MAX_METRICS_BUFFER,axiomApiEndpoint:t.AXIOM_API_ENDPOINT,statsigApiEndpoint:t.STATSIG_API_ENDPOINT,budgets:[{metric:"lcp",threshold:t.LCP_THRESHOLD,warningThreshold:t.LCP_WARNING_THRESHOLD,enabled:!0},{metric:"fid",threshold:t.FID_THRESHOLD,warningThreshold:t.FID_WARNING_THRESHOLD,enabled:!0},{metric:"cls",threshold:t.CLS_THRESHOLD,warningThreshold:t.CLS_WARNING_THRESHOLD,enabled:!0},{metric:"widget-load",threshold:t.WIDGET_LOAD_THRESHOLD,warningThreshold:t.WIDGET_LOAD_WARNING_THRESHOLD,enabled:!0},{metric:"bundle-size",threshold:t.BUNDLE_SIZE_THRESHOLD,warningThreshold:t.BUNDLE_SIZE_WARNING_THRESHOLD,enabled:!0}]},e),this.navigationStart=performance.now(),this.init()}init(){"undefined"!=typeof window&&this.config.enableTracking&&this.shouldSample()&&(this.isTracking=!0,this.config.enableWebVitals&&this.setupWebVitalsTracking(),this.config.enableResourceTracking&&this.setupResourceTracking(),setInterval((()=>this.reportMetrics()),3e4),window.addEventListener("beforeunload",(()=>this.reportMetrics())),window.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.reportMetrics()})))}shouldSample(){return Math.random()<this.config.sampleRate}setupWebVitalsTracking(){this.observePerformanceEntries(["largest-contentful-paint"],(e=>{const t=e[e.length-1],i=t.renderTime||t.loadTime;null!=i&&(this.webVitals.lcp=i,this.recordMetric("lcp",i),this.checkBudget("lcp",i))})),this.observePerformanceEntries(["first-input"],(e=>{const t=e[0],i=t.processingStart-t.startTime;void 0!==i&&(this.webVitals.fid=i,this.recordMetric("fid",this.webVitals.fid),this.checkBudget("fid",this.webVitals.fid))}));let e=0;this.observePerformanceEntries(["layout-shift"],(t=>{for(const i of t)i.hadRecentInput||(e+=i.value);this.webVitals.cls=e,this.recordMetric("cls",this.webVitals.cls),this.checkBudget("cls",this.webVitals.cls)})),this.observePerformanceEntries(["paint"],(e=>{const t=e.find((e=>"first-contentful-paint"===e.name));t&&(this.webVitals.fcp=t.startTime,this.recordMetric("fcp",this.webVitals.fcp))})),this.observePerformanceEntries(["navigation"],(e=>{const t=e[0],i=t.responseStart-t.requestStart;void 0!==i&&(this.webVitals.ttfb=i,this.recordMetric("ttfb",this.webVitals.ttfb))}))}setupResourceTracking(){this.observePerformanceEntries(["resource"],(e=>{for(const t of e)(t.name.includes("widgetic")||t.name.includes("widget"))&&this.recordMetric("resource-load",t.duration,{url:t.name,type:t.initiatorType,size:t.transferSize,cached:0===t.transferSize})}))}observePerformanceEntries(e,t){try{new PerformanceObserver((e=>{t(e.getEntries())})).observe({entryTypes:e})}catch(e){}}startWidgetLoad(e,t={}){if(!this.isTracking)return;const i=Object.assign({compositionId:e,loadStartTime:performance.now(),loadEndTime:0,renderTime:0,resourceLoadTime:0,errorCount:0,retryCount:0,bundleSize:0,isLazyLoaded:!1},t);this.widgetMetrics.set(e,i)}endWidgetLoad(e,t=!0){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);if(!i)return;i.loadEndTime=performance.now();const r=i.loadEndTime-i.loadStartTime;this.recordMetric("widget-load",r,{compositionId:e,success:t,isLazyLoaded:i.isLazyLoaded,bundleSize:i.bundleSize}),this.checkBudget("widget-load",r),i.bundleSize>0&&this.checkBudget("bundle-size",i.bundleSize)}recordWidgetRender(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&(i.renderTime=t),this.recordMetric("widget-render",t,{compositionId:e})}recordWidgetError(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&i.errorCount++,this.recordMetric("widget-error",1,{compositionId:e,error:t})}recordWidgetRetry(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&i.retryCount++,this.recordMetric("widget-retry",1,{compositionId:e,reason:t})}recordLazyLoad(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&(i.isLazyLoaded=!0,i.viewportEntry=t),this.recordMetric("lazy-load",t,{compositionId:e})}recordMetric(e,t,i){if(!this.isTracking)return;const r={name:e,value:t,timestamp:performance.now(),metadata:i};this.metrics.push(r),this.metrics.length>this.config.maxMetricsBuffer&&(this.metrics=this.metrics.slice(-this.config.maxMetricsBuffer)),this.config.enableBudgetMonitoring&&this.checkBudget(e,t)}checkBudget(e,t){const i=this.config.budgets.find((t=>t.metric===e&&t.enabled));i&&(t>i.threshold?this.triggerBudgetAlert(e,t,i.threshold,"exceeded"):i.warningThreshold&&t>i.warningThreshold&&this.triggerBudgetAlert(e,t,i.warningThreshold,"warning"))}triggerBudgetAlert(e,t,i,r){const o={type:"performance-budget-alert",metric:e,value:t,threshold:i,level:r,timestamp:Date.now(),url:window.location.href};window.dispatchEvent(new CustomEvent("widgetic:performance-alert",{detail:o})),this.recordMetric("budget-alert",t,o)}getWebVitals(){return Object.assign({},this.webVitals)}getWidgetMetrics(e){if(e){const t=this.widgetMetrics.get(e);return t?[t]:[]}return Array.from(this.widgetMetrics.values())}getMetrics(){return[...this.metrics]}getPerformanceSummary(){const e=performance.now(),t=Array.from(this.widgetMetrics.values());return{sessionDuration:e-this.navigationStart,webVitals:this.webVitals,widgets:{total:t.length,loaded:t.filter((e=>e.loadEndTime>0)).length,errors:t.reduce(((e,t)=>e+t.errorCount),0),retries:t.reduce(((e,t)=>e+t.retryCount),0),lazyLoaded:t.filter((e=>e.isLazyLoaded)).length,averageLoadTime:this.getAverageLoadTime(),totalBundleSize:t.reduce(((e,t)=>e+t.bundleSize),0)},metrics:{total:this.metrics.length,budgetViolations:this.metrics.filter((e=>"budget-alert"===e.name)).length},timestamp:Date.now()}}getAverageLoadTime(){const e=this.metrics.filter((e=>"widget-load"===e.name)).map((e=>e.value));return e.length>0?e.reduce(((e,t)=>e+t),0)/e.length:0}reportMetrics(){return e(this,void 0,void 0,(function*(){if(!this.isTracking||0===this.metrics.length)return;const e=this.getPerformanceSummary();try{this.config.reportingEndpoint&&(yield this.reportToEndpoint(e)),this.config.axiomApiKey&&this.config.axiomDataset&&(yield this.reportToAxiom(e)),this.config.statsigKey&&(yield this.reportToStatsig(e))}catch(e){}}))}reportToEndpoint(t){return e(this,void 0,void 0,(function*(){yield fetch(this.config.reportingEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}))}reportToAxiom(t){return e(this,void 0,void 0,(function*(){const e=this.config.axiomApiEndpoint||"https://api.axiom.co/v1";yield fetch(`${e}/datasets/${this.config.axiomDataset}/ingest`,{method:"POST",headers:{Authorization:`Bearer ${this.config.axiomApiKey}`,"Content-Type":"application/x-ndjson"},body:JSON.stringify(t)+"\n"})}))}reportToStatsig(t){return e(this,void 0,void 0,(function*(){const e=this.config.statsigApiEndpoint||"https://events.statsigapi.net/v1/custom";yield fetch(e,{method:"POST",headers:{"STATSIG-API-KEY":this.config.statsigKey,"Content-Type":"application/json"},body:JSON.stringify({events:[{eventName:"widget_performance",value:t,timestamp:Date.now()}]})})}))}clearMetrics(){this.metrics=[],this.widgetMetrics.clear()}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e)}stop(){this.isTracking=!1,this.observer&&this.observer.disconnect(),this.reportMetrics()}}let r=null;function o(e){return r||(r=new i(e)),r}function s(e={}){return r=new i(e),r}var n=Object.freeze({__proto__:null,PerformanceMonitor:i,getPerformanceMonitor:o,initializePerformanceMonitoring:s});class a{constructor(e={}){this.items=new Map,this.observer=null,this.preloadObserver=null,this.loadingQueue=[],this.activeLoads=0,this.performanceMonitor=o(),this.retryTimeouts=new Map,this.config=Object.assign({enabled:!0,rootMargin:"50px",threshold:[0,.25,.5,.75,1],enablePreloading:!0,preloadDistance:"200px",retryAttempts:3,retryDelay:1e3,enablePrefetch:!0,prefetchDelay:2e3,enableProgressiveLoading:!0,maxConcurrentLoads:3,enableResourceHints:!0},e),this.init()}init(){"undefined"!=typeof window&&this.config.enabled&&("IntersectionObserver"in window?(this.setupIntersectionObserver(),this.config.enablePreloading&&this.setupPreloadObserver()):this.fallbackToImmediateLoading())}setupIntersectionObserver(){this.observer=new IntersectionObserver((e=>this.handleIntersection(e)),{rootMargin:this.config.rootMargin,threshold:this.config.threshold})}setupPreloadObserver(){this.preloadObserver=new IntersectionObserver((e=>this.handlePreloadIntersection(e)),{rootMargin:this.config.preloadDistance,threshold:0})}handleIntersection(e){for(const t of e){const e=t.target.getAttribute("data-lazy-id"),i=t.target.getAttribute("data-composition-id")||t.target.getAttribute("composition-id"),r=(e?this.items.get(e):null)||(i?this.items.get(i):null);r&&(!t.isIntersecting||r.isLoaded||r.isLoading||(r.viewportEntryTime=performance.now(),this.performanceMonitor.recordLazyLoad(r.compositionId,r.viewportEntryTime),this.queueLoad(r)))}}handlePreloadIntersection(e){for(const t of e){const e=t.target.getAttribute("data-lazy-id"),i=t.target.getAttribute("data-composition-id")||t.target.getAttribute("composition-id"),r=(e?this.items.get(e):null)||(i?this.items.get(i):null);!r||r.isPreloaded||r.isLoaded||t.isIntersecting&&this.preloadResources(r)}}register(e,t,i,r={}){const o=e.getAttribute("data-lazy-id")||`lazy_${t}_${Math.random().toString(36).substr(2,9)}`;e.setAttribute("data-lazy-id",o),e.setAttribute("data-composition-id",t);const s={element:e,compositionId:t,config:r.config||{},loadFunction:i,priority:r.priority||5,retryCount:0,isLoading:!1,isLoaded:!1,isPreloaded:!1,resourceUrls:r.resourceUrls};this.items.set(o,s),e.classList.add("widgetic-lazy-loading"),e.setAttribute("data-lazy","true"),this.observer&&this.observer.observe(e),this.preloadObserver&&this.config.enablePreloading&&this.preloadObserver.observe(e),this.config.enableResourceHints&&s.resourceUrls&&this.addResourceHints(s.resourceUrls),this.observer||setTimeout((()=>this.loadItem(s)),100)}unregister(e){let t=e,i=this.items.get(e);if(!i)for(const[r,o]of this.items.entries())if(o.compositionId===e){t=r,i=o;break}if(!i)return;this.observer&&this.observer.unobserve(i.element),this.preloadObserver&&this.preloadObserver.unobserve(i.element);const r=this.retryTimeouts.get(t)||this.retryTimeouts.get(i.compositionId);r&&(clearTimeout(r),this.retryTimeouts.delete(t),this.retryTimeouts.delete(i.compositionId)),this.items.delete(t)}queueLoad(e){if(this.config.enableProgressiveLoading){const t=this.loadingQueue.findIndex((t=>t.priority<e.priority));-1===t?this.loadingQueue.push(e):this.loadingQueue.splice(t,0,e),this.processLoadingQueue()}else this.loadItem(e)}processLoadingQueue(){return e(this,void 0,void 0,(function*(){for(;this.loadingQueue.length>0&&this.activeLoads<this.config.maxConcurrentLoads;){const e=this.loadingQueue.shift();!e||e.isLoaded||e.isLoading||this.loadItem(e)}}))}loadItem(t){return e(this,void 0,void 0,(function*(){if(!t.isLoading&&!t.isLoaded){t.isLoading=!0,this.activeLoads++,this.performanceMonitor.startWidgetLoad(t.compositionId,{isLazyLoaded:!0,bundleSize:this.estimateBundleSize(t)});try{t.element.classList.add("widgetic-loading"),t.element.classList.remove("widgetic-lazy-loading"),yield t.loadFunction(),t.isLoaded=!0,t.element.classList.remove("widgetic-loading"),t.element.classList.add("widgetic-loaded"),t.element.removeAttribute("data-lazy"),this.observer&&this.observer.unobserve(t.element),this.preloadObserver&&this.preloadObserver.unobserve(t.element),this.performanceMonitor.endWidgetLoad(t.compositionId,!0)}catch(e){if(t.element.classList.add("widgetic-load-error"),this.performanceMonitor.recordWidgetError(t.compositionId,e instanceof Error?e.message:"Load failed"),this.performanceMonitor.endWidgetLoad(t.compositionId,!1),t.retryCount<this.config.retryAttempts){t.retryCount++,this.performanceMonitor.recordWidgetRetry(t.compositionId,`Attempt ${t.retryCount}`);const e=setTimeout((()=>{t.isLoading=!1,this.retryTimeouts.delete(t.compositionId),this.loadItem(t)}),this.config.retryDelay*t.retryCount);this.retryTimeouts.set(t.compositionId,e)}}finally{t.isLoading=!1,this.activeLoads--,this.config.enableProgressiveLoading&&setTimeout((()=>this.processLoadingQueue()),10)}}}))}preloadResources(t){return e(this,void 0,void 0,(function*(){if(t.resourceUrls&&!t.isPreloaded){t.isPreloaded=!0;try{const e=t.resourceUrls.map((e=>this.preloadResource(e)));yield Promise.allSettled(e)}catch(e){}}}))}preloadResource(t){return e(this,void 0,void 0,(function*(){return new Promise(((e,i)=>{const r=document.createElement("link");r.rel="preload",r.href=t,t.endsWith(".js")?r.as="script":t.endsWith(".css")?r.as="style":t.match(/\.(png|jpg|jpeg|gif|webp|svg)$/)?r.as="image":(r.as="fetch",r.setAttribute("crossorigin","anonymous")),r.onload=()=>e(),r.onerror=()=>i(new Error(`Failed to preload ${t}`)),document.head.appendChild(r)}))}))}addResourceHints(e){for(const t of e)try{const e=new URL(t);if(e.origin!==window.location.origin){const t=document.createElement("link");t.rel="dns-prefetch",t.href=e.origin,document.head.appendChild(t)}}catch(e){}}estimateBundleSize(e){return 5e4+10*JSON.stringify(e.config).length}fallbackToImmediateLoading(){for(const e of this.items.values())e.isLoaded||e.isLoading||setTimeout((()=>this.loadItem(e)),1e3*Math.random())}forceLoad(t){const i=this.items.get(t);return i?i.isLoaded?Promise.resolve():new Promise(((t,r)=>{const o=i.loadFunction;i.loadFunction=()=>e(this,void 0,void 0,(function*(){try{yield o(),t()}catch(e){r(e)}})),this.loadItem(i)})):Promise.reject(new Error(`Widget ${t} not found`))}loadVisible(){const e=[];for(const t of this.items.values())t.isLoaded||t.isLoading||!this.isElementVisible(t.element)||e.push(t);return Promise.all(e.map((e=>this.forceLoad(e.compositionId))))}isElementVisible(e){const t=e.getBoundingClientRect(),i=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth;return t.top<i&&t.bottom>0&&t.left<r&&t.right>0}getMetrics(){const e=Array.from(this.items.values()),t=e.filter((e=>e.isLoaded)),i=e.filter((e=>e.retryCount>=this.config.retryAttempts)),r=this.performanceMonitor.getMetrics().filter((e=>"lazy-load"===e.name)).map((e=>e.value)),o=r.length>0?r.reduce(((e,t)=>e+t),0)/r.length:0,s=e.filter((e=>this.isElementVisible(e.element))),n=s.filter((e=>e.isLoaded)),a=s.length>0?n.length/s.length:0,c=e.filter((e=>e.isPreloaded)),d=e.length>0?c.length/e.length:0;return{totalItems:e.length,loadedItems:t.length,failedItems:i.length,averageLoadTime:o,viewportUtilization:a,preloadSuccess:d}}updateConfig(e){if(this.config=Object.assign(Object.assign({},this.config),e),this.observer&&(void 0!==e.threshold||void 0!==e.rootMargin)){this.observer.disconnect(),this.setupIntersectionObserver();for(const e of this.items.values())!e.isLoaded&&this.observer&&this.observer.observe(e.element)}}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.preloadObserver&&(this.preloadObserver.disconnect(),this.preloadObserver=null);for(const e of this.retryTimeouts.values())clearTimeout(e);this.retryTimeouts.clear(),this.items.clear(),this.loadingQueue=[]}}let c=null;function d(e){return c||(c=new a(e)),c}function l(e={}){return c=new a(e),c}class h{constructor(e={}){this.resources=new Map,this.loadQueue=[],this.activeRequests=0,this.performanceMonitor=o(),this.config=Object.assign({enablePreloading:!0,enablePrefetching:!0,enableServiceWorker:!1,enableBundleSplitting:!0,enableCriticalResourceOptimization:!0,enableNetworkAwareLoading:!0,preloadThreshold:200,prefetchDelay:2e3,maxConcurrentRequests:6,cacheDuration:864e5,priorityLevels:[{pattern:"**/*.css",priority:"critical",preload:!0,prefetch:!1},{pattern:"**/core.js",priority:"critical",preload:!0,prefetch:!1},{pattern:"**/widget-*.js",priority:"high",preload:!0,prefetch:!0},{pattern:"**/fonts/*",priority:"high",preload:!0,prefetch:!1},{pattern:"**/images/*",priority:"medium",preload:!1,prefetch:!0},{pattern:"**/analytics.js",priority:"low",preload:!1,prefetch:!0}]},e),this.init()}init(){return e(this,void 0,void 0,(function*(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.detectNetworkInfo(),this.config.enableServiceWorker&&(yield this.initServiceWorker()),this.setupResourceObserver(),this.addGlobalResourceHints())}))}detectNetworkInfo(){if("connection"in navigator){const e=navigator.connection;this.networkInfo={effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData},e.addEventListener("change",(()=>{this.networkInfo={effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData}}))}}initServiceWorker(){return e(this,void 0,void 0,(function*(){if("serviceWorker"in navigator)try{const e=yield navigator.serviceWorker.register("/sw-cache.js");this.serviceWorker=e.active||e.installing||e.waiting||void 0}catch(e){}}))}setupResourceObserver(){if("PerformanceObserver"in window){new PerformanceObserver((e=>{for(const t of e.getEntries())"resource"===t.entryType&&this.trackResourceLoad(t)})).observe({entryTypes:["resource"]})}}trackResourceLoad(e){const t=this.resources.get(e.name);t&&(t.isLoaded=!0,t.loadTime=e.duration,t.cached=0===e.transferSize,this.performanceMonitor.recordMetric("resource-load",e.duration,{url:e.name,type:t.type,size:e.transferSize,cached:t.cached,priority:t.priority}))}addGlobalResourceHints(){const e=["cdn.widgetic.com","analytics.widgetic.com","api.widgetic.com"];for(const t of e)this.addResourceHint("dns-prefetch",`https://${t}`);this.addResourceHint("preconnect","https://cdn.widgetic.com")}addResourceHint(e,t){if(document.querySelector(`link[rel="${e}"][href="${t}"]`))return;const i=document.createElement("link");i.rel=e,i.href=t,"preconnect"===e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}registerResource(e,t,i={}){const r={url:e,type:t,priority:i.priority||this.determineResourcePriority(e,t),isLoaded:!1,isPreloaded:!1,isPrefetched:!1,cached:!1,compositionId:i.compositionId};return this.resources.set(e,r),this.shouldPreload(r,i.preload)?this.preloadResource(r):this.shouldPrefetch(r,i.prefetch)&&setTimeout((()=>this.prefetchResource(r)),this.config.prefetchDelay),r}determineResourcePriority(e,t){for(const t of this.config.priorityLevels)if(this.matchesPattern(e,t.pattern))return t.priority;switch(t){case"style":return"critical";case"script":case"font":return"high";case"image":return"medium";default:return"low"}}matchesPattern(e,t){return new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).test(e)}shouldPreload(e,t){if(void 0!==t)return t;if(!this.config.enablePreloading)return!1;if(this.config.enableNetworkAwareLoading&&this.networkInfo){if(this.networkInfo.saveData)return!1;if("slow-2g"===this.networkInfo.effectiveType||"2g"===this.networkInfo.effectiveType)return"critical"===e.priority}return"critical"===e.priority||"high"===e.priority}shouldPrefetch(e,t){if(void 0!==t)return t;if(!this.config.enablePrefetching)return!1;if(this.config.enableNetworkAwareLoading&&this.networkInfo){if(this.networkInfo.saveData)return!1;if("slow-2g"===this.networkInfo.effectiveType||"2g"===this.networkInfo.effectiveType)return!1}return!0}preloadResource(t){return e(this,void 0,void 0,(function*(){if(t.isPreloaded||t.isLoaded)return;const e=performance.now();try{const i=document.createElement("link");i.rel="preload",i.href=t.url,i.as="script"===t.type?"script":"style"===t.type?"style":"font"===t.type?"font":"image"===t.type?"image":"fetch","font"!==t.type&&"fetch"!==t.type||(i.crossOrigin="anonymous"),yield new Promise(((r,o)=>{i.onload=()=>{t.isPreloaded=!0,t.loadTime=performance.now()-e,this.performanceMonitor.recordMetric("preload",t.loadTime,{url:t.url,type:t.type,priority:t.priority}),r()},i.onerror=()=>o(new Error(`Failed to preload ${t.url}`)),document.head.appendChild(i)}))}catch(e){}}))}prefetchResource(t){return e(this,void 0,void 0,(function*(){if(!t.isPrefetched&&!t.isLoaded)try{const e=document.createElement("link");e.rel="prefetch",e.href=t.url,document.head.appendChild(e),t.isPrefetched=!0,this.performanceMonitor.recordMetric("prefetch",1,{url:t.url,type:t.type,priority:t.priority})}catch(e){}}))}loadResources(t){return e(this,arguments,void 0,(function*(e,t={}){const i=e.map((e=>this.registerResource(e,t.type||"fetch",t))).sort(((e,t)=>{const i={critical:0,high:1,medium:2,low:3};return i[e.priority]-i[t.priority]})),r=[];for(let e=0;e<i.length;e+=this.config.maxConcurrentRequests){const t=i.slice(e,e+this.config.maxConcurrentRequests),o=yield Promise.all(t.map((e=>this.loadResource(e))));r.push(...o)}return r}))}loadResource(t){return e(this,void 0,void 0,(function*(){if(t.isLoaded)return t;const e=performance.now();try{const i=yield fetch(t.url);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);t.isLoaded=!0,t.loadTime=performance.now()-e,t.size=parseInt(i.headers.get("content-length")||"0"),this.performanceMonitor.recordMetric("resource-fetch",t.loadTime,{url:t.url,type:t.type,size:t.size,priority:t.priority})}catch(e){throw e}return t}))}loadBundleWithSplitting(t,i){return e(this,void 0,void 0,(function*(){if(!this.config.enableBundleSplitting)return this.loadBundle(t,i);try{const e=t.replace(/\.js$/,"-core.js");yield this.loadResource(this.registerResource(e,"script",{priority:"critical",compositionId:i}));const r=t.replace(/\.js$/,"-widget.js");yield this.loadResource(this.registerResource(r,"script",{priority:"high",compositionId:i}));const o=t.replace(/\.js$/,"-features.js");this.prefetchResource(this.registerResource(o,"script",{priority:"medium",compositionId:i}))}catch(e){return this.loadBundle(t,i)}}))}loadBundle(t,i){return e(this,void 0,void 0,(function*(){yield this.loadResource(this.registerResource(t,"script",{priority:"high",compositionId:i}))}))}generateCriticalResourceHints(){if(!this.config.enableCriticalResourceOptimization)return;const e=Array.from(this.resources.values()).filter((e=>"critical"===e.priority)).slice(0,10);for(const t of e)t.isPreloaded||t.isLoaded||this.preloadResource(t)}getMetrics(){const e=Array.from(this.resources.values()),t=e.filter((e=>e.isLoaded)),i=e.filter((e=>e.isPreloaded)),r=e.filter((e=>e.isPrefetched)),o=e.filter((e=>e.cached)),s=t.filter((e=>e.size)).reduce(((e,t)=>e+(t.size||0)),0),n=t.length>0?t.reduce(((e,t)=>e+(t.loadTime||0)),0)/t.length:0;return{totalResources:e.length,loadedResources:t.length,preloadedResources:i.length,prefetchedResources:r.length,cachedResources:o.length,totalSize:s,averageLoadTime:n,cacheHitRate:t.length>0?o.length/t.length:0,networkInfo:this.networkInfo,serviceWorkerActive:!!this.serviceWorker}}clearCache(){this.resources.clear(),this.serviceWorker&&this.serviceWorker.postMessage({type:"CLEAR_CACHE"})}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e)}getResource(e){return this.resources.get(e)}getResourcesByComposition(e){return Array.from(this.resources.values()).filter((t=>t.compositionId===e))}}let u=null;function g(e){return u||(u=new h(e)),u}function f(e={}){return u=new h(e),u}export{l as a,f as b,g as c,d,o as g,s as i,n as p};
1
+ import{_ as e}from"./vendor.js";import{P as t}from"./core.js";function i(){var e;try{if("undefined"!=typeof document){const e=document.querySelectorAll("script[src*='embed-sdk']");for(const t of Array.from(e))if("off"===t.getAttribute("data-widgetic-telemetry"))return!1}if("undefined"!=typeof window&&!1===(null===(e=window.WidgeticConfig)||void 0===e?void 0:e.telemetry))return!1}catch(e){}return!0}class r{constructor(e={}){this.metrics=[],this.webVitals={},this.widgetMetrics=new Map,this.isTracking=!1,this.config=Object.assign({enableTracking:t.ENABLE_PERFORMANCE_TRACKING,enableWebVitals:!0,enableWidgetMetrics:!0,enableResourceTracking:!0,enableBudgetMonitoring:!0,sampleRate:t.PERFORMANCE_SAMPLE_RATE,maxMetricsBuffer:t.MAX_METRICS_BUFFER,axiomApiEndpoint:t.AXIOM_API_ENDPOINT,statsigApiEndpoint:t.STATSIG_API_ENDPOINT,budgets:[{metric:"lcp",threshold:t.LCP_THRESHOLD,warningThreshold:t.LCP_WARNING_THRESHOLD,enabled:!0},{metric:"fid",threshold:t.FID_THRESHOLD,warningThreshold:t.FID_WARNING_THRESHOLD,enabled:!0},{metric:"cls",threshold:t.CLS_THRESHOLD,warningThreshold:t.CLS_WARNING_THRESHOLD,enabled:!0},{metric:"widget-load",threshold:t.WIDGET_LOAD_THRESHOLD,warningThreshold:t.WIDGET_LOAD_WARNING_THRESHOLD,enabled:!0},{metric:"bundle-size",threshold:t.BUNDLE_SIZE_THRESHOLD,warningThreshold:t.BUNDLE_SIZE_WARNING_THRESHOLD,enabled:!0}]},e),this.navigationStart=performance.now(),this.init()}init(){"undefined"!=typeof window&&this.config.enableTracking&&i()&&this.shouldSample()&&(this.isTracking=!0,this.config.enableWebVitals&&this.setupWebVitalsTracking(),this.config.enableResourceTracking&&this.setupResourceTracking(),setInterval((()=>this.reportMetrics()),3e4),window.addEventListener("beforeunload",(()=>this.reportMetrics())),window.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.reportMetrics()})))}shouldSample(){return Math.random()<this.config.sampleRate}setupWebVitalsTracking(){this.observePerformanceEntries(["largest-contentful-paint"],(e=>{const t=e[e.length-1],i=t.renderTime||t.loadTime;null!=i&&(this.webVitals.lcp=i,this.recordMetric("lcp",i),this.checkBudget("lcp",i))})),this.observePerformanceEntries(["first-input"],(e=>{const t=e[0],i=t.processingStart-t.startTime;void 0!==i&&(this.webVitals.fid=i,this.recordMetric("fid",this.webVitals.fid),this.checkBudget("fid",this.webVitals.fid))}));let e=0;this.observePerformanceEntries(["layout-shift"],(t=>{for(const i of t)i.hadRecentInput||(e+=i.value);this.webVitals.cls=e,this.recordMetric("cls",this.webVitals.cls),this.checkBudget("cls",this.webVitals.cls)})),this.observePerformanceEntries(["paint"],(e=>{const t=e.find((e=>"first-contentful-paint"===e.name));t&&(this.webVitals.fcp=t.startTime,this.recordMetric("fcp",this.webVitals.fcp))})),this.observePerformanceEntries(["navigation"],(e=>{const t=e[0],i=t.responseStart-t.requestStart;void 0!==i&&(this.webVitals.ttfb=i,this.recordMetric("ttfb",this.webVitals.ttfb))}))}setupResourceTracking(){this.observePerformanceEntries(["resource"],(e=>{for(const t of e)(t.name.includes("widgetic")||t.name.includes("widget"))&&this.recordMetric("resource-load",t.duration,{url:t.name,type:t.initiatorType,size:t.transferSize,cached:0===t.transferSize})}))}observePerformanceEntries(e,t){try{new PerformanceObserver((e=>{t(e.getEntries())})).observe({entryTypes:e})}catch(e){}}startWidgetLoad(e,t={}){if(!this.isTracking)return;const i=Object.assign({compositionId:e,loadStartTime:performance.now(),loadEndTime:0,renderTime:0,resourceLoadTime:0,errorCount:0,retryCount:0,bundleSize:0,isLazyLoaded:!1},t);this.widgetMetrics.set(e,i)}endWidgetLoad(e,t=!0){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);if(!i)return;i.loadEndTime=performance.now();const r=i.loadEndTime-i.loadStartTime;this.recordMetric("widget-load",r,{compositionId:e,success:t,isLazyLoaded:i.isLazyLoaded,bundleSize:i.bundleSize}),this.checkBudget("widget-load",r),i.bundleSize>0&&this.checkBudget("bundle-size",i.bundleSize)}recordWidgetRender(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&(i.renderTime=t),this.recordMetric("widget-render",t,{compositionId:e})}recordWidgetError(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&i.errorCount++,this.recordMetric("widget-error",1,{compositionId:e,error:t})}recordWidgetRetry(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&i.retryCount++,this.recordMetric("widget-retry",1,{compositionId:e,reason:t})}recordLazyLoad(e,t){if(!this.isTracking)return;const i=this.widgetMetrics.get(e);i&&(i.isLazyLoaded=!0,i.viewportEntry=t),this.recordMetric("lazy-load",t,{compositionId:e})}recordMetric(e,t,i){if(!this.isTracking)return;const r={name:e,value:t,timestamp:performance.now(),metadata:i};this.metrics.push(r),this.metrics.length>this.config.maxMetricsBuffer&&(this.metrics=this.metrics.slice(-this.config.maxMetricsBuffer)),this.config.enableBudgetMonitoring&&this.checkBudget(e,t)}checkBudget(e,t){const i=this.config.budgets.find((t=>t.metric===e&&t.enabled));i&&(t>i.threshold?this.triggerBudgetAlert(e,t,i.threshold,"exceeded"):i.warningThreshold&&t>i.warningThreshold&&this.triggerBudgetAlert(e,t,i.warningThreshold,"warning"))}triggerBudgetAlert(e,t,i,r){const o={type:"performance-budget-alert",metric:e,value:t,threshold:i,level:r,timestamp:Date.now(),url:window.location.href};window.dispatchEvent(new CustomEvent("widgetic:performance-alert",{detail:o})),this.recordMetric("budget-alert",t,o)}getWebVitals(){return Object.assign({},this.webVitals)}getWidgetMetrics(e){if(e){const t=this.widgetMetrics.get(e);return t?[t]:[]}return Array.from(this.widgetMetrics.values())}getMetrics(){return[...this.metrics]}getPerformanceSummary(){const e=performance.now(),t=Array.from(this.widgetMetrics.values());return{sessionDuration:e-this.navigationStart,webVitals:this.webVitals,widgets:{total:t.length,loaded:t.filter((e=>e.loadEndTime>0)).length,errors:t.reduce(((e,t)=>e+t.errorCount),0),retries:t.reduce(((e,t)=>e+t.retryCount),0),lazyLoaded:t.filter((e=>e.isLazyLoaded)).length,averageLoadTime:this.getAverageLoadTime(),totalBundleSize:t.reduce(((e,t)=>e+t.bundleSize),0)},metrics:{total:this.metrics.length,budgetViolations:this.metrics.filter((e=>"budget-alert"===e.name)).length},timestamp:Date.now()}}getAverageLoadTime(){const e=this.metrics.filter((e=>"widget-load"===e.name)).map((e=>e.value));return e.length>0?e.reduce(((e,t)=>e+t),0)/e.length:0}reportMetrics(){return e(this,void 0,void 0,(function*(){if(!this.isTracking||0===this.metrics.length)return;if(!i())return;const e=this.getPerformanceSummary();try{this.config.reportingEndpoint&&(yield this.reportToEndpoint(e)),this.config.axiomApiKey&&this.config.axiomDataset&&(yield this.reportToAxiom(e)),this.config.statsigKey&&(yield this.reportToStatsig(e))}catch(e){}}))}reportToEndpoint(t){return e(this,void 0,void 0,(function*(){yield fetch(this.config.reportingEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}))}reportToAxiom(t){return e(this,void 0,void 0,(function*(){const e=this.config.axiomApiEndpoint||"https://api.axiom.co/v1";yield fetch(`${e}/datasets/${this.config.axiomDataset}/ingest`,{method:"POST",headers:{Authorization:`Bearer ${this.config.axiomApiKey}`,"Content-Type":"application/x-ndjson"},body:JSON.stringify(t)+"\n"})}))}reportToStatsig(t){return e(this,void 0,void 0,(function*(){const e=this.config.statsigApiEndpoint||"https://events.statsigapi.net/v1/custom";yield fetch(e,{method:"POST",headers:{"STATSIG-API-KEY":this.config.statsigKey,"Content-Type":"application/json"},body:JSON.stringify({events:[{eventName:"widget_performance",value:t,timestamp:Date.now()}]})})}))}clearMetrics(){this.metrics=[],this.widgetMetrics.clear()}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e)}stop(){this.isTracking=!1,this.observer&&this.observer.disconnect(),this.reportMetrics()}}let o=null;function s(e){return o||(o=new r(e)),o}function n(e={}){return o=new r(e),o}var a=Object.freeze({__proto__:null,PerformanceMonitor:r,getPerformanceMonitor:s,initializePerformanceMonitoring:n});class c{constructor(e={}){this.items=new Map,this.observer=null,this.preloadObserver=null,this.loadingQueue=[],this.activeLoads=0,this.performanceMonitor=s(),this.retryTimeouts=new Map,this.config=Object.assign({enabled:!0,rootMargin:"50px",threshold:[0,.25,.5,.75,1],enablePreloading:!0,preloadDistance:"200px",retryAttempts:3,retryDelay:1e3,enablePrefetch:!0,prefetchDelay:2e3,enableProgressiveLoading:!0,maxConcurrentLoads:3,enableResourceHints:!0},e),this.init()}init(){"undefined"!=typeof window&&this.config.enabled&&("IntersectionObserver"in window?(this.setupIntersectionObserver(),this.config.enablePreloading&&this.setupPreloadObserver()):this.fallbackToImmediateLoading())}setupIntersectionObserver(){this.observer=new IntersectionObserver((e=>this.handleIntersection(e)),{rootMargin:this.config.rootMargin,threshold:this.config.threshold})}setupPreloadObserver(){this.preloadObserver=new IntersectionObserver((e=>this.handlePreloadIntersection(e)),{rootMargin:this.config.preloadDistance,threshold:0})}handleIntersection(e){for(const t of e){const e=t.target.getAttribute("data-lazy-id"),i=t.target.getAttribute("data-composition-id")||t.target.getAttribute("composition-id"),r=(e?this.items.get(e):null)||(i?this.items.get(i):null);r&&(!t.isIntersecting||r.isLoaded||r.isLoading||(r.viewportEntryTime=performance.now(),this.performanceMonitor.recordLazyLoad(r.compositionId,r.viewportEntryTime),this.queueLoad(r)))}}handlePreloadIntersection(e){for(const t of e){const e=t.target.getAttribute("data-lazy-id"),i=t.target.getAttribute("data-composition-id")||t.target.getAttribute("composition-id"),r=(e?this.items.get(e):null)||(i?this.items.get(i):null);!r||r.isPreloaded||r.isLoaded||t.isIntersecting&&this.preloadResources(r)}}register(e,t,i,r={}){const o=e.getAttribute("data-lazy-id")||`lazy_${t}_${Math.random().toString(36).substr(2,9)}`;e.setAttribute("data-lazy-id",o),e.setAttribute("data-composition-id",t);const s={element:e,compositionId:t,config:r.config||{},loadFunction:i,priority:r.priority||5,retryCount:0,isLoading:!1,isLoaded:!1,isPreloaded:!1,resourceUrls:r.resourceUrls};this.items.set(o,s),e.classList.add("widgetic-lazy-loading"),e.setAttribute("data-lazy","true"),this.observer&&this.observer.observe(e),this.preloadObserver&&this.config.enablePreloading&&this.preloadObserver.observe(e),this.config.enableResourceHints&&s.resourceUrls&&this.addResourceHints(s.resourceUrls),this.observer||setTimeout((()=>this.loadItem(s)),100)}unregister(e){let t=e,i=this.items.get(e);if(!i)for(const[r,o]of this.items.entries())if(o.compositionId===e){t=r,i=o;break}if(!i)return;this.observer&&this.observer.unobserve(i.element),this.preloadObserver&&this.preloadObserver.unobserve(i.element);const r=this.retryTimeouts.get(t)||this.retryTimeouts.get(i.compositionId);r&&(clearTimeout(r),this.retryTimeouts.delete(t),this.retryTimeouts.delete(i.compositionId)),this.items.delete(t)}queueLoad(e){if(this.config.enableProgressiveLoading){const t=this.loadingQueue.findIndex((t=>t.priority<e.priority));-1===t?this.loadingQueue.push(e):this.loadingQueue.splice(t,0,e),this.processLoadingQueue()}else this.loadItem(e)}processLoadingQueue(){return e(this,void 0,void 0,(function*(){for(;this.loadingQueue.length>0&&this.activeLoads<this.config.maxConcurrentLoads;){const e=this.loadingQueue.shift();!e||e.isLoaded||e.isLoading||this.loadItem(e)}}))}loadItem(t){return e(this,void 0,void 0,(function*(){if(!t.isLoading&&!t.isLoaded){t.isLoading=!0,this.activeLoads++,this.performanceMonitor.startWidgetLoad(t.compositionId,{isLazyLoaded:!0,bundleSize:this.estimateBundleSize(t)});try{t.element.classList.add("widgetic-loading"),t.element.classList.remove("widgetic-lazy-loading"),yield t.loadFunction(),t.isLoaded=!0,t.element.classList.remove("widgetic-loading"),t.element.classList.add("widgetic-loaded"),t.element.removeAttribute("data-lazy"),this.observer&&this.observer.unobserve(t.element),this.preloadObserver&&this.preloadObserver.unobserve(t.element),this.performanceMonitor.endWidgetLoad(t.compositionId,!0)}catch(e){if(t.element.classList.add("widgetic-load-error"),this.performanceMonitor.recordWidgetError(t.compositionId,e instanceof Error?e.message:"Load failed"),this.performanceMonitor.endWidgetLoad(t.compositionId,!1),t.retryCount<this.config.retryAttempts){t.retryCount++,this.performanceMonitor.recordWidgetRetry(t.compositionId,`Attempt ${t.retryCount}`);const e=setTimeout((()=>{t.isLoading=!1,this.retryTimeouts.delete(t.compositionId),this.loadItem(t)}),this.config.retryDelay*t.retryCount);this.retryTimeouts.set(t.compositionId,e)}}finally{t.isLoading=!1,this.activeLoads--,this.config.enableProgressiveLoading&&setTimeout((()=>this.processLoadingQueue()),10)}}}))}preloadResources(t){return e(this,void 0,void 0,(function*(){if(t.resourceUrls&&!t.isPreloaded){t.isPreloaded=!0;try{const e=t.resourceUrls.map((e=>this.preloadResource(e)));yield Promise.allSettled(e)}catch(e){}}}))}preloadResource(t){return e(this,void 0,void 0,(function*(){return new Promise(((e,i)=>{const r=document.createElement("link");r.rel="preload",r.href=t,t.endsWith(".js")?r.as="script":t.endsWith(".css")?r.as="style":t.match(/\.(png|jpg|jpeg|gif|webp|svg)$/)?r.as="image":(r.as="fetch",r.setAttribute("crossorigin","anonymous")),r.onload=()=>e(),r.onerror=()=>i(new Error(`Failed to preload ${t}`)),document.head.appendChild(r)}))}))}addResourceHints(e){for(const t of e)try{const e=new URL(t);if(e.origin!==window.location.origin){const t=document.createElement("link");t.rel="dns-prefetch",t.href=e.origin,document.head.appendChild(t)}}catch(e){}}estimateBundleSize(e){return 5e4+10*JSON.stringify(e.config).length}fallbackToImmediateLoading(){for(const e of this.items.values())e.isLoaded||e.isLoading||setTimeout((()=>this.loadItem(e)),1e3*Math.random())}forceLoad(t){const i=this.items.get(t);return i?i.isLoaded?Promise.resolve():new Promise(((t,r)=>{const o=i.loadFunction;i.loadFunction=()=>e(this,void 0,void 0,(function*(){try{yield o(),t()}catch(e){r(e)}})),this.loadItem(i)})):Promise.reject(new Error(`Widget ${t} not found`))}loadVisible(){const e=[];for(const t of this.items.values())t.isLoaded||t.isLoading||!this.isElementVisible(t.element)||e.push(t);return Promise.all(e.map((e=>this.forceLoad(e.compositionId))))}isElementVisible(e){const t=e.getBoundingClientRect(),i=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth;return t.top<i&&t.bottom>0&&t.left<r&&t.right>0}getMetrics(){const e=Array.from(this.items.values()),t=e.filter((e=>e.isLoaded)),i=e.filter((e=>e.retryCount>=this.config.retryAttempts)),r=this.performanceMonitor.getMetrics().filter((e=>"lazy-load"===e.name)).map((e=>e.value)),o=r.length>0?r.reduce(((e,t)=>e+t),0)/r.length:0,s=e.filter((e=>this.isElementVisible(e.element))),n=s.filter((e=>e.isLoaded)),a=s.length>0?n.length/s.length:0,c=e.filter((e=>e.isPreloaded)),d=e.length>0?c.length/e.length:0;return{totalItems:e.length,loadedItems:t.length,failedItems:i.length,averageLoadTime:o,viewportUtilization:a,preloadSuccess:d}}updateConfig(e){if(this.config=Object.assign(Object.assign({},this.config),e),this.observer&&(void 0!==e.threshold||void 0!==e.rootMargin)){this.observer.disconnect(),this.setupIntersectionObserver();for(const e of this.items.values())!e.isLoaded&&this.observer&&this.observer.observe(e.element)}}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.preloadObserver&&(this.preloadObserver.disconnect(),this.preloadObserver=null);for(const e of this.retryTimeouts.values())clearTimeout(e);this.retryTimeouts.clear(),this.items.clear(),this.loadingQueue=[]}}let d=null;function l(e){return d||(d=new c(e)),d}function h(e={}){return d=new c(e),d}class u{constructor(e={}){this.resources=new Map,this.loadQueue=[],this.activeRequests=0,this.performanceMonitor=s(),this.config=Object.assign({enablePreloading:!0,enablePrefetching:!0,enableServiceWorker:!1,enableBundleSplitting:!0,enableCriticalResourceOptimization:!0,enableNetworkAwareLoading:!0,preloadThreshold:200,prefetchDelay:2e3,maxConcurrentRequests:6,cacheDuration:864e5,priorityLevels:[{pattern:"**/*.css",priority:"critical",preload:!0,prefetch:!1},{pattern:"**/core.js",priority:"critical",preload:!0,prefetch:!1},{pattern:"**/widget-*.js",priority:"high",preload:!0,prefetch:!0},{pattern:"**/fonts/*",priority:"high",preload:!0,prefetch:!1},{pattern:"**/images/*",priority:"medium",preload:!1,prefetch:!0},{pattern:"**/analytics.js",priority:"low",preload:!1,prefetch:!0}]},e),this.init()}init(){return e(this,void 0,void 0,(function*(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.detectNetworkInfo(),this.config.enableServiceWorker&&(yield this.initServiceWorker()),this.setupResourceObserver(),this.addGlobalResourceHints())}))}detectNetworkInfo(){if("connection"in navigator){const e=navigator.connection;this.networkInfo={effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData},e.addEventListener("change",(()=>{this.networkInfo={effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData}}))}}initServiceWorker(){return e(this,void 0,void 0,(function*(){if("serviceWorker"in navigator)try{const e=yield navigator.serviceWorker.register("/sw-cache.js");this.serviceWorker=e.active||e.installing||e.waiting||void 0}catch(e){}}))}setupResourceObserver(){if("PerformanceObserver"in window){new PerformanceObserver((e=>{for(const t of e.getEntries())"resource"===t.entryType&&this.trackResourceLoad(t)})).observe({entryTypes:["resource"]})}}trackResourceLoad(e){const t=this.resources.get(e.name);t&&(t.isLoaded=!0,t.loadTime=e.duration,t.cached=0===e.transferSize,this.performanceMonitor.recordMetric("resource-load",e.duration,{url:e.name,type:t.type,size:e.transferSize,cached:t.cached,priority:t.priority}))}addGlobalResourceHints(){const e=["cdn.widgetic.com","analytics.widgetic.com","api.widgetic.com"];for(const t of e)this.addResourceHint("dns-prefetch",`https://${t}`);this.addResourceHint("preconnect","https://cdn.widgetic.com")}addResourceHint(e,t){if(document.querySelector(`link[rel="${e}"][href="${t}"]`))return;const i=document.createElement("link");i.rel=e,i.href=t,"preconnect"===e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}registerResource(e,t,i={}){const r={url:e,type:t,priority:i.priority||this.determineResourcePriority(e,t),isLoaded:!1,isPreloaded:!1,isPrefetched:!1,cached:!1,compositionId:i.compositionId};return this.resources.set(e,r),this.shouldPreload(r,i.preload)?this.preloadResource(r):this.shouldPrefetch(r,i.prefetch)&&setTimeout((()=>this.prefetchResource(r)),this.config.prefetchDelay),r}determineResourcePriority(e,t){for(const t of this.config.priorityLevels)if(this.matchesPattern(e,t.pattern))return t.priority;switch(t){case"style":return"critical";case"script":case"font":return"high";case"image":return"medium";default:return"low"}}matchesPattern(e,t){return new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).test(e)}shouldPreload(e,t){if(void 0!==t)return t;if(!this.config.enablePreloading)return!1;if(this.config.enableNetworkAwareLoading&&this.networkInfo){if(this.networkInfo.saveData)return!1;if("slow-2g"===this.networkInfo.effectiveType||"2g"===this.networkInfo.effectiveType)return"critical"===e.priority}return"critical"===e.priority||"high"===e.priority}shouldPrefetch(e,t){if(void 0!==t)return t;if(!this.config.enablePrefetching)return!1;if(this.config.enableNetworkAwareLoading&&this.networkInfo){if(this.networkInfo.saveData)return!1;if("slow-2g"===this.networkInfo.effectiveType||"2g"===this.networkInfo.effectiveType)return!1}return!0}preloadResource(t){return e(this,void 0,void 0,(function*(){if(t.isPreloaded||t.isLoaded)return;const e=performance.now();try{const i=document.createElement("link");i.rel="preload",i.href=t.url,i.as="script"===t.type?"script":"style"===t.type?"style":"font"===t.type?"font":"image"===t.type?"image":"fetch","font"!==t.type&&"fetch"!==t.type||(i.crossOrigin="anonymous"),yield new Promise(((r,o)=>{i.onload=()=>{t.isPreloaded=!0,t.loadTime=performance.now()-e,this.performanceMonitor.recordMetric("preload",t.loadTime,{url:t.url,type:t.type,priority:t.priority}),r()},i.onerror=()=>o(new Error(`Failed to preload ${t.url}`)),document.head.appendChild(i)}))}catch(e){}}))}prefetchResource(t){return e(this,void 0,void 0,(function*(){if(!t.isPrefetched&&!t.isLoaded)try{const e=document.createElement("link");e.rel="prefetch",e.href=t.url,document.head.appendChild(e),t.isPrefetched=!0,this.performanceMonitor.recordMetric("prefetch",1,{url:t.url,type:t.type,priority:t.priority})}catch(e){}}))}loadResources(t){return e(this,arguments,void 0,(function*(e,t={}){const i=e.map((e=>this.registerResource(e,t.type||"fetch",t))).sort(((e,t)=>{const i={critical:0,high:1,medium:2,low:3};return i[e.priority]-i[t.priority]})),r=[];for(let e=0;e<i.length;e+=this.config.maxConcurrentRequests){const t=i.slice(e,e+this.config.maxConcurrentRequests),o=yield Promise.all(t.map((e=>this.loadResource(e))));r.push(...o)}return r}))}loadResource(t){return e(this,void 0,void 0,(function*(){if(t.isLoaded)return t;const e=performance.now();try{const i=yield fetch(t.url);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);t.isLoaded=!0,t.loadTime=performance.now()-e,t.size=parseInt(i.headers.get("content-length")||"0"),this.performanceMonitor.recordMetric("resource-fetch",t.loadTime,{url:t.url,type:t.type,size:t.size,priority:t.priority})}catch(e){throw e}return t}))}loadBundleWithSplitting(t,i){return e(this,void 0,void 0,(function*(){if(!this.config.enableBundleSplitting)return this.loadBundle(t,i);try{const e=t.replace(/\.js$/,"-core.js");yield this.loadResource(this.registerResource(e,"script",{priority:"critical",compositionId:i}));const r=t.replace(/\.js$/,"-widget.js");yield this.loadResource(this.registerResource(r,"script",{priority:"high",compositionId:i}));const o=t.replace(/\.js$/,"-features.js");this.prefetchResource(this.registerResource(o,"script",{priority:"medium",compositionId:i}))}catch(e){return this.loadBundle(t,i)}}))}loadBundle(t,i){return e(this,void 0,void 0,(function*(){yield this.loadResource(this.registerResource(t,"script",{priority:"high",compositionId:i}))}))}generateCriticalResourceHints(){if(!this.config.enableCriticalResourceOptimization)return;const e=Array.from(this.resources.values()).filter((e=>"critical"===e.priority)).slice(0,10);for(const t of e)t.isPreloaded||t.isLoaded||this.preloadResource(t)}getMetrics(){const e=Array.from(this.resources.values()),t=e.filter((e=>e.isLoaded)),i=e.filter((e=>e.isPreloaded)),r=e.filter((e=>e.isPrefetched)),o=e.filter((e=>e.cached)),s=t.filter((e=>e.size)).reduce(((e,t)=>e+(t.size||0)),0),n=t.length>0?t.reduce(((e,t)=>e+(t.loadTime||0)),0)/t.length:0;return{totalResources:e.length,loadedResources:t.length,preloadedResources:i.length,prefetchedResources:r.length,cachedResources:o.length,totalSize:s,averageLoadTime:n,cacheHitRate:t.length>0?o.length/t.length:0,networkInfo:this.networkInfo,serviceWorkerActive:!!this.serviceWorker}}clearCache(){this.resources.clear(),this.serviceWorker&&this.serviceWorker.postMessage({type:"CLEAR_CACHE"})}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e)}getResource(e){return this.resources.get(e)}getResourcesByComposition(e){return Array.from(this.resources.values()).filter((t=>t.compositionId===e))}}let g=null;function f(e){return g||(g=new u(e)),g}function p(e={}){return g=new u(e),g}export{h as a,p as b,f as c,l as d,s as g,n as i,a as p};
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{g as t,a as i}from"./api.js";import{m as n,k as o,l as s,c as a,g as d}from"./core.js";import{g as r,a as c}from"./media.js";import{getMessenger as l}from"./messaging.js";import{R as u}from"./display.js";const g="DOMAIN_NOT_ALLOWED";function m(){if("undefined"==typeof document)return[];const e=[],t=document.querySelectorAll("script[src*='embed-sdk']");for(const i of Array.from(t)){const t=i.getAttribute("data-api-url");t&&t.trim()&&e.push(t.trim().replace(/\/+$/,""))}const i=window.WIDGETIC_EMBED_API;return i&&String(i).trim()&&e.push(String(i).trim().replace(/\/+$/,"")),e}function p(e){var t;if("undefined"==typeof window)return null;const i=window.__WIDGETIC_EMBED_LOOKUP__;return(null===(t=null==i?void 0:i[e])||void 0===t?void 0:t.embedUrl)||null}function h(t){return e(this,void 0,void 0,(function*(){try{const i=yield fetch(t,{method:"GET",mode:"cors"});if(!i.ok){const t=yield function(t){return e(this,void 0,void 0,(function*(){if(403!==t.status)return null;try{const e=yield t.json();if(!e||"object"!=typeof e||e.code!==g)return null;const i=e.details&&"object"==typeof e.details?e.details:null,n="string"==typeof(null==i?void 0:i.reason)?i.reason.slice(0,80):void 0;return{code:g,reason:n}}catch(e){return null}}))}(i);return t?{kind:"refused",refusal:t}:{kind:"unavailable"}}const n=function(e){if(!e||"object"!=typeof e)return null;const t="string"==typeof e.embedUrl?e.embedUrl:"";return t?{embedUrl:t,compositionId:"string"==typeof e.compositionId?e.compositionId:void 0,design:e.design&&"object"==typeof e.design?e.design:{},content:e.content&&"object"==typeof e.content?e.content:{},contentItems:Array.isArray(e.contentItems)?e.contentItems:[]}:null}(yield i.json());return n?{kind:"payload",payload:n}:{kind:"unavailable"}}catch(e){return{kind:"unavailable"}}}))}function f(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:{status:"found",payload:e.payload}}function b(e){const t=`/embed/compositions/${e}`,i=[];for(const e of m())i.push(`${e}${t}`);if("undefined"!=typeof window){const e=window.location.hostname;"localhost"!==e&&"127.0.0.1"!==e||i.push(`http://localhost:3000${t}`)}i.push(`https://api-gateway-service-uf6l.onrender.com${t}`);const s=o().replace(/\/+$/,"");i.push(`${s}${t}`);const a=String(n.PROD_API_URL).replace(/\/+$/,"");return a&&i.push(`${a}${t}`),[...new Set(i)]}function w(t){return e(this,void 0,void 0,(function*(){const e=m();for(const i of e){const e=yield h(`${i}/embed/compositions/${t}`);if("unavailable"!==e.kind)return f(e)}if("undefined"!=typeof window){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e){const e=yield h(`http://localhost:3000/embed/compositions/${t}`);if("unavailable"!==e.kind)return f(e)}}const i=yield function(e){const t=p(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const i=document.createElement("script");i.src=`https://cdn.widgetic.com/embed/compositions/${e}.js`,i.async=!0,i.onload=()=>t(p(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(t);if(i){for(const e of b(t)){const t=yield h(e);if("refused"===t.kind)return f(t);if("payload"===t.kind){const e=t.payload;return{status:"found",payload:Object.assign(Object.assign({},e),{embedUrl:e.embedUrl||i})}}}return{status:"found",payload:{embedUrl:i,compositionId:t}}}for(const e of b(t)){const t=yield h(e);if("unavailable"!==t.kind)return f(t)}return{status:"not-found"}}))}const v=new Set;function y(e,t){var i;if(v.has(e))return;v.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function I(e,t,i,n,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=i,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",n&&s.setAttribute("data-composition-id",n),function(e,t){if(!t)return;const i=t.design&&Object.keys(t.design).length>0?t.design:null,n=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!i&&!n&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};i&&(s.design=i),n&&(s.content=n),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}const E="undefined"!=typeof HTMLElement?HTMLElement:class{};class k extends E{static get observedAttributes(){return["composition-id","width","height","resize","autoscale","adaptive","theme"]}constructor(){super(),this.svelteComponent=null,this.compositionData=null,this.widgetData=null,this.loadedModule=null,this.isInitialized=!1,this.isWidgetConnected=!1,this.resizeObserver=null,this.eventListeners=new Map,this.widgetState={ready:!1,error:null,loading:!1,data:{}},this.instanceId=this.generateInstanceId(),this.cssNamespace=`widgetic-${this.instanceId}`,this.initializeCSSIsolation(),s.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){if(!this.isWidgetConnected){this.isWidgetConnected=!0,s.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 t=yield w(e);if("refused"===t.status)throw y(e,t.refusal),new Error("This embed is not authorized to be shown on this website.");const i="found"===t.status?t.payload:null;if(null==i?void 0:i.embedUrl)return this.innerHTML="",this.appendChild(I(i.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",e,i)),void this.setWidgetReady();yield this.loadWidgetData(e),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){s.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(s.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(s.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){s.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(i){return e(this,void 0,void 0,(function*(){const e=t();this.compositionData=yield e.getComposition(i),this.widgetData=yield e.getWidget(this.compositionData.widgetId),s.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:i,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=i();this.loadedModule=yield e.loadModule(this.widgetData),s.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return e(this,void 0,void 0,(function*(){if(!this.loadedModule||!this.compositionData)throw new Error("Widget module or composition data not loaded");try{const{component:e}=this.loadedModule.module,t=document.createElement("div");if(t.className=`widgetic-content-${this.instanceId}`,this.applyWidgetProperties(t),e.$$typeof)yield this.initializeReactComponent(t,e);else if(e._isVue||e.__isVue)yield this.initializeVueComponent(t,e);else{if("function"!=typeof e)throw new Error("Unsupported component type");yield this.initializeSvelteOrVanillaComponent(t,e)}this.innerHTML="",this.appendChild(t),this.isInitialized=!0,s.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw s.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,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})),s.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})),s.info("Widget ready",{instanceId:this.instanceId})}setErrorState(e){this.widgetState.error=e,this.widgetState.loading=!1,this.widgetState.ready=!1,this.setAttribute("data-error","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-ready"),this.innerHTML=`\n <div class="widgetic-error-${this.instanceId}">\n <strong>Widget Error</strong><br>\n <small>${e.message}</small>\n </div>\n `,this.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:e.message,instanceId:this.instanceId},bubbles:!0})),s.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return e(this,void 0,void 0,(function*(){this.cleanup(),this.isInitialized=!1,this.isWidgetConnected=!1,yield this.connectedCallback()}))}cleanup(){this.svelteComponent&&"function"==typeof this.svelteComponent.$destroy&&(this.svelteComponent.$destroy(),this.svelteComponent=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.eventListeners.forEach((e=>{if("function"==typeof e)try{e()}catch(e){s.warn("Failed to cleanup event listener",{instanceId:this.instanceId,error:e})}})),this.eventListeners.clear();const e=document.getElementById(`widgetic-base-styles-${this.instanceId}`);e&&e.remove(),s.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function x(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",k),s.info("WidgeticWidget custom element registered")))}class C{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 C.instance||(C.instance=new C),C.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 S{constructor(){this.autoScaleManager=C.getInstance(),x()}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:l}=t,u=document.createElement("widgetic-widget");if(u.setAttribute("composition-id",e),u.setAttribute("width",String(i)),u.setAttribute("height",String(n)),u.setAttribute("resize",o),"boolean"==typeof s?u.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(u.setAttribute("autoscale","true"),void 0!==s.minHeight&&u.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&u.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&u.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&u.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&u.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&u.setAttribute("autoscale-animation-duration",String(s.animationDuration))):u.setAttribute("autoscale","false"),u.setAttribute("adaptive",String(a)),d&&Object.keys(d).length>0){r().registerWidget(e,d),this.setupCustomElementMediaListener(u,e)}if(l&&Object.keys(l).length>0){c().registerWidget(e,l),this.setupCustomElementContentListener(u,e)}return{id:`custom-${e}-${Date.now()}`,element:u,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:()=>{u._mediaCommandCleanup&&u._mediaCommandCleanup(),u._mediaObserverCleanup&&u._mediaObserverCleanup(),u._contentPositionCleanup&&u._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=r(),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=c(),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 W=Object.freeze({__proto__:null,CustomElementRenderer:S});class M{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&s.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void s.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,a=i.initialMode||(o<i.breakpoint?"mobile":"desktop"),d={mode:a,breakpoint:i.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,d),this.callbacks.set(e,n);const r=new ResizeObserver((t=>{this.handleResize(e,t,i)}));r.observe(t),this.observers.set(e,r),n(d),s.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:a,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),s.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 s.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<i.breakpoint?"mobile":"desktop";if(o!==i.mode){const a={mode:o,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,a),n(a),s.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 a=t[t.length-1];if(!a)return;const d=a.contentRect.width,r=d<i.breakpoint?"mobile":"desktop";if(r!==n.mode){const t={mode:r,breakpoint:i.breakpoint,width:d,timestamp:Date.now()};this.currentStates.set(e,t),o(t),s.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:r,width:d,breakpoint:i.breakpoint})}else if(Math.abs(d-n.width)>10){const t=Object.assign(Object.assign({},n),{width:d,timestamp:Date.now()});this.currentStates.set(e,t),s.debug("Container width updated",{widgetId:e,width:d,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);s.debug("ResponsiveManager cleanup complete")}}let $=null;function L(){return $||($=new M),$}class A{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=C.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i,height:n,resize:o="fixed",autoscale:a=!1,adaptive:d,responsive:l,container:g,allowFullscreen:m=!0,sandbox:p=this.getDefaultSandboxPermissions(),allowedFeatures:h=this.getDefaultAllowedFeatures(),loading:f="lazy",enableResize:b=!0,compositionData:w,widgetData:v,security:y={},fallback:I={enabled:!0,timeout:1e4,retryCount:3},media:E}=t;if(!i||!n||!g)throw new Error("Missing required parameters: width, height, and container are required");const k=w||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},x=v||{id:k.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: ${k.name||e}`,w.loading=f,this.applySandboxSecurity(w,p,h),w.width=i.toString(),w.height=n.toString(),w.frameBorder="0",w.scrolling="no",m&&(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:a,adaptive:d,responsive:l,media:E},C=u.generateIframeCSS(v);C&&(w.style.cssText+=C),this.applyIframeStyling(w,e,{width:i,height:n,resize:o,autoscale:a,adaptive:d}),w.style.visibility="hidden",w.style.opacity="0",w.style.transition="opacity 0.3s ease",this.addLoadingIndicator(g,v),this.setupEnhancedIframeMessaging(w,e,y),this.setupLoadingOptimization(w,e,I);const S="lazy"===f,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(g),w.style.visibility="visible",w.style.opacity="1",t()},w.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(g),i(new Error(`Failed to load iframe for composition: ${e}`))}}));if(g.appendChild(w),b&&"undefined"!=typeof ResizeObserver){const t=new u({observeResize:!0}),i=`iframe-${e}-${Date.now()}`;w.setAttribute("data-widget-id",i),t.registerWidget(i,w,g,v),w.__resizeHandler=t,w.__widgetId=i}l&&"number"==typeof l&&l>0&&this.setupResponsiveMonitoring(w,g,e,l),this.iframeRegistry.set(e,w),w.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),S||(yield W);const M=`iframe-${e}-${Date.now()}`;if(s.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:i,height:n},resize:o,autoscale:a,responsive:l,sandbox:p.join(" "),features:h.join("; ")}),v.media&&Object.keys(v.media).length>0){r().registerWidget(e,v.media),this.setupIframeMediaListener(w,e)}if(t.content&&Object.keys(t.content).length>0){c().registerWidget(e,t.content),this.setupIframeContentListener(w,e)}return{id:M,element:w,compositionData:k,widgetData:x,renderMode:"iframe",cleanup:()=>this.cleanupWidget(w)}}catch(t){throw s.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(g),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){s.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(e),n=[];for(let e=0;e<i.length;e++){const o=i[e],a=t[e];if("fulfilled"===o.status)n.push(o.value);else{s.error("Iframe widget rendering failed in batch",{compositionId:a.compositionId,error:o.reason});const e=`error-${a.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(a,o.reason),compositionData:{id:a.compositionId,name:`Composition ${a.compositionId}`,widgetId:`widget-${a.compositionId}`,config:{}},widgetData:{id:`widget-${a.compositionId}`,name:`Widget ${a.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return s.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||[a.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=`${a.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 d();o.set("apiKey",e)}catch(e){s.warn("Failed to get auth token for iframe",e),a.API_KEY&&o.set("apiKey",a.API_KEY)}const r=`${n}?${o.toString()}`;return s.debug("Built secure iframe URL",{compositionId:t,url:r}),r}))}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)},s.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 a=0;const d=()=>{a<o?(a++,s.warn(`Iframe loading failed, retrying (${a}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+a}),1e3*a)):(s.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},r=setTimeout((()=>{s.warn("Iframe loading timeout",{compositionId:t,timeout:n}),d()}),n);this.loadingTimeouts.set(t,r),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),s.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{s.error("Iframe error occurred",{compositionId:t}),d()}))}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=l({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:o(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),s.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,s.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(s.debug("Enhanced iframe message received",{type:t.type,instanceId:t.instanceId,sequence:t.sequence}),t.type){case"resize":this.handleResizeMessage(e,t);break;case"ready":this.handleReadyMessage(e,t);break;case"error":this.handleErrorMessage(e,t);break;case"data":this.handleDataMessage(e,t);break;case"event":this.handleEventMessage(e,t);break;default:s.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width: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})),s.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})),s.info("Iframe widget ready",{instanceId:t.instanceId})}handleErrorMessage(e,t){e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,error:t.payload.error,code:t.payload.code},bubbles:!0})),s.error("Iframe widget error",{instanceId:t.instanceId,error:t.payload.error})}handleDataMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:data",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,data:t.payload},bubbles:!0})),s.debug("Iframe data received",{instanceId:t.instanceId,dataType:t.payload.type})}handleEventMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,eventType:t.payload.type,eventData:t.payload.data},bubbles:!0})),s.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){l().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 a=e.__messenger,d=e.__messagingCompositionId;a&&d&&a.unregisterHandler(d);const r=this.loadingTimeouts.get(d);r&&(clearTimeout(r),this.loadingTimeouts.delete(d)),d&&this.iframeRegistry.delete(d),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),s.debug("Iframe cleanup complete",{compositionId:d})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,i,n){const o=L(),a=l(),d={breakpoint:n,debounceDelay:150},r=`responsive-${i}`;o.registerWidget(r,t,d,(t=>{s.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),a.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,s.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:r})}setupIframeMediaListener(e,t){const i=r(),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=c(),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 z=null;var D=Object.freeze({__proto__:null,IframeRenderer:A,getIframeRenderer:function(){return z||(z=new A),z}});class R{constructor(){this.batchClient=t(),this.moduleLoader=i(),this.customElementRenderer=new S,this.iframeRenderer=new A,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 _=null;function T(){return _||(_=new R),_}function H(){_&&_.cleanupAll(),_=null}var O=Object.freeze({__proto__:null,WidgetRenderer:R,getWidgetRenderer:T,resetWidgetRenderer:H});export{S as C,A as I,k as W,y as a,x as b,I as c,R as d,H as e,W as f,T as g,D as i,w as r,O as w};
1
+ import{_ as e}from"./vendor.js";import{g as t,a as i}from"./api.js";import{m as n,k as o,l as s,c as a,g as r}from"./core.js";import{g as d,a as c}from"./media.js";import{getMessenger as l}from"./messaging.js";import{R as u}from"./display.js";const g=["DOMAIN_NOT_ALLOWED","UNPUBLISHED","SUSPENDED","NOT_FOUND","RATE_LIMITED"],m={DOMAIN_NOT_ALLOWED:"domain_not_allowed",UNPUBLISHED:"unpublished",SUSPENDED:"suspended",NOT_FOUND:"not_found",RATE_LIMITED:"rate_limited"};function p(e){return g.includes(e)?m[e]:null}const h="DOMAIN_NOT_ALLOWED";function f(){if("undefined"==typeof document)return[];const e=[],t=document.querySelectorAll("script[src*='embed-sdk']");for(const i of Array.from(t)){const t=i.getAttribute("data-api-url");t&&t.trim()&&e.push(t.trim().replace(/\/+$/,""))}const i=window.WIDGETIC_EMBED_API;return i&&String(i).trim()&&e.push(String(i).trim().replace(/\/+$/,"")),e}function b(e){var t;if("undefined"==typeof window)return null;const i=window.__WIDGETIC_EMBED_LOOKUP__;return(null===(t=null==i?void 0:i[e])||void 0===t?void 0:t.embedUrl)||null}function w(t){return e(this,void 0,void 0,(function*(){let e=null;try{e=yield t.json()}catch(t){e=null}const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e.code;return"string"==typeof t&&t.length>0&&t.length<=64?t:null}(e),n=(i&&p(i)?i:null)||(429===(o=t.status)?"RATE_LIMITED":404===o?"NOT_FOUND":null);var o;if(!n)return null;const s=p(n);return s?{gatewayCode:n,stateCode:s}:null}))}function v(t){return e(this,void 0,void 0,(function*(){let i="";try{i=new URL(t).origin}catch(e){i=""}try{const n=yield fetch(t,{method:"GET",mode:"cors"});if(!n.ok){const t=yield function(t){return e(this,void 0,void 0,(function*(){if(403!==t.status)return null;try{const e=yield t.json();if(!e||"object"!=typeof e||e.code!==h)return null;const i=e.details&&"object"==typeof e.details?e.details:null,n="string"==typeof(null==i?void 0:i.reason)?i.reason.slice(0,80):void 0;return{code:h,reason:n}}catch(e){return null}}))}(n);if(t)return{kind:"refused",refusal:t};const i=yield w(n);return i?{kind:"failed",failure:i}:{kind:"unavailable"}}const o=function(e){if(!e||"object"!=typeof e)return null;const t="string"==typeof e.embedUrl?e.embedUrl:"";return t?{embedUrl:t,compositionId:"string"==typeof e.compositionId?e.compositionId:void 0,design:e.design&&"object"==typeof e.design?e.design:{},content:e.content&&"object"==typeof e.content?e.content:{},contentItems:Array.isArray(e.contentItems)?e.contentItems:[]}:null}(yield n.json());return o?{kind:"payload",payload:o,gatewayOrigin:i}:{kind:"unavailable"}}catch(e){return{kind:"unavailable"}}}))}function y(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:"failed"===e.kind?{status:"failed",failure:e.failure}:{status:"found",payload:e.payload,gatewayOrigin:e.gatewayOrigin||void 0}}function I(e){const t=`/embed/compositions/${e}`,i=[];for(const e of f())i.push(`${e}${t}`);const s=o().replace(/\/+$/,"");i.push(`${s}${t}`);const a=String(n.PROD_API_URL).replace(/\/+$/,"");return a&&i.push(`${a}${t}`),[...new Set(i)]}function E(t){return e(this,void 0,void 0,(function*(){const e=f();for(const i of e){const e=yield v(`${i}/embed/compositions/${t}`);if("unavailable"!==e.kind)return y(e)}const i=yield function(e){const t=b(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const i=document.createElement("script");i.src=`https://cdn.widgetic.com/embed/compositions/${e}.js`,i.async=!0,i.onload=()=>t(b(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(t);if(i){for(const e of I(t)){const t=yield v(e);if("refused"===t.kind)return y(t);if("failed"!==t.kind&&"payload"===t.kind){const e=t.payload;return{status:"found",payload:Object.assign(Object.assign({},e),{embedUrl:e.embedUrl||i}),gatewayOrigin:t.gatewayOrigin||void 0}}}return{status:"found",payload:{embedUrl:i,compositionId:t}}}let n=null;for(const e of I(t)){const t=yield v(e);if("refused"===t.kind)return y(t);if("failed"!==t.kind){if("payload"===t.kind)return y(t)}else n=t.failure}return n?{status:"failed",failure:n}:{status:"not-found"}}))}const k=new Set;function x(e,t){var i;if(k.has(e))return;k.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function C(e,t,i,n,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=i,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",n&&s.setAttribute("data-composition-id",n),function(e,t){if(!t)return;const i=t.design&&Object.keys(t.design).length>0?t.design:null,n=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!i&&!n&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};i&&(s.design=i),n&&(s.content=n),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}const S="undefined"!=typeof HTMLElement?HTMLElement:class{};class W extends S{static get observedAttributes(){return["composition-id","width","height","resize","autoscale","adaptive","theme"]}constructor(){super(),this.svelteComponent=null,this.compositionData=null,this.widgetData=null,this.loadedModule=null,this.isInitialized=!1,this.isWidgetConnected=!1,this.resizeObserver=null,this.eventListeners=new Map,this.widgetState={ready:!1,error:null,loading:!1,data:{}},this.instanceId=this.generateInstanceId(),this.cssNamespace=`widgetic-${this.instanceId}`,this.initializeCSSIsolation(),s.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){if(!this.isWidgetConnected){this.isWidgetConnected=!0,s.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 t=yield E(e);if("refused"===t.status)throw x(e,t.refusal),new Error("This embed is not authorized to be shown on this website.");const i="found"===t.status?t.payload:null;if(null==i?void 0:i.embedUrl)return this.innerHTML="",this.appendChild(C(i.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",e,i)),void this.setWidgetReady();yield this.loadWidgetData(e),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){s.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(s.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(s.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){s.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(i){return e(this,void 0,void 0,(function*(){const e=t();this.compositionData=yield e.getComposition(i),this.widgetData=yield e.getWidget(this.compositionData.widgetId),s.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:i,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=i();this.loadedModule=yield e.loadModule(this.widgetData),s.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return e(this,void 0,void 0,(function*(){if(!this.loadedModule||!this.compositionData)throw new Error("Widget module or composition data not loaded");try{const{component:e}=this.loadedModule.module,t=document.createElement("div");if(t.className=`widgetic-content-${this.instanceId}`,this.applyWidgetProperties(t),e.$$typeof)yield this.initializeReactComponent(t,e);else if(e._isVue||e.__isVue)yield this.initializeVueComponent(t,e);else{if("function"!=typeof e)throw new Error("Unsupported component type");yield this.initializeSvelteOrVanillaComponent(t,e)}this.innerHTML="",this.appendChild(t),this.isInitialized=!0,s.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw s.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,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})),s.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})),s.info("Widget ready",{instanceId:this.instanceId})}setErrorState(e){this.widgetState.error=e,this.widgetState.loading=!1,this.widgetState.ready=!1,this.setAttribute("data-error","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-ready"),this.innerHTML=`\n <div class="widgetic-error-${this.instanceId}">\n <strong>Widget Error</strong><br>\n <small>${e.message}</small>\n </div>\n `,this.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:e.message,instanceId:this.instanceId},bubbles:!0})),s.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return e(this,void 0,void 0,(function*(){this.cleanup(),this.isInitialized=!1,this.isWidgetConnected=!1,yield this.connectedCallback()}))}cleanup(){this.svelteComponent&&"function"==typeof this.svelteComponent.$destroy&&(this.svelteComponent.$destroy(),this.svelteComponent=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.eventListeners.forEach((e=>{if("function"==typeof e)try{e()}catch(e){s.warn("Failed to cleanup event listener",{instanceId:this.instanceId,error:e})}})),this.eventListeners.clear();const e=document.getElementById(`widgetic-base-styles-${this.instanceId}`);e&&e.remove(),s.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function M(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",W),s.info("WidgeticWidget custom element registered")))}class L{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 L.instance||(L.instance=new L),L.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 r=o.scrollHeight;s(r)}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 r=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,r)}}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 r=performance.now(),d=o,c=i=>{const o=i-r,a=Math.min(o/n,1),l=1-Math.pow(1-a,3),u=d+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 A{constructor(){this.autoScaleManager=L.getInstance(),M()}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:r,content:l}=t,u=document.createElement("widgetic-widget");if(u.setAttribute("composition-id",e),u.setAttribute("width",String(i)),u.setAttribute("height",String(n)),u.setAttribute("resize",o),"boolean"==typeof s?u.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(u.setAttribute("autoscale","true"),void 0!==s.minHeight&&u.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&u.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&u.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&u.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&u.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&u.setAttribute("autoscale-animation-duration",String(s.animationDuration))):u.setAttribute("autoscale","false"),u.setAttribute("adaptive",String(a)),r&&Object.keys(r).length>0){d().registerWidget(e,r),this.setupCustomElementMediaListener(u,e)}if(l&&Object.keys(l).length>0){c().registerWidget(e,l),this.setupCustomElementContentListener(u,e)}return{id:`custom-${e}-${Date.now()}`,element:u,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:()=>{u._mediaCommandCleanup&&u._mediaCommandCleanup(),u._mediaObserverCleanup&&u._mediaObserverCleanup(),u._contentPositionCleanup&&u._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:r}=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,r||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=d(),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||{},r="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:r,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=c(),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 $=Object.freeze({__proto__:null,CustomElementRenderer:A});class D{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&s.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void s.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,a=i.initialMode||(o<i.breakpoint?"mobile":"desktop"),r={mode:a,breakpoint:i.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,r),this.callbacks.set(e,n);const d=new ResizeObserver((t=>{this.handleResize(e,t,i)}));d.observe(t),this.observers.set(e,d),n(r),s.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:a,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),s.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 s.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<i.breakpoint?"mobile":"desktop";if(o!==i.mode){const a={mode:o,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,a),n(a),s.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 a=t[t.length-1];if(!a)return;const r=a.contentRect.width,d=r<i.breakpoint?"mobile":"desktop";if(d!==n.mode){const t={mode:d,breakpoint:i.breakpoint,width:r,timestamp:Date.now()};this.currentStates.set(e,t),o(t),s.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:d,width:r,breakpoint:i.breakpoint})}else if(Math.abs(r-n.width)>10){const t=Object.assign(Object.assign({},n),{width:r,timestamp:Date.now()});this.currentStates.set(e,t),s.debug("Container width updated",{widgetId:e,width:r,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);s.debug("ResponsiveManager cleanup complete")}}let z=null;function R(){return z||(z=new D),z}class _{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=L.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i,height:n,resize:o="fixed",autoscale:a=!1,adaptive:r,responsive:l,container:g,allowFullscreen:m=!0,sandbox:p=this.getDefaultSandboxPermissions(),allowedFeatures:h=this.getDefaultAllowedFeatures(),loading:f="lazy",enableResize:b=!0,compositionData:w,widgetData:v,security:y={},fallback:I={enabled:!0,timeout:1e4,retryCount:3},media:E}=t;if(!i||!n||!g)throw new Error("Missing required parameters: width, height, and container are required");const k=w||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},x=v||{id:k.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: ${k.name||e}`,w.loading=f,this.applySandboxSecurity(w,p,h),w.width=i.toString(),w.height=n.toString(),w.frameBorder="0",w.scrolling="no",m&&(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:a,adaptive:r,responsive:l,media:E},C=u.generateIframeCSS(v);C&&(w.style.cssText+=C),this.applyIframeStyling(w,e,{width:i,height:n,resize:o,autoscale:a,adaptive:r}),w.style.visibility="hidden",w.style.opacity="0",w.style.transition="opacity 0.3s ease",this.addLoadingIndicator(g,v),this.setupEnhancedIframeMessaging(w,e,y),this.setupLoadingOptimization(w,e,I);const S="lazy"===f,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(g),w.style.visibility="visible",w.style.opacity="1",t()},w.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(g),i(new Error(`Failed to load iframe for composition: ${e}`))}}));if(g.appendChild(w),b&&"undefined"!=typeof ResizeObserver){const t=new u({observeResize:!0}),i=`iframe-${e}-${Date.now()}`;w.setAttribute("data-widget-id",i),t.registerWidget(i,w,g,v),w.__resizeHandler=t,w.__widgetId=i}l&&"number"==typeof l&&l>0&&this.setupResponsiveMonitoring(w,g,e,l),this.iframeRegistry.set(e,w),w.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),S||(yield W);const M=`iframe-${e}-${Date.now()}`;if(s.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:i,height:n},resize:o,autoscale:a,responsive:l,sandbox:p.join(" "),features:h.join("; ")}),v.media&&Object.keys(v.media).length>0){d().registerWidget(e,v.media),this.setupIframeMediaListener(w,e)}if(t.content&&Object.keys(t.content).length>0){c().registerWidget(e,t.content),this.setupIframeContentListener(w,e)}return{id:M,element:w,compositionData:k,widgetData:x,renderMode:"iframe",cleanup:()=>this.cleanupWidget(w)}}catch(t){throw s.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(g),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){s.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(e),n=[];for(let e=0;e<i.length;e++){const o=i[e],a=t[e];if("fulfilled"===o.status)n.push(o.value);else{s.error("Iframe widget rendering failed in batch",{compositionId:a.compositionId,error:o.reason});const e=`error-${a.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(a,o.reason),compositionData:{id:a.compositionId,name:`Composition ${a.compositionId}`,widgetId:`widget-${a.compositionId}`,config:{}},widgetData:{id:`widget-${a.compositionId}`,name:`Widget ${a.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return s.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||[a.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=`${a.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 r();o.set("apiKey",e)}catch(e){s.warn("Failed to get auth token for iframe",e),a.API_KEY&&o.set("apiKey",a.API_KEY)}const d=`${n}?${o.toString()}`;return s.debug("Built secure iframe URL",{compositionId:t,url:d}),d}))}applyIframeStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:r}=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),r&&this.makeIframeResponsive(e,r)}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)},s.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 a=0;const r=()=>{a<o?(a++,s.warn(`Iframe loading failed, retrying (${a}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+a}),1e3*a)):(s.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},d=setTimeout((()=>{s.warn("Iframe loading timeout",{compositionId:t,timeout:n}),r()}),n);this.loadingTimeouts.set(t,d),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),s.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{s.error("Iframe error occurred",{compositionId:t}),r()}))}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=l({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:o(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),s.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,s.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(s.debug("Enhanced iframe message received",{type:t.type,instanceId:t.instanceId,sequence:t.sequence}),t.type){case"resize":this.handleResizeMessage(e,t);break;case"ready":this.handleReadyMessage(e,t);break;case"error":this.handleErrorMessage(e,t);break;case"data":this.handleDataMessage(e,t);break;case"event":this.handleEventMessage(e,t);break;default:s.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width: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})),s.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})),s.info("Iframe widget ready",{instanceId:t.instanceId})}handleErrorMessage(e,t){e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,error:t.payload.error,code:t.payload.code},bubbles:!0})),s.error("Iframe widget error",{instanceId:t.instanceId,error:t.payload.error})}handleDataMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:data",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,data:t.payload},bubbles:!0})),s.debug("Iframe data received",{instanceId:t.instanceId,dataType:t.payload.type})}handleEventMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,eventType:t.payload.type,eventData:t.payload.data},bubbles:!0})),s.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){l().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 a=e.__messenger,r=e.__messagingCompositionId;a&&r&&a.unregisterHandler(r);const d=this.loadingTimeouts.get(r);d&&(clearTimeout(d),this.loadingTimeouts.delete(r)),r&&this.iframeRegistry.delete(r),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),s.debug("Iframe cleanup complete",{compositionId:r})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,i,n){const o=R(),a=l(),r={breakpoint:n,debounceDelay:150},d=`responsive-${i}`;o.registerWidget(d,t,r,(t=>{s.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),a.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,s.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:d})}setupIframeMediaListener(e,t){const i=d(),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=c(),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 T=null;var O=Object.freeze({__proto__:null,IframeRenderer:_,getIframeRenderer:function(){return T||(T=new _),T}});class U{constructor(){this.batchClient=t(),this.moduleLoader=i(),this.customElementRenderer=new A,this.iframeRenderer=new _,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 r="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,r),this.emitWidgetEvent("ready",{widgetId:e,compositionId:t.compositionId,renderMode:r.renderMode,loadTime:(null==a?void 0:a.loadTime)||0,cached:(null==a?void 0:a.cached)||!1}),r}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)):[],r=new Map(a.map((e=>[e.id,e]))),d=a.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));d.length>0&&(yield this.moduleLoader.preloadModules(d));const c=t.map((t=>e(this,void 0,void 0,(function*(){const e=o.get(t.compositionId)||{id:t.compositionId,widgetId:"default",name:"Composition",settings:{},config:{},version:"1.0.0"},i=r.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 H=null;function j(){return H||(H=new U),H}function N(){H&&H.cleanupAll(),H=null}var P=Object.freeze({__proto__:null,WidgetRenderer:U,getWidgetRenderer:j,resetWidgetRenderer:N});export{A as C,_ as I,W,x as a,M as b,C as c,U as d,N as e,$ as f,j as g,O as i,E as r,p as s,P as w};
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Maps gateway failure bodies and HTTP statuses to one vocabulary (R-15 / host bridge ยง4).
3
+ */
4
+ export declare const GATEWAY_REFUSAL_CODES: readonly ["DOMAIN_NOT_ALLOWED", "UNPUBLISHED", "SUSPENDED", "NOT_FOUND", "RATE_LIMITED"];
5
+ export type GatewayRefusalCode = (typeof GATEWAY_REFUSAL_CODES)[number];
6
+ export declare function stateCodeFromGatewayCode(code: string): string | null;
7
+ export declare function gatewayCodeFromHttpStatus(status: number): GatewayRefusalCode | null;
8
+ /** Reads `code` from a failed embed lookup response body when present. */
9
+ export declare function readGatewayCodeFromBody(body: unknown): string | null;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Partners may disable third-party telemetry from the embed script tag.
3
+ * Behaviour stays the same when telemetry is on; this only gates outbound calls.
4
+ */
5
+ declare global {
6
+ interface Window {
7
+ WidgeticConfig?: {
8
+ telemetry?: boolean;
9
+ };
10
+ }
11
+ }
12
+ /** True unless the page turned telemetry off before the script initialized. */
13
+ export declare function isEmbedTelemetryEnabled(): boolean;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Data attributes the host script writes on `<widgetic>` (host bridge contract ยง3).
3
+ */
4
+ /**
5
+ * Set on a host whose embed the gateway refused to show on this website (the
6
+ * owner limited it to the websites they listed), or answered "not available" for
7
+ * another reason (not found, not published, suspended). Its value is the
8
+ * gateway's code. The page is scanned again whenever it changes, and a refused
9
+ * host must not be looked up again each time, so a host that carries it is left
10
+ * alone.
11
+ */
12
+ export declare const REFUSED_HOST_ATTRIBUTE = "data-widgetic-refused";
13
+ export declare const HOST_CONTEXT_INVALID_ATTRIBUTE = "data-widgetic-context-invalid";
14
+ export declare const COMPOSITION_TRACKED_ATTRIBUTE = "data-widgetic-composition-tracked";
15
+ /** Clears every host-bridge marker before a new composition id is mounted. */
16
+ export declare function clearHostBridgeMarkers(host: HTMLElement): void;
17
+ /**
18
+ * When the element's composition id changes, drop the old mount so the new id can hydrate.
19
+ */
20
+ export declare function applyCompositionIdChange(host: HTMLElement, compositionId: string): void;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Builds the `widgetic:host` postMessage payload (host bridge contract ยง1).
3
+ */
4
+ import type { HostBridgeValidationResult } from "./host-bridge-validation.js";
5
+ export declare const HOST_BRIDGE_MESSAGE_VERSION = 1;
6
+ export type WidgeticHostMessage = {
7
+ type: "widgetic:host";
8
+ version: typeof HOST_BRIDGE_MESSAGE_VERSION;
9
+ compositionId: string;
10
+ context: Record<string, string | number> | null;
11
+ values: Record<string, string | number | boolean> | null;
12
+ lang: string | null;
13
+ dir: "ltr" | "rtl" | null;
14
+ mode: "light" | "dark" | null;
15
+ colors: Record<string, string> | null;
16
+ mediaResolver: string | null;
17
+ };
18
+ export declare function buildWidgeticHostMessage(compositionId: string, fields: HostBridgeValidationResult): WidgeticHostMessage;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Validates `<widgetic>` host-bridge attributes (contract ยง1 limits).
3
+ */
4
+ export type HostBridgeFieldSnapshot = {
5
+ context: Record<string, string | number> | null;
6
+ values: Record<string, string | number | boolean> | null;
7
+ lang: string | null;
8
+ dir: "ltr" | "rtl" | null;
9
+ mode: "light" | "dark" | null;
10
+ colors: Record<string, string> | null;
11
+ mediaResolver: string | null;
12
+ };
13
+ export type HostBridgeValidationResult = HostBridgeFieldSnapshot & {
14
+ contextInvalid: boolean;
15
+ };
16
+ /** One console.warn per element per distinct bad context attribute value. */
17
+ export declare function warnInvalidContextOnce(host: HTMLElement, raw: string | null): void;
18
+ /** Reads and validates host-bridge attributes on a `<widgetic>` element. */
19
+ export declare function validateHostBridgeAttributes(host: HTMLElement): HostBridgeValidationResult;
@@ -6,12 +6,9 @@
6
6
  * Copy web component = SDK + `<widgetic composition-id>` โ€” SDK looks up the
7
7
  * published widget.html and mounts it inside the host.
8
8
  */
9
- /**
10
- * Set on a host whose embed the gateway refused to show on this website (the
11
- * owner limited it to the websites they listed). Its value is the refusal code.
12
- * The page is scanned again whenever it changes, and a refused host must not be
13
- * looked up again each time, so a host that carries it is left alone.
14
- */
15
- export declare const REFUSED_HOST_ATTRIBUTE = "data-widgetic-refused";
9
+ import { REFUSED_HOST_ATTRIBUTE } from "./host-bridge-markers.js";
10
+ export { REFUSED_HOST_ATTRIBUTE };
16
11
  export declare function hydratePublishedHost(host: HTMLElement): boolean;
17
12
  export declare function hydratePublishedHosts(root?: ParentNode): number;
13
+ /** Clears the bridge when a host is removed from the page. */
14
+ export declare function teardownPublishedHost(host: HTMLElement): void;