@widgetic/embed-sdk 2.0.6 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/chunks/ABTestManager.js +1 -1
- package/dist/browser/chunks/advanced.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/core.js +1 -1
- package/dist/browser/chunks/display.js +1 -1
- package/dist/browser/chunks/media.js +1 -1
- package/dist/browser/chunks/messaging.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/chunks/security.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/ABTestManager.js +1 -1
- package/dist/esm/chunks/advanced.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/core.js +1 -1
- package/dist/esm/chunks/display.js +1 -1
- package/dist/esm/chunks/media.js +1 -1
- package/dist/esm/chunks/messaging.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/chunks/security.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +1 -1
package/dist/umd/embed-sdk.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["widgeticEmbed-sdk"]={})}(this,(function(e){"use strict";function t(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const i="https://api.axiom.co/v1",n="widgetic-performance",o="https://events.statsigapi.net/v1/custom",s=!0,r=1,a=1e3,d="",c=2500,l=2e3,u=100,h=50,g=.1,p=.05,m=1800,f=1200,v=800,y=600,w=3e3,b=2e3,I=5e5,T=3e5,k=!1,S="info",E="2.0.3",C="2.0.3";function A(){var e;return`${"undefined"!=typeof process&&"development"===(null===(e={NODE_ENV:"production"})||void 0===e?void 0:e.NODE_ENV)?R.DEV_API_URL:R.PROD_API_URL}${R.VERSION}`}const R={DEV_API_URL:"http://localhost:3000",DEV_CLIENT_URL:"http://localhost:5173",PROD_API_URL:"https://api.widgetic.com",PROD_CLIENT_URL:"https://widgetic.com",PROD_CDN_URL:"https://cdn.widgetic.com",VERSION:"/api/v1",NODE_ENV:"development",ENABLE_EDITING:!0},x="auto",D="inline",M="fixed",L=350,W=200,O=!1;let _=k;const P={get enabled(){return _},logLevel:S},z=["apikey","api_key","api-key","servicekey","service_key","service-key","token","access_token","auth_token","secret","password","private_key","authorization","bearer","internal_key","public_api_key","public_internal_key"];function q(e){if("string"==typeof e){const t=e.toLowerCase();for(const i of z)if(t.includes(i))return e.replace(/([a-zA-Z_-]*(?:key|token|secret|password)[a-zA-Z_-]*[:\s=]+)([^\s,}]+)/gi,"$1[REDACTED]");return e}if(null==e)return e;if(Array.isArray(e))return e.map(q);if("object"==typeof e){const t={};for(const[i,n]of Object.entries(e)){const e=i.toLowerCase();z.some((t=>e.includes(t.toLowerCase())||e===t.toLowerCase()))&&"string"==typeof n&&n.length>0?t[i]=`[REDACTED_${n.length}_CHARS]`:t[i]=q(n)}return t}return e}const U=new class{constructor(e=P.logLevel){this.logLevels={debug:0,info:1,warn:2,error:3},this.currentLevel=this.logLevels[e]}shouldLog(e){return P.enabled&&this.logLevels[e]>=this.currentLevel}formatMessage(e,t,...i){const n=(new Date).toISOString();return[`${`[Widgetic SDK] [${e.toUpperCase()}] [${n}]`} ${t}`,...i.map(q)]}debug(e,...t){this.shouldLog("debug")}info(e,...t){this.shouldLog("info")}warn(e,...t){this.shouldLog("warn")}error(e,...t){this.shouldLog("error")}setLevel(e){this.currentLevel=this.logLevels[e]}setDebug(e){!function(e){_=e}(e)}},B={debug:(e,...t)=>U.debug(e,...t),info:(e,...t)=>U.info(e,...t),warn:(e,...t)=>U.warn(e,...t),error:(e,...t)=>U.error(e,...t),setLevel:e=>U.setLevel(e)};class ${constructor(e){this.apiKey=e}getToken(){return t(this,void 0,void 0,(function*(){return this.apiKey}))}isTokenValid(){return t(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class F{constructor(e){this.tokenEndpoint=e.tokenEndpoint||e.endpoint||"",this.refreshEndpoint=e.refreshEndpoint,this.headers=e.headers||{},e.apiKey&&!this.headers.Authorization&&(this.headers.Authorization=`Bearer ${e.apiKey}`)}getToken(){return t(this,void 0,void 0,(function*(){if(this.cachedToken&&(yield this.isTokenValid()))return this.cachedToken;const e=yield fetch(this.tokenEndpoint,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.headers)});if(!e.ok)throw new Error(`Failed to fetch token: ${e.status} ${e.statusText}`);const t=yield e.json();if(this.cachedToken=t.token||t.access_token||t.apiKey,t.expires_in?this.tokenExpiry=Date.now()+1e3*t.expires_in:t.expires_at&&(this.tokenExpiry=new Date(t.expires_at).getTime()),!this.cachedToken)throw new Error("Invalid token response: no token found");return this.cachedToken}))}refreshToken(){return t(this,void 0,void 0,(function*(){if(!this.refreshEndpoint)return this.getToken();const e=yield fetch(this.refreshEndpoint,{method:"POST",headers:Object.assign({"Content-Type":"application/json",Authorization:`Bearer ${this.cachedToken}`},this.headers)});if(!e.ok)throw new Error(`Failed to refresh token: ${e.status} ${e.statusText}`);const t=yield e.json();if(this.cachedToken=t.token||t.access_token||t.apiKey,t.expires_in&&(this.tokenExpiry=Date.now()+1e3*t.expires_in),!this.cachedToken)throw new Error("Invalid token response: no token found");return this.cachedToken}))}isTokenValid(){return t(this,void 0,void 0,(function*(){return!!this.cachedToken&&(!this.tokenExpiry||Date.now()<this.tokenExpiry)}))}}class N{constructor(e,t){this.tokenFunction=e,this.validationFunction=t}getToken(){return t(this,void 0,void 0,(function*(){return yield this.tokenFunction()}))}isTokenValid(){return t(this,void 0,void 0,(function*(){return!this.validationFunction||(yield this.validationFunction())}))}}class j{constructor(e){this.apiKey=e}getToken(){return t(this,void 0,void 0,(function*(){if(!this.apiKey)throw new Error("No API key available. Please configure a TokenProvider or set API keys.");return this.apiKey}))}isTokenValid(){return t(this,void 0,void 0,(function*(){return!!this.apiKey}))}}var H="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};const V="https://api.widgetic.com/v1".replace(/\/+$/,"");class K{constructor(e){if(this.configuration={basePath:V,headers:{},middleware:[]},"string"==typeof e){const t=(null==e?void 0:e.startsWith("Bearer "))?e.slice(7):e;this.configuration.apiKey=e=>H(this,void 0,void 0,(function*(){return"authorization"===(null==e?void 0:e.toLowerCase())?`Bearer ${t}`:t})),this.configuration.accessToken=()=>H(this,void 0,void 0,(function*(){return t})),this.configuration.headers={"Content-Type":"application/json"}}else if(e){this.configuration=Object.assign(Object.assign({},e),{basePath:e.basePath||V});if("string"==typeof e.accessToken&&e.accessToken){const t=e.accessToken,i=t.startsWith("Bearer ")?t.slice(7):t;this.configuration.apiKey=e=>H(this,void 0,void 0,(function*(){return"authorization"===(null==e?void 0:e.toLowerCase())?`Bearer ${i}`:i})),this.configuration.accessToken=()=>H(this,void 0,void 0,(function*(){return i}))}e.headers||(this.configuration.headers={"Content-Type":"application/json"})}}set config(e){this.configuration=e}get basePath(){return null!=this.configuration.basePath?this.configuration.basePath:V}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||Z}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const e=this.configuration.apiKey;if(e)return"function"==typeof e?e:()=>e}get accessToken(){const e=this.configuration.accessToken;if(e)return"function"==typeof e?e:()=>H(this,void 0,void 0,(function*(){return e}))}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const G=new K;class Y{constructor(e=G){this.configuration=e,this.fetchApi=(e,t)=>H(this,void 0,void 0,(function*(){let i,n={url:e,init:t};this.middleware&&Array.isArray(this.middleware)||(this.middleware=[]);for(const e of this.middleware)e.pre&&(n=(yield e.pre(Object.assign({fetch:this.fetchApi},n)))||n);try{i=yield(this.configuration.fetchApi||fetch)(n.url,n.init)}catch(e){for(const t of this.middleware)t.onError&&(i=(yield t.onError({fetch:this.fetchApi,url:n.url,init:n.init,error:e,response:i?i.clone():void 0}))||i);if(void 0===i)throw e instanceof Error?new J(e,"The request failed and the interceptors did not return an alternative response"):e}for(const e of this.middleware)e.post&&(i=(yield e.post({fetch:this.fetchApi,url:n.url,init:n.init,response:i.clone()}))||i);return i})),"string"!=typeof e&&(!e||e instanceof K)||(e=new K(e)),this.configuration=e,this.middleware=this.configuration.middleware||[]}withMiddleware(...e){const t=this.clone();return t.middleware=t.middleware.concat(...e),t}withPreMiddleware(...e){const t=e.map((e=>({pre:e})));return this.withMiddleware(...t)}withPostMiddleware(...e){const t=e.map((e=>({post:e})));return this.withMiddleware(...t)}isJsonMime(e){return!!e&&Y.jsonRegex.test(e)}request(e,t){return H(this,void 0,void 0,(function*(){var i;const{url:n,init:o}=yield this.createFetchParams(e,t),s=new Headers(Object.assign(Object.assign(Object.assign({},this.configuration.headers),e.headers||{}),o.headers||{})),r=Object.assign(Object.assign({},o),{headers:s}),a=yield this.fetchApi(n,r);if(a&&a.status>=200&&a.status<300)return a;const d=a.clone();let c="Response returned an error code",l=null;try{const e=yield d.json(),t=e.error,n=t&&"object"==typeof t?t.message:t;c=e.message||n||c;const o=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.code;"string"==typeof o&&o.length>0&&(l=o)}catch(e){try{c=yield d.text()}catch(e){c=a.statusText}}throw new Q(a,c,l)}))}createFetchParams(e,t){return H(this,void 0,void 0,(function*(){let i=(this.configuration.basePath||V).replace(/\/+$/,"")+(e.path.startsWith("/")?e.path:`/${e.path}`);void 0!==e.query&&0!==Object.keys(e.query).length&&(i+="?"+this.configuration.queryParamsStringify(e.query));const n=Object.assign({},this.configuration.headers,e.headers);Object.keys(n).forEach((e=>void 0===n[e]?delete n[e]:{}));const o=this.configuration.apiKey;if(o&&!n.Authorization)try{const e=yield o("Authorization");e&&(n.Authorization=e.startsWith("Bearer ")?e:`Bearer ${e}`)}catch(e){}const s="function"==typeof t?t:()=>H(this,void 0,void 0,(function*(){return t})),r={method:e.method,headers:n,body:e.body,credentials:this.configuration.credentials},a=Object.assign(Object.assign({},r),yield s({init:r,context:e}));let d;var c;c=a.body,d="undefined"!=typeof FormData&&c instanceof FormData||a.body instanceof URLSearchParams||function(e){return"undefined"!=typeof Blob&&e instanceof Blob}(a.body)?a.body:this.isJsonMime(n["Content-Type"])?JSON.stringify(a.body):a.body;return{url:i,init:Object.assign(Object.assign({},a),{body:d})}}))}clone(){const e=new(0,this.constructor)(this.configuration);return e.middleware=this.middleware.slice(),e}}Y.jsonRegex=new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$","i");class Q extends Error{constructor(e,t,i=null){super(t),this.response=e,this.name="ResponseError",this.code=i}}class J extends Error{constructor(e,t){super(t),this.cause=e,this.name="FetchError"}}class X extends Error{constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}function Z(e,t=""){return Object.keys(e).map((i=>ee(i,e[i],t))).filter((e=>e.length>0)).join("&")}function ee(e,t,i=""){const n=i+(i.length?`[${e}]`:e);if(t instanceof Array){const e=t.map((e=>encodeURIComponent(String(e)))).join(`&${encodeURIComponent(n)}=`);return`${encodeURIComponent(n)}=${e}`}if(t instanceof Set){return ee(e,Array.from(t),i)}return t instanceof Date?`${encodeURIComponent(n)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?Z(t,n):`${encodeURIComponent(n)}=${encodeURIComponent(String(t))}`}function te(e,t){return Object.keys(e).reduce(((i,n)=>Object.assign(Object.assign({},i),{[n]:t(e[n])})),{})}class ie{constructor(e,t=e=>e){this.raw=e,this.transformer=t}unwrapSuccessEnvelope(e){if(e&&"object"==typeof e&&"success"in e&&"data"in e){const{success:t,data:i,meta:n}=e,o="boolean"!=typeof t||t;return Array.isArray(i)?{success:o,data:i,meta:n,rawData:i}:i&&"object"==typeof i?Object.assign({success:o,data:i,meta:n},i):{success:o,data:i,meta:n}}return e}value(){return H(this,void 0,void 0,(function*(){const e=yield this.raw.json();return this.transformer(this.unwrapSuccessEnvelope(e))}))}}class ne{constructor(e){this.raw=e}value(){return H(this,void 0,void 0,(function*(){}))}}function oe(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,abTestId:null==e.abTestId?void 0:e.abTestId,compositionId:null==e.compositionId?void 0:e.compositionId,name:null==e.name?void 0:e.name,description:null==e.description?void 0:e.description,trafficPercentage:null==e.trafficPercentage?void 0:e.trafficPercentage,embedCode:null==e.embedCode?void 0:e.embedCode,totalImpressions:null==e.totalImpressions?void 0:e.totalImpressions,totalConversions:null==e.totalConversions?void 0:e.totalConversions,conversionRate:null==e.conversionRate?void 0:e.conversionRate,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt)}}(e)}function se(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,creatorId:null==e.creatorId?void 0:e.creatorId,organizationId:null==e.organizationId?void 0:e.organizationId,workspaceType:null==e.workspaceType?void 0:e.workspaceType,name:null==e.name?void 0:e.name,description:null==e.description?void 0:e.description,status:null==e.status?void 0:e.status,successMetrics:null==e.successMetrics?void 0:e.successMetrics,primaryMetric:null==e.primaryMetric?void 0:e.primaryMetric,confidenceLevel:null==e.confidenceLevel?void 0:e.confidenceLevel,minSampleSize:null==e.minSampleSize?void 0:e.minSampleSize,autoGraduate:null==e.autoGraduate?void 0:e.autoGraduate,graduationThreshold:null==e.graduationThreshold?void 0:e.graduationThreshold,startDate:null==e.startDate?void 0:new Date(e.startDate),endDate:null==e.endDate?void 0:new Date(e.endDate),durationDays:null==e.durationDays?void 0:e.durationDays,winningVariantId:null==e.winningVariantId?void 0:e.winningVariantId,graduatedAt:null==e.graduatedAt?void 0:new Date(e.graduatedAt),statisticalSignificance:null==e.statisticalSignificance?void 0:e.statisticalSignificance,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt),variants:null==e.variants?void 0:e.variants.map(oe)}}(e)}function re(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,ab_test_id:null==e.ab_test_id?void 0:e.ab_test_id,variant_id:null==e.variant_id?void 0:e.variant_id,user_id:null==e.user_id?void 0:e.user_id,session_id:null==e.session_id?void 0:e.session_id,user_identifier_hash:null==e.user_identifier_hash?void 0:e.user_identifier_hash,assigned_at:null==e.assigned_at?void 0:new Date(e.assigned_at)}}(e)}function ae(e){return function(e){if(null==e)return e;return{hasMeaningfulContrast:null==e.hasMeaningfulContrast?void 0:e.hasMeaningfulContrast,primaryDriver:null==e.primaryDriver?void 0:e.primaryDriver,cognitiveClarityScore:null==e.cognitiveClarityScore?void 0:e.cognitiveClarityScore,safeToGraduate:null==e.safeToGraduate?void 0:e.safeToGraduate,qualitativeReason:null==e.qualitativeReason?void 0:e.qualitativeReason}}(e)}function de(e){return function(e){if(null==e)return e;return{action:null==e.action?void 0:e.action,reason:null==e.reason?void 0:e.reason,minAdditionalSamples:null==e.minAdditionalSamples?void 0:e.minAdditionalSamples}}(e)}function ce(e){return function(e){if(null==e)return e;return{totalImpressions:null==e.totalImpressions?void 0:e.totalImpressions,totalConversions:null==e.totalConversions?void 0:e.totalConversions,overallConversionRate:null==e.overallConversionRate?void 0:e.overallConversionRate,statisticalPower:null==e.statisticalPower?void 0:e.statisticalPower,confidenceLevel:null==e.confidenceLevel?void 0:e.confidenceLevel}}(e)}function le(e){return function(e){if(null==e)return e;return{variantId:null==e.variantId?void 0:e.variantId,variantName:null==e.variantName?void 0:e.variantName,impressions:null==e.impressions?void 0:e.impressions,conversions:null==e.conversions?void 0:e.conversions,conversionRate:null==e.conversionRate?void 0:e.conversionRate,confidenceIntervalLower:null==e.confidenceIntervalLower?void 0:e.confidenceIntervalLower,confidenceIntervalUpper:null==e.confidenceIntervalUpper?void 0:e.confidenceIntervalUpper,zScore:null==e.zScore?void 0:e.zScore,pValue:null==e.pValue?void 0:e.pValue,isWinner:null==e.isWinner?void 0:e.isWinner,liftPercentage:null==e.liftPercentage?void 0:e.liftPercentage,statisticalSignificance:null==e.statisticalSignificance?void 0:e.statisticalSignificance,bayesianProbabilityToBeatControl:null==e.bayesianProbabilityToBeatControl?void 0:e.bayesianProbabilityToBeatControl}}(e)}function ue(e){return function(e){if(null==e)return e;return{overall:null==e.overall?void 0:ce(e.overall),variants:null==e.variants?void 0:e.variants.map(le),recommendation:null==e.recommendation?void 0:de(e.recommendation)}}(e)}function he(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,translationId:null==e.translationId?void 0:e.translationId,compositionId:null==e.compositionId?void 0:e.compositionId,languageCode:null==e.languageCode?void 0:e.languageCode,languageName:null==e.languageName?void 0:e.languageName,isRoot:null==e.isRoot?void 0:e.isRoot,embedCode:null==e.embedCode?void 0:e.embedCode,totalViews:null==e.totalViews?void 0:e.totalViews,status:null==e.status?void 0:e.status,translationProgress:null==e.translationProgress?void 0:e.translationProgress,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt)}}(e)}function ge(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,creatorId:null==e.creatorId?void 0:e.creatorId,name:null==e.name?void 0:e.name,description:null==e.description?void 0:e.description,rootCompositionId:null==e.rootCompositionId?void 0:e.rootCompositionId,rootLanguage:null==e.rootLanguage?void 0:e.rootLanguage,status:null==e.status?void 0:e.status,embedCode:null==e.embedCode?void 0:e.embedCode,selectedLanguages:null==e.selectedLanguages?void 0:e.selectedLanguages,totalViews:null==e.totalViews?void 0:e.totalViews,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt),variants:null==e.variants?void 0:e.variants.map(he)}}(e)}function pe(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ge(e.data),message:null==e.message?void 0:e.message}}(e)}function me(e){return function(e){if(null==e)return e;return{id:e.id,composition_id:e.composition_id,date:new Date(e.date),country:e.country,region:null==e.region?void 0:e.region,city:null==e.city?void 0:e.city,views:e.views,unique_users:e.unique_users,created_at:null==e.created_at?void 0:new Date(e.created_at),updated_at:null==e.updated_at?void 0:new Date(e.updated_at)}}(e)}function fe(e){return function(e){if(null==e)return e;return{total_views:null==e.total_views?void 0:e.total_views,unique_views:null==e.unique_views?void 0:e.unique_views,total_interactions:null==e.total_interactions?void 0:e.total_interactions,unique_interactions:null==e.unique_interactions?void 0:e.unique_interactions,average_session_time:null==e.average_session_time?void 0:e.average_session_time,bounce_rate:null==e.bounce_rate?void 0:e.bounce_rate}}(e)}function ve(e){return function(e){if(null==e)return e;return{id:e.id,compositionId:e.compositionId,date:new Date(e.date),deviceType:e.deviceType,views:e.views,uniqueUsers:e.uniqueUsers,avgSessionDuration:e.avgSessionDuration,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt)}}(e)}function ye(e){return function(e){if(null==e)return e;return{id:e.id,composition_id:e.composition_id,timestamp:new Date(e.timestamp),event_type:e.event_type,event_data:null==e.event_data?void 0:e.event_data,user_id:null==e.user_id?void 0:e.user_id,session_id:null==e.session_id?void 0:e.session_id,ip_address:null==e.ip_address?void 0:e.ip_address,user_agent:null==e.user_agent?void 0:e.user_agent,referrer:null==e.referrer?void 0:e.referrer,created_at:null==e.created_at?void 0:new Date(e.created_at)}}(e)}function we(e){return function(e){if(null==e)return e;return{id:e.id,composition_id:e.composition_id,date:new Date(e.date),source:e.source,source_url:null==e.source_url?void 0:e.source_url,views:e.views,unique_users:e.unique_users,created_at:null==e.created_at?void 0:new Date(e.created_at),updated_at:null==e.updated_at?void 0:new Date(e.updated_at)}}(e)}function be(e){return function(e){if(null==e)return e;return{summary:fe(e.summary),devices:e.devices.map(ve),geography:e.geography.map(me),referrers:e.referrers.map(we),events:null==e.events?void 0:e.events.map(ye)}}(e)}function Ie(e){return function(e){if(null==e)return e;return{composition_id:e.composition_id,event_type:e.event_type,event_data:e.event_data,user_id:e.user_id,session_id:e.session_id,ip_address:e.ip_address,user_agent:e.user_agent,referrer:e.referrer}}(e,!1)}function Te(e){return function(e){if(null==e)return e;return{events:e.events.map(Ie)}}(e,!1)}function ke(e){return function(e){if(null==e)return e;return{canAccess:null==e.canAccess?void 0:e.canAccess,reason:null==e.reason?void 0:e.reason}}(e)}function Se(e){return function(e){if(null==e)return e;return{canAccess:null==e.canAccess?void 0:e.canAccess,reason:null==e.reason?void 0:e.reason}}(e)}function Ee(e){return function(e){if(null==e)return e;return{should_stop:null==e.should_stop?void 0:e.should_stop,reason:null==e.reason?void 0:e.reason,new_status:null==e.new_status?void 0:e.new_status}}(e)}function Ce(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ee(e.data)}}(e)}function Ae(e){return function(e){if(null==e)return e;return{id:e.id,creatorId:e.creatorId,widgetId:e.widgetId,name:e.name,content:e.content,status:e.status,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),embedSettings:null==e.embedSettings?void 0:e.embedSettings,design:null==e.design?void 0:e.design,databaseId:null==e.databaseId?void 0:e.databaseId,projectId:null==e.projectId?void 0:e.projectId,managedUserId:null==e.managedUserId?void 0:e.managedUserId}}(e)}function Re(e){return function(e){if(null==e)return e;return{name:e.name,type:e.type}}(e)}function xe(e){return function(e){if(null==e)return e;return{name:e.name,columns:e.columns.map(Re),rows:e.rows}}(e)}function De(e){return function(e){if(null==e)return e;return{compositionId:e.compositionId,hasData:e.hasData,tables:e.tables.map(xe)}}(e)}function Me(e){return function(e){if(null==e)return e;return{value:e.value,count:e.count}}(e)}function Le(e){return function(e){if(null==e)return e;return{compositionId:e.compositionId,table:e.table,totalRows:e.totalRows,tallies:null==e.tallies?null:e.tallies.map(Me),moreGroups:e.moreGroups,columns:e.columns,rows:null==e.rows?null:e.rows,moreRows:e.moreRows}}(e)}function We(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,compositionId:null==e.compositionId?void 0:e.compositionId,version:null==e.version?void 0:e.version,content:null==e.content?void 0:e.content,createdAt:null==e.createdAt?void 0:new Date(e.createdAt)}}(e)}function Oe(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:re(e.data)}}(e)}function _e(e){return function(e){if(null==e)return e;return{name:e.name,description:e.description,compositionId:e.compositionId,trafficPercentage:e.trafficPercentage}}(e,!1)}function Pe(e){return function(e){if(null==e)return e;return{name:e.name,description:e.description,status:e.status,workspaceType:e.workspaceType,variants:e.variants.map(_e),successMetrics:e.successMetrics,primaryMetric:e.primaryMetric,confidenceLevel:e.confidenceLevel,minSampleSize:e.minSampleSize,autoGraduate:e.autoGraduate,graduationThreshold:e.graduationThreshold,startDate:null==e.startDate?void 0:e.startDate.toISOString(),endDate:null==e.endDate?void 0:e.endDate.toISOString(),durationDays:e.durationDays}}(e,!1)}function ze(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ae(e.data)}}(e)}function qe(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ge(e.data),message:null==e.message?void 0:e.message}}(e)}function Ue(e){return function(e){if(null==e)return e;return{x:null==e.x?void 0:e.x,y:null==e.y?void 0:e.y}}(e)}function Be(e){return function(e){if(null==e)return e;return{width:null==e.width?void 0:e.width,height:null==e.height?void 0:e.height}}(e)}function $e(e){return function(e){if(null==e)return e;return{componentId:null==e.componentId?void 0:e.componentId,path:null==e.path?void 0:e.path,planId:null==e.planId?void 0:e.planId,status:null==e.status?void 0:e.status,position:null==e.position?void 0:Ue(e.position),size:null==e.size?void 0:Be(e.size)}}(e)}function Fe(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,name:null==e.name?void 0:e.name,creatorId:null==e.creatorId?void 0:e.creatorId,description:null==e.description?void 0:e.description,type:null==e.type?void 0:e.type,content:null==e.content?void 0:e.content,isPublic:null==e.isPublic?void 0:e.isPublic,isDraft:null==e.isDraft?void 0:e.isDraft,shareId:null==e.shareId?void 0:e.shareId,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt),jsPath:null==e.jsPath?void 0:e.jsPath,canvasId:null==e.canvasId?void 0:e.canvasId,repoId:null==e.repoId?void 0:e.repoId,databaseId:null==e.databaseId?void 0:e.databaseId,version:null==e.version?void 0:e.version,componentsMetadata:null==e.componentsMetadata?void 0:e.componentsMetadata.map($e),cpgSchemaId:null==e.cpgSchemaId?void 0:e.cpgSchemaId,lastCpgCommitSha:null==e.lastCpgCommitSha?void 0:e.lastCpgCommitSha,organizationId:null==e.organizationId?void 0:e.organizationId,projectFolder:null==e.projectFolder?void 0:e.projectFolder,workspaceType:null==e.workspaceType?void 0:e.workspaceType,managedUserId:null==e.managedUserId?void 0:e.managedUserId,warnings:null==e.warnings?void 0:e.warnings}}(e)}function Ne(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Fe(e.data),meta:null==e.meta?void 0:e.meta}}(e)}function je(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:se(e.data)}}(e)}function He(e){return function(e){if(null==e)return e;return{id:e.id,compositionId:e.compositionId,date:new Date(e.date),totalViews:e.totalViews,uniqueViews:e.uniqueViews,totalInteractions:e.totalInteractions,uniqueInteractions:e.uniqueInteractions,totalSessionTime:e.totalSessionTime,averageSessionTime:e.averageSessionTime,bounceRate:e.bounceRate,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt)}}(e)}function Ve(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,message:null==e.message?void 0:e.message}}(e)}function Ke(e){return function(e){if(null==e)return e;return{operationId:null==e.operationId?void 0:e.operationId}}(e)}function Ge(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ke(e.data)}}(e)}function Ye(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,name:null==e.name?void 0:e.name,creatorId:null==e.creatorId?void 0:e.creatorId,description:null==e.description?void 0:e.description,type:null==e.type?void 0:e.type,content:null==e.content?void 0:e.content,isPublic:null==e.isPublic?void 0:e.isPublic,isDraft:null==e.isDraft?void 0:e.isDraft,shareId:null==e.shareId?void 0:e.shareId,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt),jsPath:null==e.jsPath?void 0:e.jsPath,canvasId:null==e.canvasId?void 0:e.canvasId,repoId:null==e.repoId?void 0:e.repoId,databaseId:null==e.databaseId?void 0:e.databaseId,version:null==e.version?void 0:e.version,componentsMetadata:null==e.componentsMetadata?void 0:e.componentsMetadata.map($e),cpgSchemaId:null==e.cpgSchemaId?void 0:e.cpgSchemaId,lastCpgCommitSha:null==e.lastCpgCommitSha?void 0:e.lastCpgCommitSha,organizationId:null==e.organizationId?void 0:e.organizationId,projectFolder:null==e.projectFolder?void 0:e.projectFolder,workspaceType:null==e.workspaceType?void 0:e.workspaceType,managedUserId:null==e.managedUserId?void 0:e.managedUserId}}(e)}function Qe(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ye(e.data),warnings:null==e.warnings?void 0:e.warnings}}(e)}function Je(e){return function(e){if(null==e)return e;return{token:null==e.token?void 0:e.token,tokenType:null==e.tokenType?void 0:e.tokenType,expiresIn:null==e.expiresIn?void 0:e.expiresIn,expiresAt:null==e.expiresAt?void 0:new Date(e.expiresAt),scopes:null==e.scopes?void 0:e.scopes}}(e)}function Xe(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Je(e.data)}}(e)}function Ze(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,name:null==e.name?void 0:e.name,composition_id:null==e.composition_id?void 0:e.composition_id,traffic_percentage:null==e.traffic_percentage?void 0:e.traffic_percentage}}(e)}function et(e){return function(e){if(null==e)return e;return{test_id:null==e.test_id?void 0:e.test_id,name:null==e.name?void 0:e.name,status:null==e.status?void 0:e.status,variants:null==e.variants?void 0:e.variants.map(Ze),success_metrics:null==e.success_metrics?void 0:e.success_metrics}}(e)}function tt(e){return function(e){if(null==e)return e;return{page:null==e.page?void 0:e.page,size:null==e.size?void 0:e.size,total:null==e.total?void 0:e.total}}(e)}function it(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(Ae),meta:null==e.meta?void 0:tt(e.meta)}}(e)}function nt(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,name:null==e.name?void 0:e.name,description:null==e.description?void 0:e.description,category:null==e.category?void 0:e.category}}(e)}function ot(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(nt)}}(e)}function st(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,name:null==e.name?void 0:e.name,description:null==e.description?void 0:e.description}}(e)}function rt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(st)}}(e)}function at(e){return function(e){if(null==e)return e;return{version:null==e.version?void 0:e.version,widgetType:null==e.widgetType?void 0:e.widgetType,type:null==e.type?void 0:e.type,content:null==e.content?void 0:e.content,contentItems:null==e.contentItems?void 0:e.contentItems,metadata:null==e.metadata?void 0:e.metadata}}(e)}function dt(e){return function(e){if(null==e)return e;return{version:null==e.version?void 0:e.version,widgetType:null==e.widgetType?void 0:e.widgetType,type:null==e.type?void 0:e.type,theme:null==e.theme?void 0:e.theme,componentGroups:null==e.componentGroups?void 0:e.componentGroups,metadata:null==e.metadata?void 0:e.metadata}}(e)}function ct(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,name:null==e.name?void 0:e.name,version:null==e.version?void 0:e.version,type:null==e.type?void 0:e.type,componentGroups:null==e.componentGroups?void 0:e.componentGroups,defaults:null==e.defaults?void 0:e.defaults}}(e)}function lt(e){return function(e){if(null==e)return e;return{compositionId:null==e.compositionId?void 0:e.compositionId,widgetId:null==e.widgetId?void 0:e.widgetId,version:null==e.version?void 0:e.version,previewUrl:null==e.previewUrl?void 0:e.previewUrl}}(e)}function ut(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(We)}}(e)}function ht(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,error:null==e.error?void 0:e.error}}(e)}function gt(e){return function(e){if(null==e)return e;return{compositions:null==e.compositions?void 0:e.compositions.map(Ae),errors:null==e.errors?void 0:e.errors.map(ht)}}(e)}function pt(e){return function(e){if(null==e)return e;return{presets:null==e.presets?void 0:e.presets}}(e)}function mt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:pt(e.data)}}(e)}function ft(e){return function(e){if(null==e)return e;return{name:null==e.name?void 0:e.name,nativeName:null==e.nativeName?void 0:e.nativeName,region:null==e.region?void 0:e.region,isPreselected:null==e.isPreselected?void 0:e.isPreselected}}(e)}function vt(e){return function(e){if(null==e)return e;return{languages:null==e.languages?void 0:te(e.languages,ft),preselected:null==e.preselected?void 0:e.preselected}}(e)}function yt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:vt(e.data)}}(e)}function wt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ge(e.data)}}(e)}function bt(e){return function(e){if(null==e)return e;return{languageCode:null==e.languageCode?void 0:e.languageCode,views:null==e.views?void 0:e.views,percentage:null==e.percentage?void 0:e.percentage}}(e)}function It(e){return function(e){if(null==e)return e;return{languageCode:null==e.languageCode?void 0:e.languageCode,views:null==e.views?void 0:e.views}}(e)}function Tt(e){return function(e){if(null==e)return e;return{totalViews:null==e.totalViews?void 0:e.totalViews,languageBreakdown:null==e.languageBreakdown?void 0:e.languageBreakdown.map(bt),topPerformingLanguages:null==e.topPerformingLanguages?void 0:e.topPerformingLanguages.map(It),completionStatus:null==e.completionStatus?void 0:e.completionStatus}}(e)}function kt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Tt(e.data)}}(e)}function St(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,name:null==e.name?void 0:e.name,rootLanguage:null==e.rootLanguage?void 0:e.rootLanguage,rootCompositionId:null==e.rootCompositionId?void 0:e.rootCompositionId,languageCompositions:null==e.languageCompositions?void 0:e.languageCompositions,status:null==e.status?void 0:e.status}}(e)}function Et(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:St(e.data)}}(e)}function Ct(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(ge),count:null==e.count?void 0:e.count}}(e)}function At(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,composition_id:null==e.composition_id?void 0:e.composition_id,name:null==e.name?void 0:e.name,traffic_percentage:null==e.traffic_percentage?void 0:e.traffic_percentage}}(e)}function Rt(e){return function(e){if(null==e)return e;return{id:null==e.id?void 0:e.id,version:null==e.version?void 0:e.version,commitSha:null==e.commitSha?void 0:e.commitSha,commitTitle:null==e.commitTitle?void 0:e.commitTitle,artifactUrl:null==e.artifactUrl?void 0:e.artifactUrl,publishedAt:null==e.publishedAt?void 0:new Date(e.publishedAt),isPublished:null==e.isPublished?void 0:e.isPublished,prompt:null==e.prompt?void 0:e.prompt,publishedBy:null==e.publishedBy?void 0:e.publishedBy}}(e)}function xt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(Rt)}}(e)}function Dt(e){return function(e){if(null==e)return e;return{page:null==e.page?void 0:e.page,size:null==e.size?void 0:e.size,total:null==e.total?void 0:e.total,limit:null==e.limit?void 0:e.limit,offset:null==e.offset?void 0:e.offset,hasNextPage:null==e.hasNextPage?void 0:e.hasNextPage,hasPreviousPage:null==e.hasPreviousPage?void 0:e.hasPreviousPage}}(e)}function Mt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(Ye),meta:null==e.meta?void 0:Dt(e.meta)}}(e)}function Lt(e){return function(e){if(null==e)return e;return{widgets:null==e.widgets?void 0:e.widgets.map(Ye),errors:null==e.errors?void 0:e.errors.map(ht)}}(e)}function Wt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ae(e.data)}}(e)}function Ot(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ue(e.data)}}(e)}function _t(e){return function(e){if(null==e)return e;return{count:null==e.count?void 0:e.count,workspace_type:null==e.workspace_type?void 0:e.workspace_type}}(e)}function Pt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data.map(se),meta:null==e.meta?void 0:_t(e.meta)}}(e)}function zt(e){return function(e){if(null==e)return e;return{id:e.id,compositionId:e.compositionId,year:e.year,month:e.month,startDate:new Date(e.startDate),endDate:new Date(e.endDate),totalViews:e.totalViews,uniqueViews:e.uniqueViews,totalInteractions:e.totalInteractions,uniqueInteractions:e.uniqueInteractions,totalSessionTime:e.totalSessionTime,averageSessionTime:e.averageSessionTime,bounceRate:e.bounceRate,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt)}}(e)}function qt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data}}(e)}function Ut(e){return function(e){if(null==e)return e;return{widgetId:null==e.widgetId?void 0:e.widgetId,version:null==e.version?void 0:e.version,commitTitle:null==e.commitTitle?void 0:e.commitTitle}}(e)}function Bt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ut(e.data)}}(e)}function $t(e){return function(e){if(null==e)return e;return{email:e.email}}(e,!1)}function Ft(e){return function(e){if(null==e)return e;return{valid:null==e.valid?void 0:e.valid,errors:null==e.errors?void 0:e.errors,warnings:null==e.warnings?void 0:e.warnings}}(e)}function Nt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,validationResult:null==e.validationResult?void 0:Ft(e.validationResult),compositionUpdated:null==e.compositionUpdated?void 0:e.compositionUpdated,realtimeUpdateSent:null==e.realtimeUpdateSent?void 0:e.realtimeUpdateSent}}(e)}function jt(e){return function(e){if(null==e)return e;return{widgetId:null==e.widgetId?void 0:e.widgetId,version:null==e.version?void 0:e.version,artifactUrl:null==e.artifactUrl?void 0:e.artifactUrl,commitSha:null==e.commitSha?void 0:e.commitSha,commitTitle:null==e.commitTitle?void 0:e.commitTitle}}(e)}function Ht(e){return function(e){if(null==e)return e;return{data:null==e.data?void 0:jt(e.data),message:null==e.message?void 0:e.message}}(e)}function Vt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ht(e.data)}}(e)}function Kt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:se(e.data),message:null==e.message?void 0:e.message}}(e)}function Gt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:se(e.data),message:null==e.message?void 0:e.message}}(e)}function Yt(e){return function(e){if(null==e)return e;return{limit:null==e.limit?void 0:e.limit,hasNextPage:null==e.hasNextPage?void 0:e.hasNextPage,hasPreviousPage:null==e.hasPreviousPage?void 0:e.hasPreviousPage,nextCursor:null==e.nextCursor?void 0:e.nextCursor,previousCursor:null==e.previousCursor?void 0:e.previousCursor}}(e)}function Qt(e){return function(e){if(null==e)return e;return{pagination:null==e.pagination?void 0:Yt(e.pagination)}}(e)}function Jt(e){return function(e){if(null==e)return e;return{success:e.success,message:null==e.message?void 0:e.message,data:e.data,meta:null==e.meta?void 0:Qt(e.meta)}}(e)}function Xt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,message:null==e.message?void 0:e.message}}(e)}function Zt(e){return function(e){if(null==e)return e;return{experiment_id:e.experiment_id,variant_id:e.variant_id,conversion_type:e.conversion_type,timestamp:null==e.timestamp?void 0:e.timestamp.toISOString(),user_id:e.user_id}}(e,!1)}function ei(e){return function(e){if(null==e)return e;return{event_type:e.event_type,data:Zt(e.data)}}(e,!1)}function ti(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,message:null==e.message?void 0:e.message,count:null==e.count?void 0:e.count}}(e)}function ii(e){return function(e){if(null==e)return e;return{experiment_id:e.experiment_id,variant_id:e.variant_id,conversion_type:e.conversion_type,timestamp:null==e.timestamp?void 0:e.timestamp.toISOString()}}(e,!1)}function ni(e){return function(e){if(null==e)return e;return{event_type:e.event_type,data:ii(e.data)}}(e,!1)}function oi(e){return function(e){if(null==e)return e;return{events:e.events.map(ni)}}(e,!1)}function si(e){return function(e){if(null==e)return e;return{name:e.name,description:e.description,status:e.status,successMetrics:e.successMetrics,primaryMetric:e.primaryMetric,confidenceLevel:e.confidenceLevel,minSampleSize:e.minSampleSize,autoGraduate:e.autoGraduate,graduationThreshold:e.graduationThreshold,startDate:null==e.startDate?void 0:e.startDate.toISOString(),endDate:null==e.endDate?void 0:e.endDate.toISOString(),durationDays:e.durationDays}}(e,!1)}function ri(e){return function(e){if(null==e)return e;return{token:e.token,email:e.email}}(e,!1)}function ai(e){return function(e){if(null==e)return e;return{repositoryId:null==e.repositoryId?void 0:e.repositoryId}}(e)}function di(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ai(e.data),meta:null==e.meta?void 0:e.meta}}(e)}function ci(e){return function(e){if(null==e)return e;return{thumbnailUrl:null==e.thumbnailUrl?void 0:e.thumbnailUrl}}(e)}function li(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ci(e.data)}}(e)}function ui(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,message:null==e.message?void 0:e.message}}(e)}function hi(e){return function(e){if(null==e)return e;return{valid:null==e.valid?void 0:e.valid,errors:null==e.errors?void 0:e.errors,warnings:null==e.warnings?void 0:e.warnings,sanitizedContent:null==e.sanitizedContent?void 0:e.sanitizedContent}}(e)}function gi(e){return function(e){if(null==e)return e;return{valid:null==e.valid?void 0:e.valid,reason:null==e.reason?void 0:e.reason,message:null==e.message?void 0:e.message}}(e)}function pi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:gi(e.data)}}(e)}function mi(e){return function(e){if(null==e)return e;return{valid:null==e.valid?void 0:e.valid,tokenType:null==e.tokenType?void 0:e.tokenType,scopes:null==e.scopes?void 0:e.scopes,userId:null==e.userId?void 0:e.userId,expiresAt:null==e.expiresAt?void 0:new Date(e.expiresAt)}}(e)}function fi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:mi(e.data)}}(e)}function vi(e){return function(e){if(null==e)return e;return{test_id:null==e.test_id?void 0:e.test_id,test_name:null==e.test_name?void 0:e.test_name,status:null==e.status?void 0:e.status,impact:null==e.impact?void 0:e.impact}}(e)}function yi(e){return function(e){if(null==e)return e;return{test_id:null==e.test_id?void 0:e.test_id,test_name:null==e.test_name?void 0:e.test_name,status:null==e.status?void 0:e.status,reason:null==e.reason?void 0:e.reason}}(e)}function wi(e){return function(e){if(null==e)return e;return{can_delete:null==e.can_delete?void 0:e.can_delete,blockers:null==e.blockers?void 0:e.blockers.map(yi),warnings:null==e.warnings?void 0:e.warnings.map(vi)}}(e)}function bi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:wi(e.data)}}(e)}function Ii(e){return function(e){if(null==e)return e;return{variant:null==e.variant?void 0:e.variant,metric:null==e.metric?void 0:e.metric,reason:null==e.reason?void 0:e.reason}}(e)}function Ti(e){return function(e){if(null==e)return e;return{is_valid:null==e.is_valid?void 0:e.is_valid,issues:null==e.issues?void 0:e.issues.map(Ii),recommendations:null==e.recommendations?void 0:e.recommendations}}(e)}function ki(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ti(e.data)}}(e)}function Si(e){return function(e){if(null==e)return e;return{composition_id:e.composition_id,name:e.name}}(e,!1)}function Ei(e){return function(e){if(null==e)return e;return{variants:e.variants.map(Si),success_metrics:e.success_metrics}}(e,!1)}function Ci(e){return function(e){if(null==e)return e;return{can_delete:null==e.can_delete?void 0:e.can_delete,affected_compositions:null==e.affected_compositions?void 0:e.affected_compositions,blockers:null==e.blockers?void 0:e.blockers.map(yi),warnings:null==e.warnings?void 0:e.warnings.map(vi)}}(e)}function Ai(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ci(e.data)}}(e)}function Ri(e){return function(e){if(null==e)return e;return{id:e.id,compositionId:e.compositionId,year:e.year,weekNumber:e.weekNumber,startDate:new Date(e.startDate),endDate:new Date(e.endDate),totalViews:e.totalViews,uniqueViews:e.uniqueViews,totalInteractions:e.totalInteractions,uniqueInteractions:e.uniqueInteractions,totalSessionTime:e.totalSessionTime,averageSessionTime:e.averageSessionTime,bounceRate:e.bounceRate,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),updatedAt:null==e.updatedAt?void 0:new Date(e.updatedAt)}}(e)}var xi="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};class Di extends Y{assignVariantRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling assignVariant().');if(null==e.assignVariantRequest)throw new X("assignVariantRequest",'Required parameter "assignVariantRequest" was null or undefined when calling assignVariant().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/ab-tests/{id}/assign".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.assignVariantRequest,o=s,null==o?o:{user_id:o.user_id,session_id:o.session_id})},t);var o,s;return new ie(n,(e=>oe(e)))}))}assignVariant(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.assignVariantRaw(e,t);return yield i.value()}))}checkWorkspaceABTestAutoStopRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling checkWorkspaceABTestAutoStop().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling checkWorkspaceABTestAutoStop().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}/auto-stop-check".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>Ce(e)))}))}checkWorkspaceABTestAutoStop(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.checkWorkspaceABTestAutoStopRaw(e,t);return yield i.value()}))}createABTestAssignmentRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.createABTestAssignmentRequest)throw new X("createABTestAssignmentRequest",'Required parameter "createABTestAssignmentRequest" was null or undefined when calling createABTestAssignment().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/ab-tests/assignments",method:"POST",headers:i,query:{},body:(s=e.createABTestAssignmentRequest,o=s,null==o?o:{experiment_id:o.experiment_id,variant_id:o.variant_id,user_id:o.user_id,session_id:o.session_id,device_type:o.device_type,user_agent:o.user_agent,ip_address:o.ip_address,country_code:o.country_code})},t);var o,s;return new ie(n,(e=>Oe(e)))}))}createABTestAssignment(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.createABTestAssignmentRaw(e,t);return yield i.value()}))}createWorkspaceABTestRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling createWorkspaceABTest().');if(null==e.createABTestRequest)throw new X("createABTestRequest",'Required parameter "createABTestRequest" was null or undefined when calling createWorkspaceABTest().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:Pe(e.createABTestRequest)},t);return new ie(n,(e=>je(e)))}))}createWorkspaceABTest(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.createWorkspaceABTestRaw(e,t);return yield i.value()}))}deleteWorkspaceABTestRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling deleteWorkspaceABTest().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling deleteWorkspaceABTest().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"DELETE",headers:i,query:{}},t);return new ie(n,(e=>Ve(e)))}))}deleteWorkspaceABTest(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.deleteWorkspaceABTestRaw(e,t);return yield i.value()}))}getABTestConfigRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getABTestConfig().');const i=yield this.request({path:"/ab-tests/{id}/config".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:{},query:{}},t);return new ie(i,(e=>et(e)))}))}getABTestConfig(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.getABTestConfigRaw(e,t);return yield i.value()}))}getAvailableMetricsRaw(e){return xi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("apiKeyAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/metrics/available",method:"GET",headers:t,query:{}},e);return new ie(i,(e=>ot(e)))}))}getAvailableMetrics(e){return xi(this,void 0,void 0,(function*(){const t=yield this.getAvailableMetricsRaw(e);return yield t.value()}))}getAvailableSuccessMetricsRaw(e){return xi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("apiKeyAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/ab-tests/metrics/available",method:"GET",headers:t,query:{}},e);return new ie(i,(e=>rt(e)))}))}getAvailableSuccessMetrics(e){return xi(this,void 0,void 0,(function*(){const t=yield this.getAvailableSuccessMetricsRaw(e);return yield t.value()}))}getVariantConfigRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getVariantConfig().');const i=yield this.request({path:"/ab-tests/variants/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:{},query:{}},t);return new ie(i,(e=>At(e)))}))}getVariantConfig(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.getVariantConfigRaw(e,t);return yield i.value()}))}getWorkspaceABTestRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTest().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling getWorkspaceABTest().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>je(e)))}))}getWorkspaceABTest(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestRaw(e,t);return yield i.value()}))}getWorkspaceABTestDiagnosisRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTestDiagnosis().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling getWorkspaceABTestDiagnosis().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}/diagnosis".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>Wt(e)))}))}getWorkspaceABTestDiagnosis(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestDiagnosisRaw(e,t);return yield i.value()}))}getWorkspaceABTestStatisticsRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTestStatistics().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling getWorkspaceABTestStatistics().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}/statistics".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>Ot(e)))}))}getWorkspaceABTestStatistics(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestStatisticsRaw(e,t);return yield i.value()}))}listWorkspaceABTestsRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling listWorkspaceABTests().');const i={};null!=e.status&&(i.status=e.status);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/workspaces/{workspaceId}/ab-tests".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>Pt(e)))}))}listWorkspaceABTests(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.listWorkspaceABTestsRaw(e,t);return yield i.value()}))}pauseWorkspaceABTestRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling pauseWorkspaceABTest().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling pauseWorkspaceABTest().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}/pause".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"POST",headers:i,query:{}},t);return new ie(n,(e=>je(e)))}))}pauseWorkspaceABTest(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.pauseWorkspaceABTestRaw(e,t);return yield i.value()}))}setWorkspaceABTestDurationRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling setWorkspaceABTestDuration().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling setWorkspaceABTestDuration().');if(null==e.setWorkspaceABTestDurationRequest)throw new X("setWorkspaceABTestDurationRequest",'Required parameter "setWorkspaceABTestDurationRequest" was null or undefined when calling setWorkspaceABTestDuration().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}/duration".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"PUT",headers:i,query:{},body:(s=e.setWorkspaceABTestDurationRequest,o=s,null==o?o:{duration_days:o.duration_days})},t);var o,s;return new ie(n,(e=>Kt(e)))}))}setWorkspaceABTestDuration(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.setWorkspaceABTestDurationRaw(e,t);return yield i.value()}))}startWorkspaceABTestRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling startWorkspaceABTest().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling startWorkspaceABTest().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}/start".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"POST",headers:i,query:{}},t);return new ie(n,(e=>je(e)))}))}startWorkspaceABTest(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.startWorkspaceABTestRaw(e,t);return yield i.value()}))}stopWorkspaceABTestRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling stopWorkspaceABTest().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling stopWorkspaceABTest().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}/stop".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"POST",headers:i,query:{},body:(s=e.stopWorkspaceABTestRequest,o=s,null==o?o:{winning_variant_id:o.winning_variant_id,winningVariantId:o.winningVariantId})},t);var o,s;return new ie(n,(e=>Gt(e)))}))}stopWorkspaceABTest(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.stopWorkspaceABTestRaw(e,t);return yield i.value()}))}trackABTestEventRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.trackABTestEventRequest)throw new X("trackABTestEventRequest",'Required parameter "trackABTestEventRequest" was null or undefined when calling trackABTestEvent().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/ab-tests/analytics/events",method:"POST",headers:i,query:{},body:ei(e.trackABTestEventRequest)},t);return new ie(n,(e=>Xt(e)))}))}trackABTestEvent(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.trackABTestEventRaw(e,t);return yield i.value()}))}trackBulkABTestEventsRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.trackBulkABTestEventsRequest)throw new X("trackBulkABTestEventsRequest",'Required parameter "trackBulkABTestEventsRequest" was null or undefined when calling trackBulkABTestEvents().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/ab-tests/analytics/bulk",method:"POST",headers:i,query:{},body:oi(e.trackBulkABTestEventsRequest)},t);return new ie(n,(e=>ti(e)))}))}trackBulkABTestEvents(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.trackBulkABTestEventsRaw(e,t);return yield i.value()}))}updateWorkspaceABTestRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling updateWorkspaceABTest().');if(null==e.testId)throw new X("testId",'Required parameter "testId" was null or undefined when calling updateWorkspaceABTest().');if(null==e.updateABTestRequest)throw new X("updateABTestRequest",'Required parameter "updateABTestRequest" was null or undefined when calling updateWorkspaceABTest().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/{testId}".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"PUT",headers:i,query:{},body:si(e.updateABTestRequest)},t);return new ie(n,(e=>je(e)))}))}updateWorkspaceABTest(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.updateWorkspaceABTestRaw(e,t);return yield i.value()}))}validateWorkspaceCompositionDeletionRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceCompositionDeletion().');if(null==e.validateWorkspaceCompositionDeletionRequest)throw new X("validateWorkspaceCompositionDeletionRequest",'Required parameter "validateWorkspaceCompositionDeletionRequest" was null or undefined when calling validateWorkspaceCompositionDeletion().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/validate-composition-deletion".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:(s=e.validateWorkspaceCompositionDeletionRequest,o=s,null==o?o:{composition_ids:o.composition_ids})},t);var o,s;return new ie(n,(e=>bi(e)))}))}validateWorkspaceCompositionDeletion(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceCompositionDeletionRaw(e,t);return yield i.value()}))}validateWorkspaceGoalTrackingRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceGoalTracking().');if(null==e.validateWorkspaceGoalTrackingRequest)throw new X("validateWorkspaceGoalTrackingRequest",'Required parameter "validateWorkspaceGoalTrackingRequest" was null or undefined when calling validateWorkspaceGoalTracking().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/validate-goal-tracking".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:Ei(e.validateWorkspaceGoalTrackingRequest)},t);return new ie(n,(e=>ki(e)))}))}validateWorkspaceGoalTracking(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceGoalTrackingRaw(e,t);return yield i.value()}))}validateWorkspaceWidgetDeletionRaw(e,t){return xi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new X("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceWidgetDeletion().');if(null==e.validateWorkspaceWidgetDeletionRequest)throw new X("validateWorkspaceWidgetDeletionRequest",'Required parameter "validateWorkspaceWidgetDeletionRequest" was null or undefined when calling validateWorkspaceWidgetDeletion().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/workspaces/{workspaceId}/ab-tests/validate-widget-deletion".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:(s=e.validateWorkspaceWidgetDeletionRequest,o=s,null==o?o:{widget_id:o.widget_id})},t);var o,s;return new ie(n,(e=>Ai(e)))}))}validateWorkspaceWidgetDeletion(e,t){return xi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceWidgetDeletionRaw(e,t);return yield i.value()}))}}var Mi="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};class Li extends Y{analyticsEventsBulkPostRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.analyticsEventsBulkPostRequest)throw new X("analyticsEventsBulkPostRequest",'Required parameter "analyticsEventsBulkPostRequest" was null or undefined when calling analyticsEventsBulkPost().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/analytics/events/bulk",method:"POST",headers:i,query:{},body:Te(e.analyticsEventsBulkPostRequest)},t);return new ie(n,(e=>e.map(ye)))}))}analyticsEventsBulkPost(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.analyticsEventsBulkPostRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsDailyGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsDailyGet().');const i={};null!=e.startDate&&(i.start_date=e.startDate.toISOString().substring(0,10)),null!=e.endDate&&(i.end_date=e.endDate.toISOString().substring(0,10)),null!=e.limit&&(i.limit=e.limit),null!=e.offset&&(i.offset=e.offset);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/daily".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>e.map(He)))}))}compositionsIdAnalyticsDailyGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsDailyGetRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsDashboardGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsDashboardGet().');const i={};null!=e.startDate&&(i.start_date=e.startDate.toISOString().substring(0,10)),null!=e.endDate&&(i.end_date=e.endDate.toISOString().substring(0,10)),null!=e.includeEvents&&(i.include_events=e.includeEvents);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/dashboard".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>be(e)))}))}compositionsIdAnalyticsDashboardGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsDashboardGetRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsDevicesGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsDevicesGet().');const i={};null!=e.startDate&&(i.start_date=e.startDate.toISOString().substring(0,10)),null!=e.endDate&&(i.end_date=e.endDate.toISOString().substring(0,10)),null!=e.deviceType&&(i.device_type=e.deviceType),null!=e.limit&&(i.limit=e.limit),null!=e.offset&&(i.offset=e.offset);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/devices".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>e.map(ve)))}))}compositionsIdAnalyticsDevicesGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsDevicesGetRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsEventsGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsEventsGet().');const i={};null!=e.startDate&&(i.start_date=e.startDate.toISOString().substring(0,10)),null!=e.endDate&&(i.end_date=e.endDate.toISOString().substring(0,10)),null!=e.eventType&&(i.event_type=e.eventType),null!=e.userId&&(i.user_id=e.userId),null!=e.sessionId&&(i.session_id=e.sessionId),null!=e.limit&&(i.limit=e.limit),null!=e.offset&&(i.offset=e.offset);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/events".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>e.map(ye)))}))}compositionsIdAnalyticsEventsGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsEventsGetRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsEventsPostRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsEventsPost().');if(null==e.newAnalyticsEvent)throw new X("newAnalyticsEvent",'Required parameter "newAnalyticsEvent" was null or undefined when calling compositionsIdAnalyticsEventsPost().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/analytics/events".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:Ie(e.newAnalyticsEvent)},t);return new ie(n,(e=>ye(e)))}))}compositionsIdAnalyticsEventsPost(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsEventsPostRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsGeographyGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsGeographyGet().');const i={};null!=e.startDate&&(i.start_date=e.startDate.toISOString().substring(0,10)),null!=e.endDate&&(i.end_date=e.endDate.toISOString().substring(0,10)),null!=e.country&&(i.country=e.country),null!=e.region&&(i.region=e.region),null!=e.city&&(i.city=e.city),null!=e.limit&&(i.limit=e.limit),null!=e.offset&&(i.offset=e.offset);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/geography".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>e.map(me)))}))}compositionsIdAnalyticsGeographyGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsGeographyGetRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsMonthlyGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsMonthlyGet().');const i={};null!=e.month&&(i.month=e.month),null!=e.year&&(i.year=e.year),null!=e.limit&&(i.limit=e.limit),null!=e.offset&&(i.offset=e.offset);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/monthly".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>e.map(zt)))}))}compositionsIdAnalyticsMonthlyGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsMonthlyGetRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsReferrersGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsReferrersGet().');const i={};null!=e.startDate&&(i.start_date=e.startDate.toISOString().substring(0,10)),null!=e.endDate&&(i.end_date=e.endDate.toISOString().substring(0,10)),null!=e.source&&(i.source=e.source),null!=e.limit&&(i.limit=e.limit),null!=e.offset&&(i.offset=e.offset);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/referrers".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>e.map(we)))}))}compositionsIdAnalyticsReferrersGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsReferrersGetRaw(e,t);return yield i.value()}))}compositionsIdAnalyticsWeeklyGetRaw(e,t){return Mi(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling compositionsIdAnalyticsWeeklyGet().');const i={};null!=e.weekNumber&&(i.week_number=e.weekNumber),null!=e.year&&(i.year=e.year),null!=e.limit&&(i.limit=e.limit),null!=e.offset&&(i.offset=e.offset);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/analytics/weekly".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>e.map(Ri)))}))}compositionsIdAnalyticsWeeklyGet(e,t){return Mi(this,void 0,void 0,(function*(){const i=yield this.compositionsIdAnalyticsWeeklyGetRaw(e,t);return yield i.value()}))}flushAxiomEventsRaw(e){return Mi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("bearerAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/analytics/axiom/flush",method:"POST",headers:t,query:{}},e);return new ie(i,(e=>Jt(e)))}))}flushAxiomEvents(e){return Mi(this,void 0,void 0,(function*(){const t=yield this.flushAxiomEventsRaw(e);return yield t.value()}))}getAxiomStatusRaw(e){return Mi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("bearerAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/analytics/axiom/status",method:"GET",headers:t,query:{}},e);return new ie(i,(e=>Jt(e)))}))}getAxiomStatus(e){return Mi(this,void 0,void 0,(function*(){const t=yield this.getAxiomStatusRaw(e);return yield t.value()}))}}var Wi="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};class Oi extends Y{completeSignupRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.completeSignupRequest)throw new X("completeSignupRequest",'Required parameter "completeSignupRequest" was null or undefined when calling completeSignup().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/complete-signup",method:"POST",headers:i,query:{},body:(s=e.completeSignupRequest,o=s,null==o?o:{userId:o.userId,email:o.email,role:o.role,plan:o.plan,token:o.token})},t);var o,s;return new ne(n)}))}completeSignup(e,t){return Wi(this,void 0,void 0,(function*(){yield this.completeSignupRaw(e,t)}))}confirmEmailRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.updateEmailRequest)throw new X("updateEmailRequest",'Required parameter "updateEmailRequest" was null or undefined when calling confirmEmail().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/confirm-email",method:"POST",headers:i,query:{},body:ri(e.updateEmailRequest)},t);return new ne(n)}))}confirmEmail(e,t){return Wi(this,void 0,void 0,(function*(){yield this.confirmEmailRaw(e,t)}))}consumeOAuthSessionBridgeRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.bridgeId)throw new X("bridgeId",'Required parameter "bridgeId" was null or undefined when calling consumeOAuthSessionBridge().');const i=yield this.request({path:"/auth/oauth-session/{bridgeId}".replace("{bridgeId}",encodeURIComponent(String(e.bridgeId))),method:"GET",headers:{},query:{}},t);return new ne(i)}))}consumeOAuthSessionBridge(e,t){return Wi(this,void 0,void 0,(function*(){yield this.consumeOAuthSessionBridgeRaw(e,t)}))}deleteAccountRaw(e,t){return Wi(this,void 0,void 0,(function*(){const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/auth/delete-account",method:"POST",headers:i,query:{},body:(s=e.deleteAccountRequest,o=s,null==o?o:{password:o.password})},t);var o,s;return new ne(n)}))}deleteAccount(){return Wi(this,arguments,void 0,(function*(e={},t){yield this.deleteAccountRaw(e,t)}))}getSessionRaw(e){return Wi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("apiKeyAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/auth/session",method:"GET",headers:t,query:{}},e);return new ne(i)}))}getSession(e){return Wi(this,void 0,void 0,(function*(){yield this.getSessionRaw(e)}))}getUserMetadataRaw(e){return Wi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("apiKeyAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/auth/get-metadata",method:"GET",headers:t,query:{}},e);return new ne(i)}))}getUserMetadata(e){return Wi(this,void 0,void 0,(function*(){yield this.getUserMetadataRaw(e)}))}initiateOAuthRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.provider)throw new X("provider",'Required parameter "provider" was null or undefined when calling initiateOAuth().');const i={};null!=e.redirectTo&&(i.redirectTo=e.redirectTo),null!=e.role&&(i.role=e.role),null!=e.plan&&(i.plan=e.plan);const n=yield this.request({path:"/auth/oauth/{provider}".replace("{provider}",encodeURIComponent(String(e.provider))),method:"GET",headers:{},query:i},t);return new ne(n)}))}initiateOAuth(e,t){return Wi(this,void 0,void 0,(function*(){yield this.initiateOAuthRaw(e,t)}))}loginUserRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.loginUserRequest)throw new X("loginUserRequest",'Required parameter "loginUserRequest" was null or undefined when calling loginUser().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/login",method:"POST",headers:i,query:{},body:(s=e.loginUserRequest,o=s,null==o?o:{email:o.email,password:o.password})},t);var o,s;return new ie(n,(e=>qt(e)))}))}loginUser(e,t){return Wi(this,void 0,void 0,(function*(){const i=yield this.loginUserRaw(e,t);return yield i.value()}))}logoutUserRaw(e){return Wi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("apiKeyAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/auth/logout",method:"POST",headers:t,query:{}},e);return new ne(i)}))}logoutUser(e){return Wi(this,void 0,void 0,(function*(){yield this.logoutUserRaw(e)}))}refreshSessionRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.refreshSessionRequest)throw new X("refreshSessionRequest",'Required parameter "refreshSessionRequest" was null or undefined when calling refreshSession().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/refresh",method:"POST",headers:i,query:{},body:(s=e.refreshSessionRequest,o=s,null==o?o:{refresh_token:o.refresh_token})},t);var o,s;return new ne(n)}))}refreshSession(e,t){return Wi(this,void 0,void 0,(function*(){yield this.refreshSessionRaw(e,t)}))}resendConfirmationRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.resetPasswordRequest)throw new X("resetPasswordRequest",'Required parameter "resetPasswordRequest" was null or undefined when calling resendConfirmation().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/resend-confirmation",method:"POST",headers:i,query:{},body:$t(e.resetPasswordRequest)},t);return new ne(n)}))}resendConfirmation(e,t){return Wi(this,void 0,void 0,(function*(){yield this.resendConfirmationRaw(e,t)}))}resetPasswordRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.resetPasswordRequest)throw new X("resetPasswordRequest",'Required parameter "resetPasswordRequest" was null or undefined when calling resetPassword().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/reset-password",method:"POST",headers:i,query:{},body:$t(e.resetPasswordRequest)},t);return new ne(n)}))}resetPassword(e,t){return Wi(this,void 0,void 0,(function*(){yield this.resetPasswordRaw(e,t)}))}signupUserRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.signupUserRequest)throw new X("signupUserRequest",'Required parameter "signupUserRequest" was null or undefined when calling signupUser().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/signup",method:"POST",headers:i,query:{},body:(s=e.signupUserRequest,o=s,null==o?o:{email:o.email,password:o.password,role:o.role,plan:o.plan,inviteCode:o.inviteCode,name:o.name,returnTo:o.returnTo})},t);var o,s;return new ne(n)}))}signupUser(e,t){return Wi(this,void 0,void 0,(function*(){yield this.signupUserRaw(e,t)}))}signupWithInvitationRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.signupWithInvitationRequest)throw new X("signupWithInvitationRequest",'Required parameter "signupWithInvitationRequest" was null or undefined when calling signupWithInvitation().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/signup-with-invitation",method:"POST",headers:i,query:{},body:(s=e.signupWithInvitationRequest,o=s,null==o?o:{email:o.email,password:o.password,role:o.role,plan:o.plan,invitationId:o.invitationId,organizationId:o.organizationId})},t);var o,s;return new ne(n)}))}signupWithInvitation(e,t){return Wi(this,void 0,void 0,(function*(){yield this.signupWithInvitationRaw(e,t)}))}updateEmailRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.updateEmailRequest)throw new X("updateEmailRequest",'Required parameter "updateEmailRequest" was null or undefined when calling updateEmail().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/update-email",method:"POST",headers:i,query:{},body:ri(e.updateEmailRequest)},t);return new ne(n)}))}updateEmail(e,t){return Wi(this,void 0,void 0,(function*(){yield this.updateEmailRaw(e,t)}))}updateNameRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.updateNameRequest)throw new X("updateNameRequest",'Required parameter "updateNameRequest" was null or undefined when calling updateName().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/update-name",method:"POST",headers:i,query:{},body:(s=e.updateNameRequest,o=s,null==o?o:{token:o.token,name:o.name})},t);var o,s;return new ne(n)}))}updateName(e,t){return Wi(this,void 0,void 0,(function*(){yield this.updateNameRaw(e,t)}))}updatePasswordRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.updatePasswordRequest)throw new X("updatePasswordRequest",'Required parameter "updatePasswordRequest" was null or undefined when calling updatePassword().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/auth/update-password",method:"POST",headers:i,query:{},body:(s=e.updatePasswordRequest,o=s,null==o?o:{token:o.token,email:o.email,password:o.password})},t);var o,s;return new ne(n)}))}updatePassword(e,t){return Wi(this,void 0,void 0,(function*(){yield this.updatePasswordRaw(e,t)}))}updateUserMetadataRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.updateUserMetadataRequest)throw new X("updateUserMetadataRequest",'Required parameter "updateUserMetadataRequest" was null or undefined when calling updateUserMetadata().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/auth/update-metadata",method:"POST",headers:i,query:{},body:(s=e.updateUserMetadataRequest,o=s,null==o?o:{metadata:o.metadata})},t);var o,s;return new ne(n)}))}updateUserMetadata(e,t){return Wi(this,void 0,void 0,(function*(){yield this.updateUserMetadataRaw(e,t)}))}validateInviteCodeRaw(e,t){return Wi(this,void 0,void 0,(function*(){if(null==e.code)throw new X("code",'Required parameter "code" was null or undefined when calling validateInviteCode().');const i={};null!=e.code&&(i.code=e.code);const n=yield this.request({path:"/auth/invite-code",method:"GET",headers:{},query:i},t);return new ie(n,(e=>pi(e)))}))}validateInviteCode(e,t){return Wi(this,void 0,void 0,(function*(){const i=yield this.validateInviteCodeRaw(e,t);return yield i.value()}))}}var _i="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};class Pi extends Y{checkCompositionAccessRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling checkCompositionAccess().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/access".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>ke(e)))}))}checkCompositionAccess(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.checkCompositionAccessRaw(e,t);return yield i.value()}))}createCompositionRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.newComposition)throw new X("newComposition",'Required parameter "newComposition" was null or undefined when calling createComposition().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions",method:"POST",headers:i,query:{},body:(s=e.newComposition,o=s,null==o?o:{name:o.name,widgetId:o.widgetId,creatorId:o.creatorId,content:o.content,status:o.status,embedSettings:o.embedSettings,design:o.design,databaseSchema:o.databaseSchema,projectId:o.projectId,managedUserId:o.managedUserId,managedUserExternalId:o.managedUserExternalId})},t);var o,s;return new ie(n,(e=>ze(e)))}))}createComposition(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.createCompositionRaw(e,t);return yield i.value()}))}createCompositionDatabaseRecordRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling createCompositionDatabaseRecord().');if(null==e.table)throw new X("table",'Required parameter "table" was null or undefined when calling createCompositionDatabaseRecord().');if(null==e.body)throw new X("body",'Required parameter "body" was null or undefined when calling createCompositionDatabaseRecord().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/database/{table}".replace("{id}",encodeURIComponent(String(e.id))).replace("{table}",encodeURIComponent(String(e.table))),method:"POST",headers:i,query:{},body:e.body},t);return new ne(n)}))}createCompositionDatabaseRecord(e,t){return _i(this,void 0,void 0,(function*(){yield this.createCompositionDatabaseRecordRaw(e,t)}))}deleteCompositionRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling deleteComposition().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"DELETE",headers:i,query:{}},t);return new ne(n)}))}deleteComposition(e,t){return _i(this,void 0,void 0,(function*(){yield this.deleteCompositionRaw(e,t)}))}deleteCompositionDatabaseRecordRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling deleteCompositionDatabaseRecord().');if(null==e.table)throw new X("table",'Required parameter "table" was null or undefined when calling deleteCompositionDatabaseRecord().');if(null==e.recordId)throw new X("recordId",'Required parameter "recordId" was null or undefined when calling deleteCompositionDatabaseRecord().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/database/{table}/{recordId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{table}",encodeURIComponent(String(e.table))).replace("{recordId}",encodeURIComponent(String(e.recordId))),method:"DELETE",headers:i,query:{}},t);return new ne(n)}))}deleteCompositionDatabaseRecord(e,t){return _i(this,void 0,void 0,(function*(){yield this.deleteCompositionDatabaseRecordRaw(e,t)}))}describeCompositionEntriesRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling describeCompositionEntries().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/entries".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>De(e)))}))}describeCompositionEntries(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.describeCompositionEntriesRaw(e,t);return yield i.value()}))}duplicateCompositionRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling duplicateComposition().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/duplicate".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.duplicateCompositionRequest,o=s,null==o?o:{name:o.name,includeDatabase:o.includeDatabase})},t);var o,s;return new ie(n,(e=>Ge(e)))}))}duplicateComposition(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.duplicateCompositionRaw(e,t);return yield i.value()}))}getAllCompositionsRaw(e,t){return _i(this,void 0,void 0,(function*(){const i={};null!=e.page&&(i.page=e.page),null!=e.size&&(i.size=e.size),null!=e.sort&&(i.sort=e.sort),null!=e.widgetId&&(i.widget_id=e.widgetId),null!=e.workspace&&(i.workspace=e.workspace),null!=e.projectFolder&&(i.project_folder=e.projectFolder),null!=e.status&&(i.status=e.status),null!=e.include&&(i.include=e.include),null!=e.managedUserId&&(i.managedUserId=e.managedUserId),null!=e.managedUserExternalId&&(i.managedUserExternalId=e.managedUserExternalId);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions",method:"GET",headers:n,query:i},t);return new ie(o,(e=>it(e)))}))}getAllCompositions(){return _i(this,arguments,void 0,(function*(e={},t){const i=yield this.getAllCompositionsRaw(e,t);return yield i.value()}))}getCompositionByIdRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionById().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>ze(e)))}))}getCompositionById(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionByIdRaw(e,t);return yield i.value()}))}getCompositionContentRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionContent().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/content".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n)}))}getCompositionContent(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionContentRaw(e,t);return yield i.value()}))}getCompositionContentSchemaRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionContentSchema().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/schema/content".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>at(e)))}))}getCompositionContentSchema(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionContentSchemaRaw(e,t);return yield i.value()}))}getCompositionDatabaseRecordRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionDatabaseRecord().');if(null==e.table)throw new X("table",'Required parameter "table" was null or undefined when calling getCompositionDatabaseRecord().');if(null==e.recordId)throw new X("recordId",'Required parameter "recordId" was null or undefined when calling getCompositionDatabaseRecord().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/database/{table}/{recordId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{table}",encodeURIComponent(String(e.table))).replace("{recordId}",encodeURIComponent(String(e.recordId))),method:"GET",headers:i,query:{}},t);return new ne(n)}))}getCompositionDatabaseRecord(e,t){return _i(this,void 0,void 0,(function*(){yield this.getCompositionDatabaseRecordRaw(e,t)}))}getCompositionDatabaseRecordsRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionDatabaseRecords().');if(null==e.table)throw new X("table",'Required parameter "table" was null or undefined when calling getCompositionDatabaseRecords().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/database/{table}".replace("{id}",encodeURIComponent(String(e.id))).replace("{table}",encodeURIComponent(String(e.table))),method:"GET",headers:i,query:{}},t);return new ne(n)}))}getCompositionDatabaseRecords(e,t){return _i(this,void 0,void 0,(function*(){yield this.getCompositionDatabaseRecordsRaw(e,t)}))}getCompositionDesignRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionDesign().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/design".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n)}))}getCompositionDesign(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionDesignRaw(e,t);return yield i.value()}))}getCompositionDesignSchemaRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionDesignSchema().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/schema/design".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>dt(e)))}))}getCompositionDesignSchema(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionDesignSchemaRaw(e,t);return yield i.value()}))}getCompositionEmbedSchemaRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionEmbedSchema().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/schema/embed".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>ct(e)))}))}getCompositionEmbedSchema(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionEmbedSchemaRaw(e,t);return yield i.value()}))}getCompositionEmbedSettingsRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionEmbedSettings().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/embed-settings".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n)}))}getCompositionEmbedSettings(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionEmbedSettingsRaw(e,t);return yield i.value()}))}getCompositionPreviewRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionPreview().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/preview".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>lt(e)))}))}getCompositionPreview(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionPreviewRaw(e,t);return yield i.value()}))}getCompositionVersionsRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getCompositionVersions().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/versions".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>ut(e)))}))}getCompositionVersions(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionVersionsRaw(e,t);return yield i.value()}))}getCompositionsBatchRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.getCompositionsBatchRequest)throw new X("getCompositionsBatchRequest",'Required parameter "getCompositionsBatchRequest" was null or undefined when calling getCompositionsBatch().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/batch",method:"POST",headers:i,query:{},body:(s=e.getCompositionsBatchRequest,o=s,null==o?o:{compositionIds:o.compositionIds})},t);var o,s;return new ie(n,(e=>gt(e)))}))}getCompositionsBatch(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.getCompositionsBatchRaw(e,t);return yield i.value()}))}readCompositionEntriesRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling readCompositionEntries().');if(null==e.table)throw new X("table",'Required parameter "table" was null or undefined when calling readCompositionEntries().');const i={};null!=e.groupBy&&(i.groupBy=e.groupBy),null!=e.rows&&(i.rows=e.rows);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/compositions/{id}/entries/{table}".replace("{id}",encodeURIComponent(String(e.id))).replace("{table}",encodeURIComponent(String(e.table))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>Le(e)))}))}readCompositionEntries(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.readCompositionEntriesRaw(e,t);return yield i.value()}))}setDynamicContentRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling setDynamicContent().');if(null==e.setDynamicContentRequest)throw new X("setDynamicContentRequest",'Required parameter "setDynamicContentRequest" was null or undefined when calling setDynamicContent().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/content".replace("{id}",encodeURIComponent(String(e.id))),method:"PUT",headers:i,query:{},body:(s=e.setDynamicContentRequest,o=s,null==o?o:{content:o.content,validate:o.validate,partial:o.partial,version:o.version,source:o.source})},t);var o,s;return new ie(n,(e=>Nt(e)))}))}setDynamicContent(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.setDynamicContentRaw(e,t);return yield i.value()}))}updateCompositionRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling updateComposition().');if(null==e.updateComposition)throw new X("updateComposition",'Required parameter "updateComposition" was null or undefined when calling updateComposition().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"PUT",headers:i,query:{},body:(s=e.updateComposition,o=s,null==o?o:{name:o.name,widgetId:o.widgetId,content:o.content,status:o.status,embedSettings:o.embedSettings,design:o.design,projectId:o.projectId})},t);var o,s;return new ie(n,(e=>ze(e)))}))}updateComposition(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.updateCompositionRaw(e,t);return yield i.value()}))}updateCompositionDatabaseRecordRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.table)throw new X("table",'Required parameter "table" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.recordId)throw new X("recordId",'Required parameter "recordId" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.body)throw new X("body",'Required parameter "body" was null or undefined when calling updateCompositionDatabaseRecord().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/database/{table}/{recordId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{table}",encodeURIComponent(String(e.table))).replace("{recordId}",encodeURIComponent(String(e.recordId))),method:"PUT",headers:i,query:{},body:e.body},t);return new ne(n)}))}updateCompositionDatabaseRecord(e,t){return _i(this,void 0,void 0,(function*(){yield this.updateCompositionDatabaseRecordRaw(e,t)}))}updateCompositionStatusRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling updateCompositionStatus().');if(null==e.updateCompositionStatusRequest)throw new X("updateCompositionStatusRequest",'Required parameter "updateCompositionStatusRequest" was null or undefined when calling updateCompositionStatus().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/status".replace("{id}",encodeURIComponent(String(e.id))),method:"PUT",headers:i,query:{},body:(s=e.updateCompositionStatusRequest,o=s,null==o?o:{status:o.status})},t);var o,s;return new ie(n,(e=>Ae(e)))}))}updateCompositionStatus(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.updateCompositionStatusRaw(e,t);return yield i.value()}))}validateCompositionContentRaw(e,t){return _i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling validateCompositionContent().');if(null==e.body)throw new X("body",'Required parameter "body" was null or undefined when calling validateCompositionContent().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/compositions/{id}/content/validate".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:e.body},t);return new ie(n,(e=>hi(e)))}))}validateCompositionContent(e,t){return _i(this,void 0,void 0,(function*(){const i=yield this.validateCompositionContentRaw(e,t);return yield i.value()}))}}var zi="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};class qi extends Y{exchangeTokenRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.exchangeTokenRequest)throw new X("exchangeTokenRequest",'Required parameter "exchangeTokenRequest" was null or undefined when calling exchangeToken().');const i={"Content-Type":"application/json"};this.configuration&&this.configuration.apiKey&&(i.Authorization=yield this.configuration.apiKey("Authorization"));const n=yield this.request({path:"/tokens/exchange",method:"POST",headers:i,query:{},body:(s=e.exchangeTokenRequest,o=s,null==o?o:{scopes:o.scopes,expiresIn:o.expiresIn})},t);var o,s;return new ie(n,(e=>Xe(e)))}))}exchangeToken(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.exchangeTokenRaw(e,t);return yield i.value()}))}validateTokenRaw(e){return zi(this,void 0,void 0,(function*(){const t={};if(this.configuration&&this.configuration.apiKey&&(t.Authorization=yield this.configuration.apiKey("Authorization")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,i=yield e("BearerAuth",[]);i&&(t.Authorization=`Bearer ${i}`)}const i=yield this.request({path:"/tokens/validate",method:"GET",headers:t,query:{}},e);return new ie(i,(e=>fi(e)))}))}validateToken(e){return zi(this,void 0,void 0,(function*(){const t=yield this.validateTokenRaw(e);return yield t.value()}))}}var Ui="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};class Bi extends Y{addLanguagesToTranslationRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling addLanguagesToTranslation().');if(null==e.addLanguagesToTranslationRequest)throw new X("addLanguagesToTranslationRequest",'Required parameter "addLanguagesToTranslationRequest" was null or undefined when calling addLanguagesToTranslation().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/translations/{id}/languages".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.addLanguagesToTranslationRequest,o=s,null==o?o:{languages:o.languages})},t);var o,s;return new ie(n,(e=>pe(e)))}))}addLanguagesToTranslation(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.addLanguagesToTranslationRaw(e,t);return yield i.value()}))}createTranslationRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.createTranslationRequest)throw new X("createTranslationRequest",'Required parameter "createTranslationRequest" was null or undefined when calling createTranslation().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/translations",method:"POST",headers:i,query:{},body:(s=e.createTranslationRequest,o=s,null==o?o:{name:o.name,description:o.description,root_composition_id:o.root_composition_id,root_language:o.root_language,selected_languages:o.selected_languages})},t);var o,s;return new ie(n,(e=>qe(e)))}))}createTranslation(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.createTranslationRaw(e,t);return yield i.value()}))}deleteTranslationRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling deleteTranslation().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/translations/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"DELETE",headers:i,query:{}},t);return new ie(n,(e=>ui(e)))}))}deleteTranslation(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.deleteTranslationRaw(e,t);return yield i.value()}))}getLanguagePresetsRaw(e){return Ui(this,void 0,void 0,(function*(){const t=yield this.request({path:"/translations/language-presets",method:"GET",headers:{},query:{}},e);return new ie(t,(e=>mt(e)))}))}getLanguagePresets(e){return Ui(this,void 0,void 0,(function*(){const t=yield this.getLanguagePresetsRaw(e);return yield t.value()}))}getSupportedLanguagesRaw(e){return Ui(this,void 0,void 0,(function*(){const t=yield this.request({path:"/translations/supported-languages",method:"GET",headers:{},query:{}},e);return new ie(t,(e=>yt(e)))}))}getSupportedLanguages(e){return Ui(this,void 0,void 0,(function*(){const t=yield this.getSupportedLanguagesRaw(e);return yield t.value()}))}getTranslationRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getTranslation().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/translations/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>wt(e)))}))}getTranslation(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.getTranslationRaw(e,t);return yield i.value()}))}getTranslationAnalyticsRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getTranslationAnalytics().');const i={};null!=e.period&&(i.period=e.period);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/translations/{id}/analytics".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new ie(o,(e=>kt(e)))}))}getTranslationAnalytics(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.getTranslationAnalyticsRaw(e,t);return yield i.value()}))}getTranslationConfigRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getTranslationConfig().');const i=yield this.request({path:"/translations/{id}/config".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:{},query:{}},t);return new ie(i,(e=>Et(e)))}))}getTranslationConfig(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.getTranslationConfigRaw(e,t);return yield i.value()}))}getTranslationsRaw(e,t){return Ui(this,void 0,void 0,(function*(){const i={};null!=e.status&&(i.status=e.status);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/translations",method:"GET",headers:n,query:i},t);return new ie(o,(e=>Ct(e)))}))}getTranslations(){return Ui(this,arguments,void 0,(function*(e={},t){const i=yield this.getTranslationsRaw(e,t);return yield i.value()}))}removeLanguageFromTranslationRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling removeLanguageFromTranslation().');if(null==e.languageCode)throw new X("languageCode",'Required parameter "languageCode" was null or undefined when calling removeLanguageFromTranslation().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/translations/{id}/languages/{languageCode}".replace("{id}",encodeURIComponent(String(e.id))).replace("{languageCode}",encodeURIComponent(String(e.languageCode))),method:"DELETE",headers:i,query:{}},t);return new ie(n,(e=>pe(e)))}))}removeLanguageFromTranslation(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.removeLanguageFromTranslationRaw(e,t);return yield i.value()}))}retranslateExperimentRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling retranslateExperiment().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/translations/{id}/retranslate".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.retranslateExperimentRequest,o=s,null==o?o:{languages:o.languages})},t);var o,s;return new ie(n,(e=>ui(e)))}))}retranslateExperiment(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.retranslateExperimentRaw(e,t);return yield i.value()}))}submitTranslationAnalyticsEventRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling submitTranslationAnalyticsEvent().');if(null==e.submitTranslationAnalyticsEventRequest)throw new X("submitTranslationAnalyticsEventRequest",'Required parameter "submitTranslationAnalyticsEventRequest" was null or undefined when calling submitTranslationAnalyticsEvent().');const i={"Content-Type":"application/json"},n=yield this.request({path:"/translations/{id}/analytics/events".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.submitTranslationAnalyticsEventRequest,o=s,null==o?o:{eventType:o.eventType,language:o.language,compositionId:o.compositionId,metadata:o.metadata})},t);var o,s;return new ne(n)}))}submitTranslationAnalyticsEvent(e,t){return Ui(this,void 0,void 0,(function*(){yield this.submitTranslationAnalyticsEventRaw(e,t)}))}updateTranslationStatusRaw(e,t){return Ui(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling updateTranslationStatus().');if(null==e.updateTranslationStatusRequest)throw new X("updateTranslationStatusRequest",'Required parameter "updateTranslationStatusRequest" was null or undefined when calling updateTranslationStatus().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("BearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/translations/{id}/status".replace("{id}",encodeURIComponent(String(e.id))),method:"PUT",headers:i,query:{},body:(s=e.updateTranslationStatusRequest,o=s,null==o?o:{status:o.status})},t);var o,s;return new ie(n,(e=>pe(e)))}))}updateTranslationStatus(e,t){return Ui(this,void 0,void 0,(function*(){const i=yield this.updateTranslationStatusRaw(e,t);return yield i.value()}))}}var $i="undefined"!=typeof window&&window.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))};class Fi extends Y{checkWidgetAccessRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling checkWidgetAccess().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}/access".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>Se(e)))}))}checkWidgetAccess(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.checkWidgetAccessRaw(e,t);return yield i.value()}))}createWidgetRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.idempotencyKey)throw new X("idempotencyKey",'Required parameter "idempotencyKey" was null or undefined when calling createWidget().');if(null==e.newWidget)throw new X("newWidget",'Required parameter "newWidget" was null or undefined when calling createWidget().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets",method:"POST",headers:i,query:{},body:(s=e.newWidget,o=s,null==o?o:{name:o.name,type:o.type,content:o.content,isPublic:o.isPublic,isDraft:o.isDraft,canvasId:o.canvasId,projectId:o.projectId,organizationId:o.organizationId,workspaceType:o.workspaceType,managedUserId:o.managedUserId,managedUserExternalId:o.managedUserExternalId})},t);var o,s;return new ie(n,(e=>Ne(e)))}))}createWidget(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.createWidgetRaw(e,t);return yield i.value()}))}deleteWidgetRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling deleteWidget().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("bearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"DELETE",headers:i,query:{},body:(s=e.deleteWidgetRequest,o=s,null==o?o:{reason:o.reason})},t);var o,s;return new ne(n)}))}deleteWidget(e,t){return $i(this,void 0,void 0,(function*(){yield this.deleteWidgetRaw(e,t)}))}detachWidgetRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling detachWidget().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}/detach".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{}},t);return new ne(n)}))}detachWidget(e,t){return $i(this,void 0,void 0,(function*(){yield this.detachWidgetRaw(e,t)}))}duplicateWidgetRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling duplicateWidget().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("bearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}/duplicate".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.duplicateWidgetRequest,o=s,null==o?o:{name:o.name,canvas_id:o.canvas_id,managedUserId:o.managedUserId,managedUserExternalId:o.managedUserExternalId})},t);var o,s;return new ie(n,(e=>Qe(e)))}))}duplicateWidget(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.duplicateWidgetRaw(e,t);return yield i.value()}))}getWidgetContentSchemaRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getWidgetContentSchema().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}/schema/content".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n)}))}getWidgetContentSchema(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getWidgetContentSchemaRaw(e,t);return yield i.value()}))}getWidgetDesignSchemaRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling getWidgetDesignSchema().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}/schema/design".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new ie(n)}))}getWidgetDesignSchema(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getWidgetDesignSchemaRaw(e,t);return yield i.value()}))}getWidgetPublishHistoryRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new X("widgetId",'Required parameter "widgetId" was null or undefined when calling getWidgetPublishHistory().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("bearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{widgetId}/publish-history".replace("{widgetId}",encodeURIComponent(String(e.widgetId))),method:"GET",headers:i,query:{}},t);return new ie(n,(e=>xt(e)))}))}getWidgetPublishHistory(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getWidgetPublishHistoryRaw(e,t);return yield i.value()}))}getWidgetsRaw(e,t){return $i(this,void 0,void 0,(function*(){const i={};null!=e.page&&(i.page=e.page),null!=e.size&&(i.size=e.size),null!=e.canvasId&&(i.canvasId=e.canvasId),null!=e.managedUserId&&(i.managedUserId=e.managedUserId),null!=e.managedUserExternalId&&(i.managedUserExternalId=e.managedUserExternalId);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const o=yield this.request({path:"/widgets",method:"GET",headers:n,query:i},t);return new ie(o,(e=>Mt(e)))}))}getWidgets(){return $i(this,arguments,void 0,(function*(e={},t){const i=yield this.getWidgetsRaw(e,t);return yield i.value()}))}getWidgetsBatchRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.getWidgetsBatchRequest)throw new X("getWidgetsBatchRequest",'Required parameter "getWidgetsBatchRequest" was null or undefined when calling getWidgetsBatch().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/batch",method:"POST",headers:i,query:{},body:(s=e.getWidgetsBatchRequest,o=s,null==o?o:{widgetIds:o.widgetIds})},t);var o,s;return new ie(n,(e=>Lt(e)))}))}getWidgetsBatch(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getWidgetsBatchRaw(e,t);return yield i.value()}))}renameWidgetPublishHistoryTitleRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new X("widgetId",'Required parameter "widgetId" was null or undefined when calling renameWidgetPublishHistoryTitle().');if(null==e.version)throw new X("version",'Required parameter "version" was null or undefined when calling renameWidgetPublishHistoryTitle().');if(null==e.renameWidgetPublishHistoryTitleRequest)throw new X("renameWidgetPublishHistoryTitleRequest",'Required parameter "renameWidgetPublishHistoryTitleRequest" was null or undefined when calling renameWidgetPublishHistoryTitle().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("bearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{widgetId}/publish-history/{version}/title".replace("{widgetId}",encodeURIComponent(String(e.widgetId))).replace("{version}",encodeURIComponent(String(e.version))),method:"PATCH",headers:i,query:{},body:(s=e.renameWidgetPublishHistoryTitleRequest,o=s,null==o?o:{commitTitle:o.commitTitle})},t);var o,s;return new ie(n,(e=>Bt(e)))}))}renameWidgetPublishHistoryTitle(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.renameWidgetPublishHistoryTitleRaw(e,t);return yield i.value()}))}setWidgetPublishHistoryLiveRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new X("widgetId",'Required parameter "widgetId" was null or undefined when calling setWidgetPublishHistoryLive().');if(null==e.version)throw new X("version",'Required parameter "version" was null or undefined when calling setWidgetPublishHistoryLive().');const i={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("bearerAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{widgetId}/publish-history/{version}/set-live".replace("{widgetId}",encodeURIComponent(String(e.widgetId))).replace("{version}",encodeURIComponent(String(e.version))),method:"POST",headers:i,query:{}},t);return new ie(n,(e=>Vt(e)))}))}setWidgetPublishHistoryLive(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.setWidgetPublishHistoryLiveRaw(e,t);return yield i.value()}))}updateWidgetRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling updateWidget().');if(null==e.updateWidgetRequest)throw new X("updateWidgetRequest",'Required parameter "updateWidgetRequest" was null or undefined when calling updateWidget().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}".replace("{id}",encodeURIComponent(String(e.id))),method:"PATCH",headers:i,query:{},body:(s=e.updateWidgetRequest,o=s,null==o?o:{name:o.name,description:o.description,canvasId:o.canvasId,projectId:o.projectId,projectFolder:o.projectFolder})},t);var o,s;return new ne(n)}))}updateWidget(e,t){return $i(this,void 0,void 0,(function*(){yield this.updateWidgetRaw(e,t)}))}updateWidgetRepositoryRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling updateWidgetRepository().');if(null==e.updateWidgetRepositoryRequest)throw new X("updateWidgetRepositoryRequest",'Required parameter "updateWidgetRepositoryRequest" was null or undefined when calling updateWidgetRepository().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}/repository".replace("{id}",encodeURIComponent(String(e.id))),method:"PUT",headers:i,query:{},body:(s=e.updateWidgetRepositoryRequest,o=s,null==o?o:{repositoryId:o.repositoryId})},t);var o,s;return new ie(n,(e=>di(e)))}))}updateWidgetRepository(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.updateWidgetRepositoryRaw(e,t);return yield i.value()}))}uploadWidgetThumbnailRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new X("id",'Required parameter "id" was null or undefined when calling uploadWidgetThumbnail().');if(null==e.uploadWidgetThumbnailRequest)throw new X("uploadWidgetThumbnailRequest",'Required parameter "uploadWidgetThumbnailRequest" was null or undefined when calling uploadWidgetThumbnail().');const i={"Content-Type":"application/json"};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=yield e("apiKeyAuth",[]);t&&(i.Authorization=`Bearer ${t}`)}const n=yield this.request({path:"/widgets/{id}/thumbnail".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.uploadWidgetThumbnailRequest,o=s,null==o?o:{imageDataUrl:o.imageDataUrl})},t);var o,s;return new ie(n,(e=>li(e)))}))}uploadWidgetThumbnail(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.uploadWidgetThumbnailRaw(e,t);return yield i.value()}))}}class Ni extends Error{constructor(e,t,i){super(e),this.code=t,this.statusCode=i,this.name="AuthError"}}class ji{constructor(e={}){var t,i;this.currentToken=null,this.apiKey=null,this.refreshTimer=null,this.config=Object.assign({apiUrl:e.apiUrl||A(),debug:e.debug||!1},e),this.apiKey=e.apiKey||"undefined"!=typeof process&&((null===(t={NODE_ENV:"production"})||void 0===t?void 0:t.PUBLIC_API_KEY)||(null===(i={NODE_ENV:"production"})||void 0===i?void 0:i.API_KEY))||null}createTokensApiForApiKey(e){const i=new K({basePath:this.config.apiUrl,apiKey:()=>t(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${C}`}});return new qi(i)}createTokensApiForAccessToken(e){const i=new K({basePath:this.config.apiUrl,accessToken:()=>t(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${C}`}});return new qi(i)}setApiKey(e){this.apiKey=e,this.currentToken={token:e,tokenType:"API-Key",expiresAt:null,scopes:[]},this.config.debug&&B.debug("AuthManager: API key set")}getValidToken(e){return t(this,void 0,void 0,(function*(){if(this.currentToken&&this.isTokenValid(this.currentToken)){if(ji.validatedTokens.has(this.currentToken.token))return this.currentToken.token;if(yield this.validateToken())return this.currentToken.token}if(this.apiKey)return yield this.exchangeApiKeyForJWT(e),this.currentToken.token;throw new Ni("No authentication method available","NO_AUTH_METHOD")}))}exchangeApiKeyForJWT(e){return t(this,void 0,void 0,(function*(){var t;if(!this.apiKey)throw new Ni("No API key available for exchange","NO_API_KEY");const i={scopes:(null==e?void 0:e.scopes)||this.getDefaultScopes(),expiresIn:(null==e?void 0:e.expiresIn)||1800};try{const e=this.createTokensApiForApiKey(this.apiKey),n=yield e.exchangeToken({exchangeTokenRequest:i}),o=(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.token)||(null==n?void 0:n.token);if(!o)throw new Ni("Token exchange response missing token","INVALID_RESPONSE");const s=(null==n?void 0:n.data)||n,r={token:o,tokenType:s.tokenType||"Bearer",expiresAt:s.expiresAt?s.expiresAt instanceof Date?s.expiresAt.toISOString():String(s.expiresAt):null,scopes:s.scopes||[]};return this.setToken(r),this.config.debug&&B.info("AuthManager: Token exchanged successfully",{scopes:r.scopes,expiresAt:r.expiresAt}),r}catch(e){const t=e instanceof Ni?e:new Ni(`Token exchange failed: ${e instanceof Error?e.message:String(e)}`,"TOKEN_EXCHANGE_ERROR");throw this.config.onAuthError&&this.config.onAuthError(t),t}}))}validateToken(){return t(this,void 0,void 0,(function*(){var e;if(!this.currentToken)return!1;if(ji.validatedTokens.has(this.currentToken.token))return!0;try{const t=this.createTokensApiForAccessToken(this.currentToken.token),i=yield t.validateToken();return!0===(null==i?void 0:i.success)&&!0===(null===(e=i.data)||void 0===e?void 0:e.valid)||!0===(null==i?void 0:i.valid)?(ji.validatedTokens.add(this.currentToken.token),!0):(this.clearToken(),!1)}catch(e){return this.config.debug&&B.warn("AuthManager: Token validation failed",e),!1}}))}setToken(e){this.currentToken=e,e.expiresAt&&this.scheduleTokenRefresh(e),this.config.onTokenRefreshed&&this.config.onTokenRefreshed(e.token)}clearToken(){this.currentToken&&ji.validatedTokens.delete(this.currentToken.token),this.currentToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}isTokenValid(e){if(!e.expiresAt)return!0;const t=new Date(e.expiresAt).getTime();return Date.now()<t-6e4}scheduleTokenRefresh(e){if(!e.expiresAt||!this.apiKey)return;const i=new Date(e.expiresAt).getTime()-Date.now()-3e5;i>0&&(this.refreshTimer=setTimeout((()=>t(this,void 0,void 0,(function*(){try{yield this.exchangeApiKeyForJWT({scopes:e.scopes}),this.config.debug&&B.info("AuthManager: Token refreshed automatically")}catch(e){this.config.debug&&B.error("AuthManager: Automatic token refresh failed",e),this.config.onTokenExpired&&this.config.onTokenExpired()}}))),i))}getDefaultScopes(){return["compositions:read","widgets:read","projects:read"]}getCurrentTokenInfo(){return this.currentToken}hasAuthMethod(){return!(!this.apiKey&&!this.currentToken)}dispose(){this.clearToken(),this.apiKey=null,this.config.debug&&B.debug("AuthManager: Disposed")}}ji.validatedTokens=new Set;const Hi=E,Vi={NODE_ENV:"production"};let Ki=null,Gi=null;const Yi={API_URL:R.PROD_API_URL,API_VERSION:R.VERSION,CLIENT_URL:R.PROD_CLIENT_URL,PRODUCTION_URL:R.PROD_CDN_URL,NODE_ENV:"production",ENABLE_EDITING:R.ENABLE_EDITING,API_KEY:Vi.PUBLIC_API_KEY,AXIOM_API_KEY:Vi.PUBLIC_AXIOM_API_KEY,STATSIG_KEY:Vi.PUBLIC_STATSIG_KEY};function Qi(e){Ki=e}function Ji(){return Ki}function Xi(){return Gi||(Gi=new ji({apiUrl:nn(),debug:an.enabled})),Gi}function Zi(e){Xi().setApiKey(e)}function en(){return t(this,void 0,void 0,(function*(){if(Gi&&Gi.hasAuthMethod())try{return yield Gi.getValidToken()}catch(e){}if(Ki)return yield Ki.getToken();const e=Yi.API_KEY;if(!e)throw new Error("No authentication method available. Please configure an API key, TokenProvider, or set PUBLIC_API_KEY in environment variables.");return e}))}function tn(e){const t=(null==e?void 0:e.tokenProvider)||Ki;if(!t){const t=(null==e?void 0:e.apiKey)||Yi.API_KEY;return{apiKey:t,basePath:(null==e?void 0:e.basePath)||nn(),tokenProvider:t?new j(t):void 0}}return{basePath:(null==e?void 0:e.basePath)||nn(),tokenProvider:t}}function nn(){return Yi.API_URL}function on(){return Yi.PRODUCTION_URL}function sn(){return`${nn()}${Yi.API_VERSION}`}nn();const rn={renderMode:x,displayMode:D,resize:M,width:L,height:W,autoscale:O},an={enabled:k,logLevel:S},dn={AXIOM_API_KEY:Yi.AXIOM_API_KEY||"",AXIOM_DATASET:n,AXIOM_API_ENDPOINT:i,STATSIG_API_KEY:Yi.STATSIG_KEY||"",STATSIG_API_ENDPOINT:o,ENABLE_PERFORMANCE_TRACKING:s,PERFORMANCE_SAMPLE_RATE:r,PERFORMANCE_REPORTING_ENDPOINT:d,LCP_THRESHOLD:c,LCP_WARNING_THRESHOLD:l,FID_THRESHOLD:u,FID_WARNING_THRESHOLD:h,CLS_THRESHOLD:g,CLS_WARNING_THRESHOLD:p,FCP_THRESHOLD:m,FCP_WARNING_THRESHOLD:f,TTFB_THRESHOLD:v,TTFB_WARNING_THRESHOLD:y,WIDGET_LOAD_THRESHOLD:w,WIDGET_LOAD_WARNING_THRESHOLD:b,BUNDLE_SIZE_THRESHOLD:I,BUNDLE_SIZE_WARNING_THRESHOLD:T,MAX_METRICS_BUFFER:a};function cn(){return tn()}const ln=2147483647;function un(e){const t=e.getAttribute("composition-id");if(!t)throw new Error("Missing required composition-id attribute");return{compositionId:t,renderMode:hn(e.getAttribute("render-mode")),displayMode:gn(e.getAttribute("display-mode")),resize:pn(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||rn.width,height:parseInt(e.getAttribute("height")||"")||rn.height,autoscale:xn(e),adaptive:mn(e.getAttribute("adaptive")),responsive:fn(e.getAttribute("responsive")),device:Un(e),fullscreen:vn(e),triggers:_n(e),overlay:wn(e),popup:An(e),media:Wn(e),content:On(e)}}function hn(e){switch(e){case"iframe":case"custom-element":return e;default:return"auto"}}function gn(e){switch(e){case"overlay":case"popup":case"fullscreen":case"modal":return e;default:return"inline"}}function pn(e){switch(e){case"fill-width":case"fill-height":case"fixed":case"fixed-height":case"fixed-width":case"allow-scale-down":case"fill":return e;default:return"fixed"}}function mn(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function fn(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function vn(e){if("enabled"===e.getAttribute("fullscreen")||"true"===e.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:yn(e.getAttribute("fullscreen-trigger")),showControls:"false"!==e.getAttribute("fullscreen-controls"),exitOnEscape:"false"!==e.getAttribute("fullscreen-exit-on-escape"),allowAutoEnter:"true"===e.getAttribute("fullscreen-auto-enter")}}function yn(e){switch(e){case"click":case"double-click":case"hover":case"auto":case"manual":return e;default:return"click"}}function wn(e){if("enabled"===e.getAttribute("overlay")||"true"===e.getAttribute("overlay-enabled"))return{enabled:!0,position:En(e.getAttribute("overlay-position")),backdrop:In(e),background:Tn(e,In(e)),closeOnBackdropClick:"false"!==e.getAttribute("overlay-close-on-backdrop"),closeOnEscape:"false"!==e.getAttribute("overlay-close-on-escape"),showCloseButton:"false"!==e.getAttribute("overlay-close-button"),trigger:kn(e.getAttribute("overlay-trigger")),width:e.getAttribute("overlay-width")||void 0,height:e.getAttribute("overlay-height")||void 0,maxWidth:e.getAttribute("overlay-max-width")||void 0,maxHeight:e.getAttribute("overlay-max-height")||void 0,zIndex:parseInt(e.getAttribute("overlay-z-index")||"")||void 0,animation:Sn(e.getAttribute("overlay-animation")),overlayWidth:e.getAttribute("overlay-width")||void 0,overlayHeight:e.getAttribute("overlay-height")||void 0,overlayResize:Cn(e.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==e.getAttribute("keep-dimensions"),embedTarget:e.getAttribute("embed-target")||void 0}}function bn(e){return"true"===e.getAttribute("overlay-backdrop")}function In(e){return"false"!==e.getAttribute("overlay-backdrop")}function Tn(e,t){if(!t)return;const i=e.getAttribute("overlay-background-color")||void 0,n=e.getAttribute("overlay-background-opacity"),o=null===n?Number.NaN:Number(n);return{enabled:!0,color:i,opacity:Number.isFinite(o)?o:void 0}}function kn(e){switch(e){case"click":case"hover":case"manual":case"auto":return e;default:return"click"}}function Sn(e){switch(e){case"fade":case"slide-up":case"slide-down":case"slide-left":case"slide-right":case"zoom":case"bounce":case"none":return e;case"scale":return"zoom";case"slide":return"slide-up";default:return"fade"}}function En(e){switch(e){case"top":case"bottom":case"left":case"right":case"top-left":case"top-right":case"bottom-left":case"bottom-right":return e;case"top-center":return"top";case"center-left":return"left";case"center-right":return"right";case"bottom-center":return"bottom";default:return"center"}}function Cn(e){switch(e){case"fillWidth":return"fill-width";case"fillHeight":return"fill-height";case"fixedSize":return"fixed";case"fixedHeight":return"fixed-height";case"fixedWidth":return"fixed-width";case"allowScaleDown":return"allow-scale-down";case"fill":return"fill";default:return}}function An(e){if("enabled"===e.getAttribute("popup")||"true"===e.getAttribute("popup-enabled"))return{enabled:!0,trigger:Rn(e.getAttribute("popup-trigger")),width:parseInt(e.getAttribute("popup-width")||"")||void 0,height:parseInt(e.getAttribute("popup-height")||"")||void 0,centerScreen:"false"!==e.getAttribute("popup-center"),allowResize:"true"===e.getAttribute("popup-resizable"),showToolbar:"true"===e.getAttribute("popup-toolbar"),target:e.getAttribute("popup-target")||void 0}}function Rn(e){switch(e){case"click":case"manual":return e;default:return"click"}}function xn(e){const t=e.getAttribute("autoscale");return!!t&&(("true"===t||""===t||"false"!==t)&&(Dn(e)||!0))}function Dn(e){return e.getAttribute("autoscale-min-height")||e.getAttribute("autoscale-max-height")||e.getAttribute("autoscale-debounce")||e.getAttribute("autoscale-threshold")||e.getAttribute("autoscale-animate")||e.getAttribute("autoscale-animation-duration")?{enabled:!0,minHeight:parseInt(e.getAttribute("autoscale-min-height")||"")||void 0,maxHeight:parseInt(e.getAttribute("autoscale-max-height")||"")||void 0,debounceDelay:parseInt(e.getAttribute("autoscale-debounce")||"")||void 0,threshold:parseInt(e.getAttribute("autoscale-threshold")||"")||void 0,animate:"false"!==e.getAttribute("autoscale-animate"),animationDuration:parseInt(e.getAttribute("autoscale-animation-duration")||"")||void 0}:null}function Mn(e){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function Ln(e){return"widgetic"===e.tagName.toLowerCase()&&e.hasAttribute("composition-id")}function Wn(e){const t={},i=e.getAttribute("media-auto-pause")||e.getAttribute("data-media-auto-pause");null!==i&&(t.autoPause="true"===i||""===i);const n=e.getAttribute("media-type")||e.getAttribute("data-media-type");n&&["audio","video","both"].includes(n)&&(t.mediaType=n);const o=e.getAttribute("media-priority")||e.getAttribute("data-media-priority");if(o){const e=parseInt(o,10);!isNaN(e)&&e>=0&&e<=10&&(t.priority=e)}const s=e.getAttribute("media-persist-state")||e.getAttribute("data-media-persist-state");null!==s&&(t.persistState="true"===s||""===s);const r=e.getAttribute("media-allow-simultaneous")||e.getAttribute("data-media-allow-simultaneous");if(r){const e=r.split(",").map((e=>e.trim())).filter((e=>["audio","video"].includes(e)));e.length>0&&(t.allowSimultaneous=e)}const a=e.getAttribute("media-auto-resume")||e.getAttribute("data-media-auto-resume");null!==a&&(t.autoResume="true"===a||""===a);const d=e.getAttribute("media-auto-resume-timeout")||e.getAttribute("data-media-auto-resume-timeout");if(d){const e=parseInt(d,10);!isNaN(e)&&e>0&&(t.autoResumeTimeout=e)}const c=e.getAttribute("media-global-volume")||e.getAttribute("data-media-global-volume");return null!==c&&(t.globalVolume="true"===c||""===c),t}function On(e){const t={},i=e.getAttribute("content-type")||e.getAttribute("data-content-type");i&&["gallery","carousel","slider","stepper","tabs","list","custom"].includes(i)&&(t.contentType=i);const n=e.getAttribute("content-persist-state")||e.getAttribute("data-content-persist-state");null!==n&&(t.persistState="true"===n||""===n);const o=e.getAttribute("content-auto-resume")||e.getAttribute("data-content-auto-resume");null!==o&&(t.autoResume="true"===o||""===o);const s=e.getAttribute("content-auto-resume-timeout")||e.getAttribute("data-content-auto-resume-timeout");if(s){const e=parseInt(s,10);!isNaN(e)&&e>0&&(t.autoResumeTimeout=e)}const r=e.getAttribute("content-track-metadata")||e.getAttribute("data-content-track-metadata");return null!==r&&(t.trackMetadata="true"===r||""===r),Object.keys(t).length>0?t:void 0}function _n(e){const t=e.getAttribute("embed-target");if("overlay"!==t&&"mixed"!==t)return;const i=function(e){switch(e){case"page-load":return"pageLoad";case"exit-intent":return"exitIntent";case"delay":return"delay";case"scroll":return"scroll";default:return}}(e.getAttribute("event-trigger")),n=parseInt(e.getAttribute("max-views")||""),o=parseInt(e.getAttribute("time-period")||""),s=Number.isFinite(n)&&n>0||Number.isFinite(o)&&o>0;return Object.assign(Object.assign(Object.assign({mode:t,eventTrigger:i},"overlay"===t&&"delay"===i?{delay:{enabled:!0,delayMs:zn(e)}}:{}),"overlay"===t&&"scroll"===i?{scroll:{enabled:!0,threshold:.1,distance:qn(e),direction:"down"}}:{}),{overlay:{position:e.getAttribute("overlay-position")||void 0,keepDimensions:"false"!==e.getAttribute("keep-dimensions"),zIndex:Pn(e),fullWidth:"true"===e.getAttribute("overlay-full-width")||void 0,overlayWidth:e.getAttribute("overlay-width")||void 0,overlayHeight:e.getAttribute("overlay-height")||void 0,overlayResize:Cn(e.getAttribute("overlay-resize-mode")),backdrop:bn(e),background:Tn(e,bn(e)),closeButton:!0},recurrence:s?{enabled:!0,maxViews:Number.isFinite(n)&&n>0?n:Number.MAX_SAFE_INTEGER,timePeriodHours:Number.isFinite(o)&&o>0?o:24}:void 0})}function Pn(e){const t=parseInt(e.getAttribute("overlay-z-index")||"");if(Number.isFinite(t)&&!(t<=0))return Math.min(t,ln)}function zn(e){const t=parseInt(e.getAttribute("trigger-delay")||"");return!Number.isFinite(t)||t<0?3e3:Math.min(t,864e5)}function qn(e){const t=parseInt(e.getAttribute("trigger-scroll-distance")||"");return Number.isFinite(t)&&t>0?t:100}function Un(e){const t=e.getAttribute("device-mobile-enabled")||e.getAttribute("data-device-mobile-enabled"),i=e.getAttribute("device-desktop-enabled")||e.getAttribute("data-device-desktop-enabled");if(t||i)return{mobileEnabled:"false"!==t,desktopEnabled:"false"!==i}}const Bn="DOMAIN_NOT_ALLOWED";function $n(){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 Fn(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 Nn(e){return t(this,void 0,void 0,(function*(){try{const i=yield fetch(e,{method:"GET",mode:"cors"});if(!i.ok){const e=yield function(e){return t(this,void 0,void 0,(function*(){if(403!==e.status)return null;try{const t=yield e.json();if(!t||"object"!=typeof t||t.code!==Bn)return null;const i=t.details&&"object"==typeof t.details?t.details:null,n="string"==typeof(null==i?void 0:i.reason)?i.reason.slice(0,80):void 0;return{code:Bn,reason:n}}catch(e){return null}}))}(i);return e?{kind:"refused",refusal:e}:{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 jn(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:{status:"found",payload:e.payload}}function Hn(e){const t=`/embed/compositions/${e}`,i=[];for(const e of $n())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 n=nn().replace(/\/+$/,"");i.push(`${n}${t}`);const o=String(R.PROD_API_URL).replace(/\/+$/,"");return o&&i.push(`${o}${t}`),[...new Set(i)]}function Vn(e){return t(this,void 0,void 0,(function*(){const t=$n();for(const i of t){const t=yield Nn(`${i}/embed/compositions/${e}`);if("unavailable"!==t.kind)return jn(t)}if("undefined"!=typeof window){const t=window.location.hostname;if("localhost"===t||"127.0.0.1"===t){const t=yield Nn(`http://localhost:3000/embed/compositions/${e}`);if("unavailable"!==t.kind)return jn(t)}}const i=yield function(e){const t=Fn(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(Fn(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(e);if(i){for(const t of Hn(e)){const e=yield Nn(t);if("refused"===e.kind)return jn(e);if("payload"===e.kind){const t=e.payload;return{status:"found",payload:Object.assign(Object.assign({},t),{embedUrl:t.embedUrl||i})}}}return{status:"found",payload:{embedUrl:i,compositionId:e}}}for(const t of Hn(e)){const e=yield Nn(t);if("unavailable"!==e.kind)return jn(e)}return{status:"not-found"}}))}const Kn=new Set;function Gn(e,t){var i;if(Kn.has(e))return;Kn.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function Yn(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}class Qn{constructor(){this.deviceInfo=null}static getInstance(){return Qn.instance||(Qn.instance=new Qn),Qn.instance}getDeviceInfo(){return this.deviceInfo||(this.deviceInfo=this.detectDevice()),this.deviceInfo}getDeviceType(){return this.getDeviceInfo().type}isMobile(){return this.getDeviceInfo().isMobile}isTablet(){return this.getDeviceInfo().isTablet}isDesktop(){return this.getDeviceInfo().isDesktop}hasTouch(){return this.getDeviceInfo().hasTouch}detectDevice(){const e=navigator.userAgent||"",t=navigator.platform||"",i=navigator.vendor||"",n=navigator.maxTouchPoints||0,o=navigator.hardwareConcurrency||1,s=navigator.deviceMemory,r=this.detectTouchCapability(),a=this.determineDeviceType(e,t,r,n),d={type:a,isMobile:"mobile"===a,isTablet:"tablet"===a,isDesktop:"desktop"===a||"tablet"===a,hasTouch:r,userAgent:e,platform:t,vendor:i,maxTouchPoints:n,hardwareConcurrency:o,deviceMemory:s};return B.debug("Device detected",d),d}detectTouchCapability(){if("ontouchstart"in window)return!0;if(navigator.maxTouchPoints&&navigator.maxTouchPoints>0)return!0;if("onpointerdown"in window)return!0;try{if(void 0!==window.DocumentTouch&&document instanceof window.DocumentTouch)return!0}catch(e){}return!1}determineDeviceType(e,t,i,n){const o=e.toLowerCase(),s=t.toLowerCase();return[/android.*mobile/,/iphone/,/ipod/,/blackberry/,/bb10/,/windows phone/,/iemobile/,/mobile/,/phone/].some((e=>e.test(o)))?"mobile":[/ipad/,/android(?!.*mobile)/,/kindle/,/silk/,/playbook/,/tablet/].some((e=>e.test(o)))?"tablet":[/windows nt/,/macintosh/,/mac os x/,/linux/,/x11/,/cros/].some((e=>e.test(o)))?"desktop":/^(iphone|ipod|android)/.test(s)?"mobile":/^(ipad)/.test(s)?"tablet":/^(win|mac|linux)/.test(s)?"desktop":i?n>=5?"tablet":n<=2?"mobile":"tablet":"desktop"}checkDeviceRestrictions(e=!0,t=!0){const i=this.getDeviceInfo();return i.isMobile&&!e?(B.debug("Widget restricted on mobile device"),!1):!(i.isDesktop&&!t)||(B.debug("Widget restricted on desktop/tablet device"),!1)}getDeviceCapabilities(){const e={userAgent:navigator.userAgent,platform:navigator.platform,vendor:navigator.vendor,language:navigator.language,languages:navigator.languages,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,maxTouchPoints:navigator.maxTouchPoints,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,connection:navigator.connection,standalone:navigator.standalone,webdriver:navigator.webdriver};return e.screen={width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,colorDepth:screen.colorDepth,pixelDepth:screen.pixelDepth,orientation:screen.orientation},e.touch={hasTouch:this.hasTouch(),hasTouchEvents:"ontouchstart"in window,hasPointerEvents:"onpointerdown"in window,hasGestureEvents:"ongesturestart"in window},window.matchMedia&&(e.mediaQueries={hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":"coarse",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":"coarse"}),e}reset(){this.deviceInfo=null}}function Jn(){return Qn.getInstance()}function Xn(e=!0,t=!0){return Jn().checkDeviceRestrictions(e,t)}const Zn="data-widgetic-overlay",eo="data-device-restricted",to=new WeakMap,io=new WeakMap,no=new Map;function oo(e,t,i){if(to.has(e))return;const n=e.getAttribute("composition-id")||"widget",o=function(e,t){const i=io.get(e);if(i)return i;const n=(no.get(t)||0)+1;no.set(t,n);const o=1===n?t:`${t}-${n}`;return io.set(e,o),o}(e,n);let s=()=>{};if(i){const e=e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===o&&(s(),i())};document.addEventListener("widgetic:overlay-shown",e),s=()=>document.removeEventListener("widgetic:overlay-shown",e)}Promise.resolve().then((function(){return Ds})).then((({TriggerManager:i})=>{if(to.has(e))return void s();const n=new i({widgetId:o,element:e,config:t,displayWhenShown:"block"});to.set(e,n),e.hasAttribute(Zn)&&e.setAttribute(Zn,"armed"),B.debug("[published-host-display] Trigger manager armed",{widgetId:o,mode:t.mode,eventTrigger:t.eventTrigger})})).catch((e=>{s(),B.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:o,error:e})}))}const so="data-widgetic-refused";function ro(e,t,i,n){!function(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(Zn)||(e.style.display="block")}(e),e.appendChild(Yn(t,n||e.getAttribute("width")||"400",e.getAttribute("height")||"300",e.getAttribute("composition-id")||void 0,i))}function ao(e){if(e.getAttribute("data-widgetic-mounted")||e.getAttribute("data-widgetic-mounting")||e.getAttribute(eo)||e.getAttribute(so))return!0;const t=e.getAttribute("src");if(t)return ro(e,t),!0;const i=e.getAttribute("composition-id");if(!i)return!1;const n=function(e){var t,i,n,o,s;let r;try{r=un(e)}catch(e){return B.warn("[published-host-display] Could not read the embed's display settings",{error:e}),{suppressed:!1}}return Xn(null===(i=null===(t=r.device)||void 0===t?void 0:t.mobileEnabled)||void 0===i||i,null===(o=null===(n=r.device)||void 0===n?void 0:n.desktopEnabled)||void 0===o||o)?("overlay"===(null===(s=r.triggers)||void 0===s?void 0:s.mode)&&(e.style.display="none",e.setAttribute(Zn,"pending")),{suppressed:!1,triggers:r.triggers}):(e.style.display="none",e.setAttribute(eo,"true"),B.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:r.compositionId,device:r.device}),{suppressed:!0})}(e);return n.suppressed||(e.setAttribute("data-widgetic-mounting","1"),Vn(i).then((t=>{var o;if(e.getAttribute("data-widgetic-mounted"))return;if("refused"===t.status)return e.removeAttribute("data-widgetic-mounting"),e.setAttribute(so,t.refusal.code),void Gn(i,t.refusal);const s="found"===t.status?t.payload:null;if(!(null==s?void 0:s.embedUrl))return void e.removeAttribute("data-widgetic-mounting");const{triggers:r}=n;if("overlay"!==(null==r?void 0:r.mode))ro(e,s.embedUrl,s),r&&oo(e,r);else{const t=(null===(o=r.overlay)||void 0===o?void 0:o.fullWidth)?"100%":void 0;oo(e,r,(()=>ro(e,s.embedUrl,s,t)))}}))),!0}function co(e=document){const t=e.querySelectorAll("widgetic");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&ao(e)&&(i+=1);return i}function lo(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:uo(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:ho(),popupBlocking:go()}}function uo(){if("undefined"==typeof performance||!performance.getEntriesByType)return!1;try{const e=performance.getEntriesByType("navigation");if(e.length>0){const t=e[0];return"h3"===t.nextHopProtocol||"h3-29"===t.nextHopProtocol}return!1}catch(e){return!1}}function ho(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function go(){if("undefined"==typeof window||!window.open)return!1;try{const e=window.open("","widgetic-popup-test","width=1,height=1");return!e||(e.close(),!1)}catch(e){return!0}}function po(e,t){switch(e){case"custom-element":case"auto":default:return t.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function mo(){if("undefined"==typeof localStorage)return!1;try{const e="widgetic-test";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}const fo={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class vo{constructor(e={}){this.compositionCache=new Map,this.widgetCache=new Map,this.pendingCompositionRequests=new Map,this.pendingWidgetRequests=new Map,this.compositionResolvers=new Map,this.widgetResolvers=new Map,this.compositionBatchQueue=[],this.widgetBatchQueue=[],this.compositionBatchTimer=null,this.widgetBatchTimer=null,this.lastBatchError=null,this.config=Object.assign(Object.assign({},fo),e)}getCompositions(e){return t(this,void 0,void 0,(function*(){"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-start");try{const t=[],i=[];for(const n of e){const e=this.getCachedComposition(n);if(e){t.push(e);continue}const o=this.pendingCompositionRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchCompositions(i);t.push(...e)}return Object.defineProperty(t,"compositions",{get(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(t,"success",{value:!this.lastBatchError,enumerable:!1,configurable:!0}),Object.defineProperty(t,"error",{value:this.lastBatchError||void 0,enumerable:!1,configurable:!0}),t}finally{"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-end")}}))}getWidgets(e){return t(this,void 0,void 0,(function*(){const t=[],i=[];for(const n of e){const e=this.getCachedWidget(n);if(e){t.push(e);continue}const o=this.pendingWidgetRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchWidgets(i);t.push(...e)}return t}))}getComposition(e){return t(this,void 0,void 0,(function*(){const t=yield this.getCompositions([e]);if(0===t.length)throw new Error(`Composition not found: ${e}`);return t[0]}))}getWidget(e){return t(this,void 0,void 0,(function*(){const t=yield this.getWidgets([e]);if(0===t.length)throw new Error(`Widget not found: ${e}`);return t[0]}))}batchCompositions(e){return t(this,void 0,void 0,(function*(){var t;const i=[];for(const t of e)if(this.pendingCompositionRequests.has(t))i.push(this.pendingCompositionRequests.get(t));else{const e=new Promise(((e,i)=>{this.compositionBatchQueue.push(t),this.scheduleCompositionBatch(),this.compositionResolvers.set(t,{resolve:e,reject:i})}));this.pendingCompositionRequests.set(t,e),i.push(e)}const n=yield Promise.allSettled(i),o=n.find((e=>"rejected"===e.status));return this.lastBatchError=o?(null===(t=o.reason)||void 0===t?void 0:t.message)||String(o.reason):null,n.filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}batchWidgets(e){return t(this,void 0,void 0,(function*(){const t=[];for(const i of e)if(this.pendingWidgetRequests.has(i))t.push(this.pendingWidgetRequests.get(i));else{const e=new Promise(((e,t)=>{this.widgetBatchQueue.push(i),this.scheduleWidgetBatch(),this.widgetResolvers.set(i,{resolve:e,reject:t})}));this.pendingWidgetRequests.set(i,e),t.push(e)}return(yield Promise.allSettled(t)).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}scheduleCompositionBatch(){this.compositionBatchTimer||(this.compositionBatchTimer=window.setTimeout((()=>{this.executeCompositionBatch()}),this.config.debounceDelay))}scheduleWidgetBatch(){this.widgetBatchTimer||(this.widgetBatchTimer=window.setTimeout((()=>{this.executeWidgetBatch()}),this.config.debounceDelay))}executeCompositionBatch(){return t(this,void 0,void 0,(function*(){const e=[...this.compositionBatchQueue];if(this.compositionBatchQueue=[],this.compositionBatchTimer=null,0!==e.length)try{const t=yield this.fetchCompositionsBatch(e);for(const e of t.compositions){this.cacheComposition(e);const t=this.compositionResolvers.get(e.id);t&&(t.resolve(e),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.compositionResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}for(const t of e){const e=this.compositionResolvers.get(t);e&&(e.reject(new Error(`Composition not found in batch response: ${t}`)),this.compositionResolvers.delete(t)),this.pendingCompositionRequests.delete(t)}}catch(t){for(const i of e){const e=this.compositionResolvers.get(i);e&&(e.reject(t),this.compositionResolvers.delete(i)),this.pendingCompositionRequests.delete(i)}}}))}executeWidgetBatch(){return t(this,void 0,void 0,(function*(){const e=[...this.widgetBatchQueue];if(this.widgetBatchQueue=[],this.widgetBatchTimer=null,0!==e.length)try{const t=yield this.fetchWidgetsBatch(e);for(const e of t.widgets){this.cacheWidget(e);const t=this.widgetResolvers.get(e.id);t&&(t.resolve(e),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.widgetResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}for(const t of e){const e=this.widgetResolvers.get(t);e&&(e.reject(new Error(`Widget not found in batch response: ${t}`)),this.widgetResolvers.delete(t)),this.pendingWidgetRequests.delete(t)}}catch(t){for(const i of e){const e=this.widgetResolvers.get(i);e&&(e.reject(t),this.widgetResolvers.delete(i)),this.pendingWidgetRequests.delete(i)}}}))}fetchCompositionsBatch(e){return t(this,arguments,void 0,(function*(e,i=1){var n,o,s;try{const i=yield en(),o=new K({basePath:sn(),apiKey:()=>t(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${Hi}`}}),s=new Pi(o),r=yield s.getCompositionsBatch({getCompositionsBatchRequest:{compositionIds:e}}),a=r.compositions||[];return{compositions:a.map((e=>{if(!e||"object"!=typeof e)return e;const{internalConfig:t,adminNotes:i}=e;return function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["internalConfig","adminNotes"])})),errors:null===(n=r.errors)||void 0===n?void 0:n.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(i<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,i-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchCompositionsBatch(e,i+1)}const n=null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.status,r=null===(s=null==t?void 0:t.response)||void 0===s?void 0:s.statusText;if("number"==typeof n){let e=`HTTP ${n}: ${r||"Request failed"}`;switch(n){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these compositions";break;case 404:e="Composition not found: One or more compositions do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}fetchWidgetsBatch(e){return t(this,arguments,void 0,(function*(e,i=1){var n,o,s;try{const i=yield en(),o=new K({basePath:sn(),apiKey:()=>t(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${Hi}`}}),s=new Fi(o),r=yield s.getWidgetsBatch({getWidgetsBatchRequest:{widgetIds:e}});return{widgets:r.widgets||[],errors:null===(n=r.errors)||void 0===n?void 0:n.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(i<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,i-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchWidgetsBatch(e,i+1)}const n=null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.status,r=null===(s=null==t?void 0:t.response)||void 0===s?void 0:s.statusText;if("number"==typeof n){let e=`HTTP ${n}: ${r||"Request failed"}`;switch(n){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these widgets";break;case 404:e="Widget not found: One or more widgets do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}getCachedComposition(e){const t=this.compositionCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.compositionCache.delete(e),null):t.data}getCachedWidget(e){const t=this.widgetCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.widgetCache.delete(e),null):t.data}cacheComposition(e){this.compositionCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}cacheWidget(e){this.widgetCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}clearCache(){this.compositionCache.clear(),this.widgetCache.clear()}getCacheStats(){return{compositions:{size:this.compositionCache.size,entries:Array.from(this.compositionCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},widgets:{size:this.widgetCache.size,entries:Array.from(this.widgetCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},pending:{compositions:this.pendingCompositionRequests.size,widgets:this.pendingWidgetRequests.size},queues:{compositions:this.compositionBatchQueue.length,widgets:this.widgetBatchQueue.length}}}}let yo=null;function wo(){return yo||(yo=new vo),yo}const bo={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:on()};class Io{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},bo),e)}loadModule(e){return t(this,arguments,void 0,(function*(e,t={}){const i=this.getModuleKey(e.id,t.version||e.version),n=this.loadingPromises.get(i);if(n&&!t.force)return n;if(!t.force){const e=this.getCachedModule(i);if(e)return{module:e.module,url:e.url,loadTime:0,cached:!0}}const o=this.doLoadModule(e,t);this.loadingPromises.set(i,o);try{const e=yield o;return this.loadingPromises.delete(i),e}catch(e){throw this.loadingPromises.delete(i),e}}))}loadModules(e){return t(this,arguments,void 0,(function*(e,t={}){const i=new Map,n=new Map;for(const t of e)if(n.set(t.id,t),t.dependencies){this.dependencyGraph.set(t.id,new Set(t.dependencies));for(const e of t.dependencies)i.set(e,t)}const o=this.resolveDependencyOrder(e),s=[];for(const e of o)try{const i=yield this.loadModule(e,t);s.push(i)}catch(e){}return s}))}getLatestVersion(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.config.cdnBaseUrl}/${e}/latest`,i=yield this.fetchWithHttp3(t,{timeout:5e3});if(i.ok){return(yield i.json()).version}}catch(e){}return null}))}preloadModules(e){return t(this,void 0,void 0,(function*(){const t=e.map((e=>this.loadModule(e,{timeout:3e4}).catch((e=>{}))));yield Promise.allSettled(t)}))}invalidateModule(e,t){if(t){const i=this.getModuleKey(e,t);this.moduleCache.delete(i)}else{Array.from(this.moduleCache.keys()).filter((t=>t.startsWith(`${e}@`))).forEach((e=>this.moduleCache.delete(e)))}}clearCache(){this.moduleCache.clear(),this.loadingPromises.clear()}getCacheStats(){return{size:this.moduleCache.size,entries:Array.from(this.moduleCache.entries()).map((([e,t])=>({key:e,version:t.version,age:Date.now()-t.timestamp,ttl:t.ttl,url:t.url}))),loading:this.loadingPromises.size,http3Supported:this.http3Supported}}doLoadModule(e,i){return t(this,void 0,void 0,(function*(){const t=Date.now(),n=i.version||e.version,o=this.resolveModuleUrl(e,n);try{e.dependencies&&e.dependencies.length>0&&(yield this.loadDependencies(e.dependencies));const s=yield this.loadModuleFromUrl(o,{timeout:i.timeout||this.config.loadTimeout,retries:i.retries||this.config.maxRetries});if(!this.validateModule(s))throw new Error(`Invalid module structure for ${e.id}`);const r=this.getModuleKey(e.id,n);return this.cacheModule(r,{module:s,url:o,timestamp:Date.now(),version:n,ttl:this.config.cacheTTL}),{module:s,url:o,loadTime:Date.now()-t,cached:!1}}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load module ${e.id}@${n}: ${i}`)}}))}loadModuleFromUrl(e,i){return t(this,void 0,void 0,(function*(){let t=null;for(let n=1;n<=i.retries;n++)try{if(e.endsWith(".mjs")||e.includes("type=module")){const t=yield this.loadEsModule(e,i.timeout);return this.extractWidgetFromEsModule(t)}const t=yield this.fetchModuleText(e,i.timeout);return this.evaluateUmdModule(t,e)}catch(e){if(t=e instanceof Error?e:new Error(String(e)),n<i.retries){const e=this.config.retryDelay*Math.pow(2,n-1);yield new Promise((t=>setTimeout(t,e)))}}throw t||new Error("Module loading failed")}))}loadEsModule(e,i){return t(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{const o=setTimeout((()=>{n(new Error(`Module load timeout: ${e}`))}),i);import(e).then((e=>{clearTimeout(o),t(e)})).catch((e=>{clearTimeout(o),n(e)}))}))}))}fetchModuleText(e,i){return t(this,void 0,void 0,(function*(){const t=yield this.fetchWithHttp3(e,{timeout:i});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);return yield t.text()}))}fetchWithHttp3(e,i){return t(this,void 0,void 0,(function*(){null===this.http3Supported&&(this.http3Supported=yield this.detectHttp3Support());const t={signal:AbortSignal.timeout(i.timeout)};return fetch(e,t)}))}detectHttp3Support(){return t(this,void 0,void 0,(function*(){var e;try{if("connection"in navigator&&"effectiveType"in navigator.connection){const e=navigator.connection;return"4g"===e.effectiveType||"5g"===e.effectiveType}const t=`${this.config.cdnBaseUrl}/test-http3`,i=yield fetch(t,{method:"HEAD",signal:AbortSignal.timeout(2e3)}).catch((()=>null));return(null===(e=null==i?void 0:i.headers.get("alt-svc"))||void 0===e?void 0:e.includes("h3"))||!1}catch(e){return!1}}))}extractWidgetFromEsModule(e){const t=e.default||e.Widget||e.widget||e;if(!t)throw new Error("No widget found in module exports");return{id:t.id||"unknown",version:t.version||"1.0.0",component:t.component||t,metadata:t.metadata,dependencies:t.dependencies}}evaluateUmdModule(e,t){const i={window:"undefined"!=typeof window?window:{},document:"undefined"!=typeof document?document:{},console:console,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval},n=new Function("window","document","console","setTimeout","clearTimeout","setInterval","clearInterval",`\n let module = { exports: {} };\n let exports = module.exports;\n \n ${e}\n \n return module.exports.default || module.exports;\n `)(i.window,i.document,i.console,i.setTimeout,i.clearTimeout,i.setInterval,i.clearInterval);if(!n)throw new Error(`Module evaluation failed: ${t}`);return{id:n.id||"unknown",version:n.version||"1.0.0",component:n.component||n,metadata:n.metadata,dependencies:n.dependencies}}loadDependencies(e){return t(this,void 0,void 0,(function*(){const i=e.map((e=>t(this,void 0,void 0,(function*(){try{if("undefined"!=typeof window&&window[e])return}catch(e){}}))));yield Promise.allSettled(i)}))}resolveDependencyOrder(e){const t=new Set,i=new Set,n=[],o=new Map(e.map((e=>[e.id,e]))),s=e=>{if(i.has(e.id))throw new Error(`Circular dependency detected: ${e.id}`);if(!t.has(e.id)){if(i.add(e.id),e.dependencies)for(const t of e.dependencies){const e=o.get(t);e&&s(e)}i.delete(e.id),t.add(e.id),n.push(e)}};for(const i of e)t.has(i.id)||s(i);return n}resolveModuleUrl(e,t){return e.moduleUrl?e.moduleUrl.replace("{{version}}",t):`${this.config.cdnBaseUrl}/${e.id}/${t}/widget.mjs`}validateModule(e){return!!(e&&e.id&&e.version&&e.component)}getModuleKey(e,t){return`${e}@${t}`}getCachedModule(e){const t=this.moduleCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.moduleCache.delete(e),null):t}cacheModule(e,t){this.moduleCache.set(e,t)}}let To=null;function ko(){return To||(To=new Io),To}const So="undefined"!=typeof HTMLElement?HTMLElement:class{};class Eo extends So{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(),B.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return t(this,void 0,void 0,(function*(){if(!this.isWidgetConnected){this.isWidgetConnected=!0,B.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 Vn(e);if("refused"===t.status)throw Gn(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(Yn(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){B.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(B.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(B.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){B.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(e){return t(this,void 0,void 0,(function*(){const t=wo();this.compositionData=yield t.getComposition(e),this.widgetData=yield t.getWidget(this.compositionData.widgetId),B.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:e,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return t(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=ko();this.loadedModule=yield e.loadModule(this.widgetData),B.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return t(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,B.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw B.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(e,i){return t(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.React||!window.ReactDOM)throw new Error("React not available globally");{const t=window.React,n=window.ReactDOM,o=this.getWidgetProps(),s=t.createElement(i,o);n.render(s,e)}}))}initializeVueComponent(e,i){return t(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.Vue)throw new Error("Vue not available globally");{const t=window.Vue,n=this.getWidgetProps();new t({el:e,render:e=>e(i,{props:n})})}}))}initializeSvelteOrVanillaComponent(e,i){return t(this,void 0,void 0,(function*(){var t;const n=this.getWidgetProps();if(i.$$prop_def||(null===(t=i.prototype)||void 0===t?void 0:t.$$prop_def))this.svelteComponent=new i({target:e,props:n});else if(i.prototype&&i.prototype.constructor===i){const t=new i(e,n);"function"==typeof t.render&&(yield t.render())}else if("function"==typeof i)yield i(e,n);else{if(!i||"function"!=typeof i.init)throw new Error("Unknown component type");yield i.init(e,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})),B.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})),B.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})),B.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return t(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){B.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(),B.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function Co(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",Eo),B.info("WidgeticWidget custom element registered")))}class Ao{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 Ao.instance||(Ao.instance=new Ao),Ao.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 r=new MutationObserver((()=>{const e=o.scrollHeight;s(e)}));r.observe(o,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,r);const a=o.scrollHeight;s(a)}findContentElement(e){var t;if("iframe"===e.tagName.toLowerCase())try{const 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 r=this.timeouts.get(t);r&&clearTimeout(r);const a=setTimeout((()=>{const r=Math.max(i.minHeight,Math.min(i.maxHeight,s));Math.abs(r-o)>=i.threshold&&(this.setElementHeight(e,r,i.animate,i.animationDuration),this.storeHeight(t,r,n),o=r,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:o,newHeight:r,contentHeight:s}}))),this.timeouts.delete(t)}),i.debounceDelay);this.timeouts.set(t,a)}}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 r=this.animationIds.get(e.id||e.tagName);r&&cancelAnimationFrame(r);const a=performance.now(),d=o,c=i=>{const o=i-a,r=Math.min(o/n,1),l=1-Math.pow(1-r,3),u=d+s*l;if(e.style.height=`${u}px`,r<1){const t=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},l=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,l)}clearStoredHeights(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStoredHeights(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return{}}}destroy(){this.observers.forEach((e=>e.disconnect())),this.observers.clear(),this.mutationObservers.forEach((e=>e.disconnect())),this.mutationObservers.clear(),this.timeouts.forEach((e=>clearTimeout(e))),this.timeouts.clear(),this.animationIds.forEach((e=>cancelAnimationFrame(e))),this.animationIds.clear()}}class Ro{static getInstance(){return Ro.instance||(Ro.instance=new Ro),Ro.instance}constructor(){this.playingWidgets=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_media_state",this.globalVolumeKey="widgetic_global_volume",this.storageVersion="2.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=18e5,this.globalVolumeEnabled=!0,this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()},this.loadPersistedState(),this.loadGlobalVolumeState(),this.setupVisibilityHandler(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumeWidgets()}),1e3)}registerWidget(e,t={}){const i=Object.assign({autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0},t);this.widgetConfigs.set(e,i);const n=this.playingWidgets.get(e);n&&i.persistState?(i.globalVolume&&this.globalVolumeEnabled&&(n.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume),setTimeout((()=>{this.sendRestoreStateCommand(e,n)}),100)):i.globalVolume&&this.globalVolumeEnabled&&setTimeout((()=>{this.sendVolumeCommand(e,this.globalVolumeState.muted?0:this.globalVolumeState.volume)}),100)}unregisterWidget(e){this.handleMediaEvent({type:"stop",compositionId:e,config:this.widgetConfigs.get(e)||{}}),this.playingWidgets.delete(e),this.widgetConfigs.delete(e),this.eventListeners.delete(e)}handleMediaEvent(e){const{type:t,compositionId:i,config:n,data:o}=e;switch(t){case"play":this.handlePlayEvent(i,n,o);break;case"pause":this.handlePauseEvent(i,o);break;case"stop":case"ended":this.handleStopEvent(i);break;case"seeking":this.handleSeekingEvent(i,null==o?void 0:o.position);break;case"volumechange":this.handleVolumeEvent(i,null==o?void 0:o.volume);break;case"trackchange":this.handleTrackChangeEvent(i,o);break;case"playlistchange":this.handlePlaylistChangeEvent(i,o)}this.emitToListeners(i,e),n.persistState&&this.persistState(),this.dispatchGlobalEvent(e)}handlePlayEvent(e,t,i={}){const n=i.mediaType||t.mediaType||"both",o=t.priority||5,s={compositionId:e,mediaType:n,state:"playing",priority:o,startedAt:Date.now(),duration:i.duration,position:i.position||0,title:i.title,volume:i.volume,playlist:i.playlist,autoResume:t.autoResume,lastInteraction:Date.now()};!1!==t.autoPause&&this.pauseConflictingWidgets(e,n,o,t.allowSimultaneous||[]),this.playingWidgets.set(e,s)}handlePauseEvent(e,t={}){const i=this.playingWidgets.get(e);i&&(i.state="paused",i.position=t.position||i.position,i.volume=t.volume||i.volume,i.lastInteraction=Date.now())}handleStopEvent(e){const t=this.playingWidgets.get(e);t&&(t.state="stopped",t.position=0,t.lastInteraction=Date.now())}handleSeekingEvent(e,t){const i=this.playingWidgets.get(e);i&&void 0!==t&&(i.position=t,i.lastInteraction=Date.now())}handleVolumeEvent(e,t){const i=this.playingWidgets.get(e),n=this.widgetConfigs.get(e);i&&void 0!==t&&(i.lastInteraction=Date.now(),(null==n?void 0:n.globalVolume)&&this.globalVolumeEnabled?(this.globalVolumeState={volume:t>0?t:this.globalVolumeState.volume,muted:0===t,lastUpdated:Date.now(),lastChangedBy:e},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(e),i.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):i.volume=t)}handleTrackChangeEvent(e,t={}){const i=this.playingWidgets.get(e);i&&t.playlist&&(i.playlist=Object.assign(Object.assign({},i.playlist),t.playlist),i.position=0,i.title=t.playlist.trackTitle||i.title,i.lastInteraction=Date.now())}handlePlaylistChangeEvent(e,t={}){const i=this.playingWidgets.get(e);i&&t.playlist&&(i.playlist=Object.assign(Object.assign({},i.playlist),t.playlist),i.lastInteraction=Date.now())}pauseConflictingWidgets(e,t,i,n){const o=[];for(const[s,r]of this.playingWidgets){if(s===e||"playing"!==r.state)continue;this.isSimultaneousAllowed(r.mediaType,t,n)||(i>r.priority||i===r.priority&&Date.now()>r.startedAt)&&o.push(s)}for(const e of o)this.sendPauseCommand(e);o.length}isSimultaneousAllowed(e,t,i){return"both"!==e&&"both"!==t&&(e!==t&&(i.includes(e)&&i.includes(t)))}sendPauseCommand(e){var t;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const n=Yi.CLIENT_URL||"*";null===(t=i.contentWindow)||void 0===t||t.postMessage({type:"widgetic:media:command",command:"pause",compositionId:e},n)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"pause",compositionId:e}}));const n=this.playingWidgets.get(e);n&&(n.state="paused")}}getPlayingWidgets(){return Array.from(this.playingWidgets.values()).filter((e=>"playing"===e.state))}getAllMediaWidgets(){return Array.from(this.playingWidgets.values())}pauseAll(){const e=this.getPlayingWidgets();for(const t of e)this.sendPauseCommand(t.compositionId)}resumeLastPlayed(){const e=Array.from(this.playingWidgets.values()).filter((e=>"paused"===e.state)).sort(((e,t)=>t.startedAt-e.startedAt));if(e.length>0){const t=e[0];this.sendResumeCommand(t.compositionId)}}sendResumeCommand(e){var t;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const n=Yi.CLIENT_URL||"*";null===(t=i.contentWindow)||void 0===t||t.postMessage({type:"widgetic:media:command",command:"play",compositionId:e},n)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"play",compositionId:e}}))}}addEventListener(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),()=>{const i=this.eventListeners.get(e);if(i){const e=i.indexOf(t);e>-1&&i.splice(e,1)}}}emitToListeners(e,t){const i=this.eventListeners.get(e);if(i)for(const e of i)try{e(t)}catch(e){}}dispatchGlobalEvent(e){document.dispatchEvent(new CustomEvent(`widgetic:media:${e.type}`,{detail:{compositionId:e.compositionId,config:e.config,data:e.data},bubbles:!0}))}loadPersistedState(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);if(t.version!==this.storageVersion)return void this.clearPersistedState();const i=864e5;if(t.timestamp&&Date.now()-t.timestamp>i)return void this.clearPersistedState();for(const[e,i]of Object.entries(t.playingWidgets||{})){const t=i;t.compositionId&&t.mediaType&&t.state&&this.playingWidgets.set(e,t)}}}catch(e){this.clearPersistedState()}}persistState(){try{const e={version:this.storageVersion,playingWidgets:Object.fromEntries(this.playingWidgets),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){}}setupVisibilityHandler(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden&&this.pauseAll()}))}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{this.persistState()}))}clearPersistedState(e=!1){try{localStorage.removeItem(this.storageKey),e&&(localStorage.removeItem(this.globalVolumeKey),this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()})}catch(e){}}getStats(){const e=this.getPlayingWidgets(),t=Array.from(this.playingWidgets.values()).filter((e=>"paused"===e.state)),i=Array.from(this.playingWidgets.values()).filter((e=>e.playlist)),n=Array.from(this.widgetConfigs.values()).filter((e=>e.globalVolume)).length;return{totalWidgets:this.widgetConfigs.size,playingWidgets:e.length,pausedWidgets:t.length,registeredWidgets:this.playingWidgets.size,widgetsWithPlaylists:i.length,globalVolumeWidgets:n,autoResumeEnabled:this.autoResumeEnabled,globalVolumeEnabled:this.globalVolumeEnabled,globalVolume:{volume:this.globalVolumeState.volume,muted:this.globalVolumeState.muted,lastUpdated:this.globalVolumeState.lastUpdated,lastChangedBy:this.globalVolumeState.lastChangedBy},storageVersion:this.storageVersion,currentlyPlaying:e.map((e=>({compositionId:e.compositionId,mediaType:e.mediaType,priority:e.priority,duration:e.startedAt?Date.now()-e.startedAt:0,position:e.position,volume:e.volume,playlist:e.playlist?{currentTrack:e.playlist.currentTrack,totalTracks:e.playlist.totalTracks,trackTitle:e.playlist.trackTitle}:void 0}))),allWidgets:Array.from(this.playingWidgets.values()).map((e=>{var t;return{compositionId:e.compositionId,state:e.state,mediaType:e.mediaType,priority:e.priority,position:e.position,volume:e.volume,lastInteraction:e.lastInteraction,playlist:e.playlist,autoResume:e.autoResume,globalVolume:(null===(t=this.widgetConfigs.get(e.compositionId))||void 0===t?void 0:t.globalVolume)||!1}}))}}destroy(){this.pauseAll(),this.playingWidgets.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.persistState(),this.persistGlobalVolumeState()}autoResumeWidgets(e={}){if(!this.autoResumeEnabled)return;const{autoResumePlayback:t=!0,maxStateAge:i=this.defaultAutoResumeTimeout,respectTimeouts:n=!0}=e,o=Date.now(),s=[];for(const[e,r]of this.playingWidgets){const a=this.widgetConfigs.get(e);(null==a?void 0:a.autoResume)&&a.persistState&&r.lastInteraction&&(!n||o-r.lastInteraction<=(a.autoResumeTimeout||i))&&("playing"===r.state||t&&"paused"===r.state)&&s.push(r)}s.length>0&&(s.sort(((e,t)=>e.priority!==t.priority?t.priority-e.priority:(t.lastInteraction||0)-(e.lastInteraction||0))),t&&"playing"===s[0].state&&this.resumeWidget(s[0].compositionId))}resumeWidget(e){const t=this.playingWidgets.get(e),i=this.widgetConfigs.get(e);return!(!t||!i)&&(this.sendRestoreStateCommand(e,t),"playing"===t.state&&setTimeout((()=>{this.sendPlayCommand(e,t.position)}),100),!0)}sendRestoreStateCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const o={type:"widgetic:media:command",command:"restore",compositionId:e,state:{position:t.position||0,volume:t.volume||1,title:t.title,playlist:t.playlist,duration:t.duration}};if("iframe"===n.tagName.toLowerCase()){const e=Yi.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(o,e)}n.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}sendPlayCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const o={type:"widgetic:media:command",command:"play",compositionId:e,position:t};if("iframe"===n.tagName.toLowerCase()){const e=Yi.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(o,e)}n.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getPersistedState(e){return this.playingWidgets.get(e)||null}updateWidgetState(e,t){const i=this.playingWidgets.get(e);if(i){const n=Object.assign(Object.assign(Object.assign({},i),t),{lastInteraction:Date.now()});this.playingWidgets.set(e,n);const o=this.widgetConfigs.get(e);(null==o?void 0:o.persistState)&&this.persistState()}}setAutoResumeEnabled(e){this.autoResumeEnabled=e}triggerAutoResume(e={}){this.autoResumeWidgets(e)}loadGlobalVolumeState(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.globalVolumeKey);if(e){const t=JSON.parse(e);"number"==typeof t.volume&&"boolean"==typeof t.muted&&(this.globalVolumeState={volume:Math.max(0,Math.min(1,t.volume)),muted:t.muted,lastUpdated:t.lastUpdated||Date.now(),lastChangedBy:t.lastChangedBy})}}catch(e){}}persistGlobalVolumeState(){try{localStorage.setItem(this.globalVolumeKey,JSON.stringify(this.globalVolumeState))}catch(e){}}syncGlobalVolumeToWidgets(e){const t=this.globalVolumeState.muted?0:this.globalVolumeState.volume;for(const[i,n]of this.widgetConfigs)if(i!==e&&n.globalVolume){this.sendVolumeCommand(i,t);const e=this.playingWidgets.get(i);e&&(e.volume=t)}}sendVolumeCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const o={type:"widgetic:media:command",command:"setVolume",compositionId:e,volume:Math.max(0,Math.min(1,t))};if("iframe"===n.tagName.toLowerCase()){const e=Yi.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(o,e)}n.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getGlobalVolumeState(){return Object.assign({},this.globalVolumeState)}setGlobalVolume(e,t){const i=Math.max(0,Math.min(1,e));this.globalVolumeState={volume:i,muted:0===i,lastUpdated:Date.now(),lastChangedBy:t||"api"},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets()}toggleGlobalMute(e){return this.globalVolumeState=Object.assign(Object.assign({},this.globalVolumeState),{muted:!this.globalVolumeState.muted,lastUpdated:Date.now(),lastChangedBy:e||"api"}),this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(),this.globalVolumeState.muted}setGlobalVolumeEnabled(e){const t=this.globalVolumeEnabled;this.globalVolumeEnabled=e,e&&!t&&this.syncGlobalVolumeToWidgets()}isGlobalVolumeEnabled(){return this.globalVolumeEnabled}}let xo=null;function Do(){return xo||(xo=Ro.getInstance()),xo}class Mo{static getInstance(){return Mo.instance||(Mo.instance=new Mo),Mo.instance}constructor(){this.contentStates=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_content_positions",this.storageVersion="1.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=864e5,this.debounceTimers=new Map,this.loadPersistedState(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumePositions()}),1e3)}registerWidget(e,t={}){const i=Object.assign({contentType:"custom",persistState:!0,autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,debounceDelay:500,trackMetadata:!1},t);this.widgetConfigs.set(e,i);const n=this.contentStates.get(e);n&&i.persistState&&setTimeout((()=>{this.sendRestorePositionCommand(e,n)}),100)}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e)),this.contentStates.delete(e),this.widgetConfigs.delete(e),this.eventListeners.delete(e)}handleContentPositionEvent(e){const{type:t,compositionId:i,config:n,data:o}=e;switch(t){case"position":case"navigate":this.handlePositionChangeEvent(i,n,o);break;case"complete":this.handleCompleteEvent(i,o);break;case"reset":this.handleResetEvent(i);break;case"metadata":this.handleMetadataEvent(i,o)}this.emitToListeners(i,e),n.persistState&&this.debouncedPersistState(i,n.debounceDelay||500),this.dispatchGlobalEvent(e)}handlePositionChangeEvent(e,t,i={}){const n=this.contentStates.get(e),o={compositionId:e,contentType:t.contentType||"custom",currentIndex:void 0!==i.currentIndex?i.currentIndex:(null==n?void 0:n.currentIndex)||0,totalItems:void 0!==i.totalItems?i.totalItems:(null==n?void 0:n.totalItems)||0,currentItemId:i.currentItemId||(null==n?void 0:n.currentItemId),currentItemTitle:i.currentItemTitle||(null==n?void 0:n.currentItemTitle),lastUpdated:Date.now(),autoResume:t.autoResume,lastInteraction:Date.now(),metadata:t.trackMetadata?Object.assign(Object.assign({},null==n?void 0:n.metadata),i.metadata):void 0};this.contentStates.set(e,o)}handleCompleteEvent(e,t={}){const i=this.contentStates.get(e);i&&(i.lastInteraction=Date.now(),i.metadata&&(i.metadata.completed=!0,i.metadata.completedAt=Date.now(),t.metadata&&Object.assign(i.metadata,t.metadata)))}handleResetEvent(e){const t=this.contentStates.get(e);t&&(t.currentIndex=0,t.currentItemId=void 0,t.currentItemTitle=void 0,t.lastInteraction=Date.now(),t.metadata&&(t.metadata.completed=!1,delete t.metadata.completedAt))}handleMetadataEvent(e,t={}){const i=this.contentStates.get(e);i&&t.metadata&&(i.metadata||(i.metadata={}),Object.assign(i.metadata,t.metadata),i.lastInteraction=Date.now())}loadPersistedState(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);if(t.version!==this.storageVersion)return void this.clearPersistedState();const i=6048e5;if(t.timestamp&&Date.now()-t.timestamp>i)return void this.clearPersistedState();for(const[e,i]of Object.entries(t.contentStates||{})){const t=i;t.compositionId&&t.contentType&&void 0!==t.currentIndex&&this.contentStates.set(e,t)}}}catch(e){this.clearPersistedState()}}debouncedPersistState(e,t){const i=this.debounceTimers.get(e);i&&clearTimeout(i);const n=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(e)}),t);this.debounceTimers.set(e,n)}persistState(){try{const e={version:this.storageVersion,contentStates:Object.fromEntries(this.contentStates),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){}}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.persistState()}))}autoResumePositions(e={}){if(!this.autoResumeEnabled)return;const{autoResumePosition:t=!0,maxStateAge:i=this.defaultAutoResumeTimeout,respectTimeouts:n=!0}=e,o=Date.now(),s=[];for(const[e,r]of this.contentStates){const a=this.widgetConfigs.get(e);(null==a?void 0:a.autoResume)&&a.persistState&&r.lastInteraction&&(!n||o-r.lastInteraction<=(a.autoResumeTimeout||i))&&t&&s.push(r)}s.length>0&&s.forEach((e=>{this.resumeWidgetPosition(e.compositionId)}))}resumeWidgetPosition(e){const t=this.contentStates.get(e),i=this.widgetConfigs.get(e);return!(!t||!i)&&(this.sendRestorePositionCommand(e,t),!0)}sendRestorePositionCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const o={type:"widgetic:content:command",command:"restorePosition",compositionId:e,state:{currentIndex:t.currentIndex,totalItems:t.totalItems,currentItemId:t.currentItemId,currentItemTitle:t.currentItemTitle,metadata:t.metadata}};if("iframe"===n.tagName.toLowerCase()){const e=Yi.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(o,e)}n.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o}))}}getAllContentWidgets(){return Array.from(this.contentStates.values())}getPersistedPosition(e){return this.contentStates.get(e)||null}updateWidgetPosition(e,t){const i=this.contentStates.get(e);if(i){const n=Object.assign(Object.assign(Object.assign({},i),t),{lastInteraction:Date.now()});this.contentStates.set(e,n);const o=this.widgetConfigs.get(e);(null==o?void 0:o.persistState)&&this.debouncedPersistState(e,o.debounceDelay||500)}}clearPersistedState(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStats(){const e=Array.from(this.contentStates.values()),t=e.reduce(((e,t)=>(e[t.contentType]=(e[t.contentType]||0)+1,e)),{});return{totalWidgets:this.widgetConfigs.size,trackedWidgets:this.contentStates.size,autoResumeEnabled:this.autoResumeEnabled,storageVersion:this.storageVersion,contentTypes:t,allWidgets:e.map((e=>({compositionId:e.compositionId,contentType:e.contentType,currentIndex:e.currentIndex,totalItems:e.totalItems,progress:e.totalItems>0?Math.round(e.currentIndex/(e.totalItems-1)*100):0,lastInteraction:e.lastInteraction,autoResume:e.autoResume,metadata:e.metadata})))}}addEventListener(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),()=>{const i=this.eventListeners.get(e);if(i){const e=i.indexOf(t);e>-1&&i.splice(e,1)}}}emitToListeners(e,t){const i=this.eventListeners.get(e);if(i)for(const e of i)try{e(t)}catch(e){}}dispatchGlobalEvent(e){document.dispatchEvent(new CustomEvent(`widgetic:content:${e.type}`,{detail:{compositionId:e.compositionId,config:e.config,data:e.data},bubbles:!0}))}setAutoResumeEnabled(e){this.autoResumeEnabled=e}triggerAutoResume(e={}){this.autoResumePositions(e)}destroy(){for(const e of this.debounceTimers.values())clearTimeout(e);this.contentStates.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.debounceTimers.clear(),this.persistState()}}let Lo=null;function Wo(){return Lo||(Lo=Mo.getInstance()),Lo}class Oo{constructor(){this.autoScaleManager=Ao.getInstance(),Co()}render(e){return t(this,void 0,void 0,(function*(){const{compositionId:t,width:i="100%",height:n="400",resize:o="responsive",autoscale:s=!0,adaptive:r=768,media:a,content:d}=e,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",t),c.setAttribute("width",String(i)),c.setAttribute("height",String(n)),c.setAttribute("resize",o),"boolean"==typeof s?c.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(c.setAttribute("autoscale","true"),void 0!==s.minHeight&&c.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&c.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&c.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&c.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&c.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&c.setAttribute("autoscale-animation-duration",String(s.animationDuration))):c.setAttribute("autoscale","false"),c.setAttribute("adaptive",String(r)),a&&Object.keys(a).length>0){Do().registerWidget(t,a),this.setupCustomElementMediaListener(c,t)}if(d&&Object.keys(d).length>0){Wo().registerWidget(t,d),this.setupCustomElementContentListener(c,t)}return{id:`custom-${t}-${Date.now()}`,element:c,compositionData:{id:t,name:`Composition ${t}`,widgetId:`widget-${t}`,config:{}},widgetData:{id:`widget-${t}`,name:`Widget ${t}`,type:"custom-element",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"custom-element",cleanup:()=>{c._mediaCommandCleanup&&c._mediaCommandCleanup(),c._mediaObserverCleanup&&c._mediaObserverCleanup(),c._contentPositionCleanup&&c._contentPositionCleanup()}}}))}initializeWidget(e,i,n){return t(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(e,i,n){return t(this,void 0,void 0,(function*(){if(i.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const t=window.React,o=window.ReactDOM,s=t.createElement(i,{config:n.config,metadata:n.metadata});o.render(s,e)}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:e,render:e=>e(i,{props:{config:n.config,metadata:n.metadata}})})}}))}applyElementStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:r,adaptive:a}=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,a||768)}if(r){("boolean"==typeof r?r:r&&"object"==typeof r&&r.enabled)&&this.enableAutoscale(e,t,r)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const 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=Do(),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 r=(e.__widgetConfig||{}).media||{},a="audio"===n.tagName.toLowerCase()?"audio":"video";i.handleMediaEvent({type:o,compositionId:t,config:r,data:{position:n.currentTime,duration:n.duration,volume:n.volume,mediaType:a,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 r=new MutationObserver((()=>{s()}));r.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{r.disconnect()}}setupCustomElementContentListener(e,t){const i=Wo(),n=n=>{if(n.detail&&n.detail.type){const o=n.detail.type,s=n.detail.data||n.detail;let r={};try{const t=e.getAttribute("data-content-config");t&&(r=JSON.parse(t))}catch(e){r={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:r,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)}}}class _o{constructor(e={}){this.messageHandlers=new Map,this.messageQueue=new Map,this.pendingMessages=new Map,this.heartbeatIntervals=new Map,this.sequenceNumbers=new Map,this.allowedOrigins=new Set,this.customEventSubscriptions=new Map,this.functionCallHandlers=new Map,this.pendingFunctionCalls=new Map,this.widgetControllers=new Map,this.securityOptions=Object.assign({enableSignatureValidation:!1,allowedOrigins:[],messageTimeout:3e4,enableHeartbeat:!1,heartbeatInterval:3e4},e),this.setupAllowedOrigins(this.securityOptions.allowedOrigins),this.setupGlobalMessageListener(),B.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){Yi.CLIENT_URL&&this.allowedOrigins.add(Yi.CLIENT_URL),"undefined"!=typeof window&&window.location&&this.allowedOrigins.add(window.location.origin),e&&e.forEach((e=>this.allowedOrigins.add(e)));const t=new Set;this.allowedOrigins.forEach((e=>{try{const i=new URL(e);t.add(i.origin)}catch(i){t.add(e)}})),this.allowedOrigins=t,B.debug("Allowed origins configured",{origins:Array.from(this.allowedOrigins)})}setupGlobalMessageListener(){"undefined"!=typeof window&&window.addEventListener("message",(e=>{this.handleIncomingMessage(e)}))}validateMessage(e){if(!this.allowedOrigins.has(e.origin))return B.warn("Message from unauthorized origin",{origin:e.origin}),null;try{const t="string"==typeof e.data?JSON.parse(e.data):e.data;return this.isValidWidgeticMessage(t)?this.securityOptions.enableSignatureValidation&&!this.validateSignature(t)?(B.warn("Message signature validation failed",{instanceId:t.instanceId}),null):t:(B.warn("Invalid message structure",{message:t}),null)}catch(t){return B.warn("Failed to parse message",{error:t,data:e.data}),null}}isValidWidgeticMessage(e){return e&&"string"==typeof e.type&&"string"==typeof e.instanceId&&"number"==typeof e.timestamp&&"string"==typeof e.version&&void 0!==e.payload}validateSignature(e){return!0}generateSignature(e){const t=JSON.stringify(Object.assign({},e));return btoa(t).substring(0,16)}handleIncomingMessage(e){const t=this.validateMessage(e);if(!t)return;switch(B.debug("Received valid message",{type:t.type,instanceId:t.instanceId}),t.type){case"heartbeat":return void this.handleHeartbeat(t);case"auth":return void this.handleAuthentication(t);case"custom-event":return void this.handleCustomEvent(t);case"function-call":return void this.handleFunctionCall(t);case"function-response":return void this.handleFunctionResponse(t);case"text-field-change":return void this.handleTextFieldChange(t)}const i=this.messageHandlers.get(t.instanceId);if(i)try{i(t)}catch(e){B.error("Message handler error",{error:e,instanceId:t.instanceId})}else B.debug("No handler for message",{instanceId:t.instanceId,type:t.type})}handleHeartbeat(e){B.debug("Heartbeat received",{instanceId:e.instanceId}),this.sendMessage(e.instanceId,{type:"heartbeat",instanceId:e.instanceId,payload:{response:!0},timestamp:Date.now(),version:"1.0"})}handleAuthentication(e){B.debug("Authentication message received",{instanceId:e.instanceId})}handleTextFieldChange(e){const{fieldId:t,text:i,metadata:n}=e.payload;t&&"string"==typeof i?(Promise.resolve().then((function(){return Ss})).then((({getSecurityManager:o})=>{const s=o().validateTextFieldUpdate(e.instanceId,t,i,n);if(!s.allowed)return B.warn("Text field change blocked by security",{instanceId:e.instanceId,fieldId:t,reason:s.reason,severity:s.severity}),void document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:t,reason:s.reason,severity:s.severity,originalTextLength:i.length,timestamp:Date.now()},bubbles:!0}));B.debug("Text field change received",{instanceId:e.instanceId,fieldId:t,textLength:i.length,sanitized:!(!s.sanitizedText||s.sanitizedText===i)}),Promise.resolve().then((function(){return sr})).then((({getTextFieldManager:o})=>{const r=o(),a=s.sanitizedText||i;r.updateTextField(e.instanceId,t,a,{autoPersist:!0,persistState:!0,textType:(null==n?void 0:n.textType)||"custom",debounceDelay:(null==n?void 0:n.debounceDelay)||1e3,maxLength:null==n?void 0:n.maxLength},Object.assign(Object.assign({},n),{securityValidated:!0,sanitized:a!==i}))})).catch((t=>{B.warn("Failed to handle text field change",{error:t,instanceId:e.instanceId})}))})).catch((t=>{B.warn("Failed to validate text field security",{error:t,instanceId:e.instanceId})})),document.dispatchEvent(new CustomEvent("widgetic:text-field-change",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:t,text:i,metadata:n},bubbles:!0}))):B.warn("Invalid text field change message",{instanceId:e.instanceId,payload:e.payload})}handleCustomEvent(e){const{eventName:t,eventData:i,metadata:n}=e.payload,o=this.customEventSubscriptions.get(e.instanceId);if(!o)return;const s=o.get(t);s&&0!==s.size&&(B.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:t,subscriberCount:s.size}),s.forEach((o=>{try{o(i,n)}catch(i){B.error("Custom event callback error",{error:i,eventName:t,instanceId:e.instanceId})}})),document.dispatchEvent(new CustomEvent(`widgetic:custom:${t}`,{detail:{instanceId:e.instanceId,compositionId:e.compositionId,eventName:t,eventData:i,metadata:n},bubbles:!0})))}handleFunctionCall(e){const{functionName:t,args:i,requestId:n}=e.payload,o=this.functionCallHandlers.get(e.instanceId);if(!o)return void this.sendFunctionResponse(e.instanceId,n,!1,void 0,"No function handlers registered");const s=o.get(t);if(s){B.debug("Executing function call",{instanceId:e.instanceId,functionName:t,args:i});try{const t=s(...i);t&&"function"==typeof t.then?t.then((t=>this.sendFunctionResponse(e.instanceId,n,!0,t))).catch((t=>this.sendFunctionResponse(e.instanceId,n,!1,void 0,t.message||"Function execution failed"))):this.sendFunctionResponse(e.instanceId,n,!0,t)}catch(t){this.sendFunctionResponse(e.instanceId,n,!1,void 0,t instanceof Error?t.message:"Function execution failed")}}else this.sendFunctionResponse(e.instanceId,n,!1,void 0,`Function '${t}' not found`)}handleFunctionResponse(e){const{requestId:t,success:i,result:n,error:o}=e.payload,s=this.pendingFunctionCalls.get(t);s?(clearTimeout(s.timeout),this.pendingFunctionCalls.delete(t),i?s.resolve(n):s.reject(new Error(o||"Function call failed"))):B.warn("Received response for unknown function call",{requestId:t})}sendFunctionResponse(e,t,i,n,o){this.sendMessage(e,{type:"function-response",instanceId:e,payload:{requestId:t,success:i,result:n,error:o},timestamp:Date.now(),version:"1.0"})}registerHandler(e,t){this.messageHandlers.set(e,t),B.debug("Message handler registered",{instanceId:e}),this.messageQueue.has(e)||this.messageQueue.set(e,[]),this.sequenceNumbers.set(e,0),this.securityOptions.enableHeartbeat&&this.startHeartbeat(e)}unregisterHandler(e){this.messageHandlers.delete(e),this.messageQueue.delete(e),this.sequenceNumbers.delete(e),this.stopHeartbeat(e),B.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,t){const i=document.querySelector(`[data-widgetic-id="${e}"]`);if(!i||!i.contentWindow)return B.warn("Cannot send message - iframe not found",{instanceId:e}),void this.queueMessage(e,t);const n=this.getNextSequence(e),o=Object.assign(Object.assign({},t),{sequence:n});this.securityOptions.enableSignatureValidation&&(o.signature=this.generateSignature(o));try{i.contentWindow.postMessage(JSON.stringify(o),"*"),B.debug("Message sent",{instanceId:e,type:o.type,sequence:n})}catch(i){B.error("Failed to send message",{error:i,instanceId:e}),this.queueMessage(e,t)}}queueMessage(e,t){const i=this.messageQueue.get(e)||[];i.push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now()}),this.messageQueue.set(e,i),this.scheduleRetry(e)}scheduleRetry(e){if(this.pendingMessages.has(e))return;const t=setTimeout((()=>{this.processMessageQueue(e),this.pendingMessages.delete(e)}),1e3);this.pendingMessages.set(e,t)}processMessageQueue(e){const t=this.messageQueue.get(e);if(!t||0===t.length)return;const i=[];t.forEach((t=>{t.retryCount<t.maxRetries?(t.retryCount++,this.sendMessage(e,t.message),t.retryCount<t.maxRetries&&i.push(t)):B.warn("Message retry limit exceeded",{instanceId:e,message:t.message})})),this.messageQueue.set(e,i)}getNextSequence(e){const t=(this.sequenceNumbers.get(e)||0)+1;return this.sequenceNumbers.set(e,t),t}startHeartbeat(e){if(this.heartbeatIntervals.has(e))return;const t=setInterval((()=>{this.sendMessage(e,{type:"heartbeat",instanceId:e,payload:{ping:Date.now()},timestamp:Date.now(),version:"1.0"})}),this.securityOptions.heartbeatInterval);this.heartbeatIntervals.set(e,t),B.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const t=this.heartbeatIntervals.get(e);t&&(clearInterval(t),this.heartbeatIntervals.delete(e),B.debug("Heartbeat stopped",{instanceId:e}))}cleanup(){this.heartbeatIntervals.forEach((e=>clearInterval(e))),this.heartbeatIntervals.clear(),this.pendingMessages.forEach((e=>clearTimeout(e))),this.pendingMessages.clear(),this.messageHandlers.clear(),this.messageQueue.clear(),this.sequenceNumbers.clear(),B.info("WidgeticMessenger cleanup complete")}createWidgetController(e,i){const n={subscribe:(t,i)=>this.subscribeToCustomEvent(e,t,i),unsubscribe:(t,i)=>{this.unsubscribeFromCustomEvent(e,t,i)},callFunction:(t,...i)=>this.callWidgetFunction(e,t,i),getState:t=>this.callWidgetFunction(e,"getState",t?[t]:[]),setState:(t,i)=>this.callWidgetFunction(e,"setState",[t,i]),updateConfig:t=>this.callWidgetFunction(e,"updateConfig",[t]),refresh:()=>this.callWidgetFunction(e,"refresh",[]),destroy:()=>this.callWidgetFunction(e,"destroy",[]),emit:(t,i,n)=>{this.sendCustomEvent(e,t,i,n)},registerTextField:(i,n)=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return sr}));return t().registerTextField(e,i,n)})),updateTextField:(i,n,o)=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return sr}));t().updateTextField(e,i,n,{autoPersist:!0,persistState:!0},o)})),getTextField:i=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return sr}));return t().getTextField(e,i)})),clearTextField:i=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return sr}));t().clearTextField(e,i)})),getTextFields:()=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return sr}));return t().getWidgetTextFields(e)})),clearAllTextFields:()=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return sr}));t().clearWidgetTextFields(e)}))};return this.widgetControllers.set(e,n),n}subscribeToCustomEvent(e,t,i){this.customEventSubscriptions.has(e)||this.customEventSubscriptions.set(e,new Map);const n=this.customEventSubscriptions.get(e);n.has(t)||n.set(t,new Set);const o=n.get(t);return o.add(i),B.debug("Subscribed to custom event",{instanceId:e,eventName:t,totalSubscribers:o.size}),()=>{o.delete(i),0===o.size&&n.delete(t),0===n.size&&this.customEventSubscriptions.delete(e)}}unsubscribeFromCustomEvent(e,t,i){const n=this.customEventSubscriptions.get(e);if(!n)return;const o=n.get(t);o&&(i?o.delete(i):o.clear(),0===o.size&&n.delete(t),0===n.size&&this.customEventSubscriptions.delete(e),B.debug("Unsubscribed from custom event",{instanceId:e,eventName:t}))}callWidgetFunction(e,t,i,n=1e4){return new Promise(((o,s)=>{const r=`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,a=setTimeout((()=>{this.pendingFunctionCalls.delete(r),s(new Error(`Function call timeout: ${t}`))}),n);this.pendingFunctionCalls.set(r,{resolve:o,reject:s,timeout:a}),this.sendMessage(e,{type:"function-call",instanceId:e,payload:{functionName:t,args:i,requestId:r},timestamp:Date.now(),version:"1.0"}),B.debug("Sent function call",{instanceId:e,functionName:t,args:i,requestId:r})}))}sendCustomEvent(e,t,i,n){this.sendMessage(e,{type:"custom-event",instanceId:e,payload:{eventName:t,eventData:i,metadata:n},timestamp:Date.now(),version:"1.0"}),B.debug("Sent custom event",{instanceId:e,eventName:t})}registerFunctionHandlers(e,t){this.functionCallHandlers.has(e)||this.functionCallHandlers.set(e,new Map);const i=this.functionCallHandlers.get(e);Object.entries(t).forEach((([e,t])=>{i.set(e,t)})),B.debug("Registered function handlers",{instanceId:e,functions:Object.keys(t)})}unregisterFunctionHandlers(e,t){const i=this.functionCallHandlers.get(e);i&&(t?t.forEach((e=>i.delete(e))):i.clear(),0===i.size&&this.functionCallHandlers.delete(e),B.debug("Unregistered function handlers",{instanceId:e,functions:t||"all"}))}getWidgetController(e){return this.widgetControllers.get(e)||null}removeWidgetController(e){this.customEventSubscriptions.delete(e),this.functionCallHandlers.delete(e);const t=[];this.pendingFunctionCalls.forEach(((i,n)=>{n.startsWith(e)&&(clearTimeout(i.timeout),i.reject(new Error("Widget controller removed")),t.push(n))})),t.forEach((e=>this.pendingFunctionCalls.delete(e))),this.widgetControllers.delete(e),B.debug("Removed widget controller",{instanceId:e})}isActive(){return this.messageHandlers.size>0||this.widgetControllers.size>0}getCustomEventSubscriptions(){let e=0;return this.customEventSubscriptions.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}getFunctionHandlers(){let e=0;return this.functionCallHandlers.forEach((t=>{e+=t.size})),e}getMessagingStats(){return{activeHandlers:this.messageHandlers.size,widgetControllers:this.widgetControllers.size,customEventSubscriptions:this.getCustomEventSubscriptions(),functionHandlers:this.getFunctionHandlers(),pendingFunctionCalls:this.pendingFunctionCalls.size,heartbeatIntervals:this.heartbeatIntervals.size,messageQueues:Array.from(this.messageQueue.entries()).map((([e,t])=>({instanceId:e,queuedMessages:t.length})))}}}let Po=null;function zo(e){return Po||(Po=new _o(e)),Po}class qo{constructor(e={}){this.options=e,this.resizeObserver=null,this.instances=new Map,this.debounceTimers=new Map,this.options=Object.assign({observeResize:!0,debounceMs:100,enableAdaptive:!0},e),this.options.observeResize&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.handleResize.bind(this)))}registerWidget(e,t,i,n){const o={widgetId:e,element:t,container:i,config:n,originalWidth:n.width,originalHeight:n.height,aspectRatio:n.width/n.height,isObserving:!1};this.instances.set(e,o),this.applyResizeMode(o),this.resizeObserver&&this.options.observeResize&&(this.resizeObserver.observe(i),o.isObserving=!0),B.debug("Widget registered for resize handling",{widgetId:e,resizeMode:n.resize,originalSize:{width:n.width,height:n.height}})}unregisterWidget(e){const t=this.instances.get(e);if(!t)return;this.resizeObserver&&t.isObserving&&this.resizeObserver.unobserve(t.container);const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e)),this.instances.delete(e),B.debug("Widget unregistered from resize handling",{widgetId:e})}static generateIframeCSS(e){const{resize:t,width:i,height:n,autoscale:o}=e;let s="";switch(t){case"fill-width":s=`\n width: 100% !important;\n height: ${n/i*100}vw !important;\n max-height: ${n}px !important;\n object-fit: ${o?"contain":"cover"};\n `;break;case"fill-height":s=`\n height: 100% !important;\n width: ${i/n*100}vh !important;\n max-width: ${i}px !important;\n object-fit: ${o?"contain":"cover"};\n `;break;case"fixed":default:s=`\n width: ${i}px !important;\n height: ${n}px !important;\n flex-shrink: 0;\n object-fit: cover;\n `;break;case"fixed-height":s=`\n width: 100% !important;\n height: ${n}px !important;\n object-fit: ${o?"contain":"cover"};\n `;break;case"fixed-width":s=`\n width: ${i}px !important;\n height: 100% !important;\n object-fit: ${o?"contain":"cover"};\n `;break;case"allow-scale-down":s=`\n max-width: ${i}px !important;\n max-height: ${n}px !important;\n width: 100% !important;\n height: auto !important;\n object-fit: contain;\n `;break;case"fill":s=`\n width: 100% !important;\n height: 100% !important;\n object-fit: ${o?"contain":"cover"};\n `}return s.trim()}applyResizeMode(e){const{element:t,container:i,config:n}=e,{resize:o,autoscale:s}=n,r=i.getBoundingClientRect(),a=r.width,d=r.height;let c,l;switch(o){case"fill-width":c=a,l=c/e.aspectRatio,s&&l>d&&(l=d,c=l*e.aspectRatio);break;case"fill-height":l=d,c=l*e.aspectRatio,s&&c>a&&(c=a,l=c/e.aspectRatio);break;case"fixed":default:c=e.originalWidth,l=e.originalHeight;break;case"fixed-height":c=a,l=e.originalHeight;break;case"fixed-width":c=e.originalWidth,l=d;break;case"allow-scale-down":const t=a/e.originalWidth,i=d/e.originalHeight,n=Math.min(1,Math.min(t,i));c=e.originalWidth*n,l=e.originalHeight*n;break;case"fill":c=a,l=d}this.setElementSize(t,c,l,n),this.options.enableAdaptive&&n.adaptive&&this.handleAdaptiveBreakpoint(e,a),B.debug("Resize mode applied",{widgetId:e.widgetId,resizeMode:o,containerSize:{width:a,height:d},newSize:{width:c,height:l}})}setElementSize(e,t,i,n){switch(e.style.width=`${Math.round(t)}px`,e.style.height=`${Math.round(i)}px`,n.resize){case"fill":case"fill-width":case"fill-height":e.style.objectFit=n.autoscale?"contain":"cover";break;default:e.style.objectFit="contain"}e.style.boxSizing="border-box",e.style.display="block"}handleAdaptiveBreakpoint(e,t){if(!e.config.adaptive)return;const i=t<=e.config.adaptive,n=e.element;i?(n.classList.add("widgetic-adaptive-mobile"),n.classList.remove("widgetic-adaptive-desktop"),n.style.maxWidth="100%",n.style.fontSize="14px"):(n.classList.add("widgetic-adaptive-desktop"),n.classList.remove("widgetic-adaptive-mobile"),n.style.fontSize="")}handleResize(e){for(const t of e){const e=t.target;for(const[t,i]of this.instances)if(i.container===e){const e=this.debounceTimers.get(t);e&&clearTimeout(e);const n=window.setTimeout((()=>{this.applyResizeMode(i),this.debounceTimers.delete(t)}),this.options.debounceMs);this.debounceTimers.set(t,n)}}}forceResize(e){const t=this.instances.get(e);t&&this.applyResizeMode(t)}forceResizeAll(){for(const e of this.instances.values())this.applyResizeMode(e)}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.instances.clear()}}let Uo=null;class Bo{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&B.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void B.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,s=i.initialMode||(o<i.breakpoint?"mobile":"desktop"),r={mode:s,breakpoint:i.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,r),this.callbacks.set(e,n);const a=new ResizeObserver((t=>{this.handleResize(e,t,i)}));a.observe(t),this.observers.set(e,a),n(r),B.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:s,containerWidth:o})}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e));const i=this.observers.get(e);i&&(i.disconnect(),this.observers.delete(e)),this.callbacks.delete(e),this.currentStates.delete(e),B.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 B.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<i.breakpoint?"mobile":"desktop";if(o!==i.mode){const s={mode:o,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,s),n(s),B.info("Responsive state changed manually",{widgetId:e,from:i.mode,to:o,width:t,breakpoint:i.breakpoint})}}handleResize(e,t,i){const n=this.debounceTimers.get(e);n&&clearTimeout(n);const o=setTimeout((()=>{this.processResize(e,t,i),this.debounceTimers.delete(e)}),i.debounceDelay||150);this.debounceTimers.set(e,o)}processResize(e,t,i){const n=this.currentStates.get(e),o=this.callbacks.get(e);if(!n||!o)return;const s=t[t.length-1];if(!s)return;const r=s.contentRect.width,a=r<i.breakpoint?"mobile":"desktop";if(a!==n.mode){const t={mode:a,breakpoint:i.breakpoint,width:r,timestamp:Date.now()};this.currentStates.set(e,t),o(t),B.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:a,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),B.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);B.debug("ResponsiveManager cleanup complete")}}let $o=null;function Fo(){return $o||($o=new Bo),$o}class No{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=Ao.getInstance()}renderWidget(e){return t(this,void 0,void 0,(function*(){const{compositionId:t,width:i,height:n,resize:o="fixed",autoscale:s=!1,adaptive:r,responsive:a,container:d,allowFullscreen:c=!0,sandbox:l=this.getDefaultSandboxPermissions(),allowedFeatures:u=this.getDefaultAllowedFeatures(),loading:h="lazy",enableResize:g=!0,compositionData:p,widgetData:m,security:f={},fallback:v={enabled:!0,timeout:1e4,retryCount:3},media:y}=e;if(!i||!n||!d)throw new Error("Missing required parameters: width, height, and container are required");const w=p||{id:t,name:`Composition ${t}`,widgetId:`widget-${t}`,config:{}},b=m||{id:w.widgetId,name:`Widget ${t}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]};try{const p=this.createSecureIframe(t,e);p.src=yield this.buildSecureIframeUrl(t,e),p.title=`Widgetic Widget: ${w.name||t}`,p.loading=h,this.applySandboxSecurity(p,l,u),p.width=i.toString(),p.height=n.toString(),p.frameBorder="0",p.scrolling="no",c&&(p.allowFullscreen=!0,p.setAttribute("allowfullscreen","")),p.title=`Widgetic Widget ${t}`,p.setAttribute("aria-label",`Interactive widget: ${t}`);const m={compositionId:t,renderMode:"iframe",displayMode:"inline",resize:o,width:"number"==typeof i?i:parseInt(i.toString()),height:"number"==typeof n?n:parseInt(n.toString()),autoscale:s,adaptive:r,responsive:a,media:y},I=qo.generateIframeCSS(m);I&&(p.style.cssText+=I),this.applyIframeStyling(p,t,{width:i,height:n,resize:o,autoscale:s,adaptive:r}),p.style.visibility="hidden",p.style.opacity="0",p.style.transition="opacity 0.3s ease",this.addLoadingIndicator(d,m),this.setupEnhancedIframeMessaging(p,t,f),this.setupLoadingOptimization(p,t,v);const T="lazy"===h,k=new Promise(((e,i)=>{let n=null;T||(n=setTimeout((()=>{i(new Error(`Iframe load timeout for composition: ${t}`))}),v.timeout||1e4)),p.onload=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(d),p.style.visibility="visible",p.style.opacity="1",e()},p.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(d),i(new Error(`Failed to load iframe for composition: ${t}`))}}));if(d.appendChild(p),g&&"undefined"!=typeof ResizeObserver){const e=new qo({observeResize:!0}),i=`iframe-${t}-${Date.now()}`;p.setAttribute("data-widget-id",i),e.registerWidget(i,p,d,m),p.__resizeHandler=e,p.__widgetId=i}a&&"number"==typeof a&&a>0&&this.setupResponsiveMonitoring(p,d,t,a),this.iframeRegistry.set(t,p),p.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),T||(yield k);const S=`iframe-${t}-${Date.now()}`;if(B.info("Enhanced iframe widget rendered successfully",{compositionId:t,size:{width:i,height:n},resize:o,autoscale:s,responsive:a,sandbox:l.join(" "),features:u.join("; ")}),m.media&&Object.keys(m.media).length>0){Do().registerWidget(t,m.media),this.setupIframeMediaListener(p,t)}if(e.content&&Object.keys(e.content).length>0){Wo().registerWidget(t,e.content),this.setupIframeContentListener(p,t)}return{id:S,element:p,compositionData:w,widgetData:b,renderMode:"iframe",cleanup:()=>this.cleanupWidget(p)}}catch(e){throw B.error("Enhanced iframe widget rendering failed",{compositionId:t,error:e}),this.removeLoadingIndicator(d),e}}))}renderWidgets(e){return t(this,void 0,void 0,(function*(){B.debug("Rendering multiple iframe widgets",{count:e.length});const t=e.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(t),n=[];for(let t=0;t<i.length;t++){const o=i[t],s=e[t];if("fulfilled"===o.status)n.push(o.value);else{B.error("Iframe widget rendering failed in batch",{compositionId:s.compositionId,error:o.reason});const e=`error-${s.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(s,o.reason),compositionData:{id:s.compositionId,name:`Composition ${s.compositionId}`,widgetId:`widget-${s.compositionId}`,config:{}},widgetData:{id:`widget-${s.compositionId}`,name:`Widget ${s.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return B.info("Iframe batch rendering complete",{total:e.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||[Yi.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(e,i){return t(this,void 0,void 0,(function*(){var t;const n=`${Yi.CLIENT_URL}/embed/${e}`,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===(t=i.security)||void 0===t?void 0:t.signatureValidation)&&o.set("validateSignature","true"),o.set("sdkVersion","1.0"),o.set("mode","iframe");try{const e=yield en();o.set("apiKey",e)}catch(e){B.warn("Failed to get auth token for iframe",e),Yi.API_KEY&&o.set("apiKey",Yi.API_KEY)}const s=`${n}?${o.toString()}`;return B.debug("Built secure iframe URL",{compositionId:e,url:s}),s}))}applyIframeStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:r,adaptive:a}=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;r&&this.enableIframeAutoscale(e,t,r),a&&this.makeIframeResponsive(e,a)}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)},B.debug("AutoScale enabled for iframe",{compositionId:t,config:n}))}setupLoadingOptimization(e,t,i){if(!i.enabled)return;const n=i.timeout||1e4,o=i.retryCount||3;let s=0;const r=()=>{s<o?(s++,B.warn(`Iframe loading failed, retrying (${s}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+s}),1e3*s)):(B.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},a=setTimeout((()=>{B.warn("Iframe loading timeout",{compositionId:t,timeout:n}),r()}),n);this.loadingTimeouts.set(t,a),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),B.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{B.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=zo({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:nn(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),B.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,B.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(B.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:B.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})),B.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})),B.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})),B.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})),B.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})),B.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){zo().sendMessage(e,{type:t,instanceId:e,payload:i,timestamp:Date.now(),version:"1.0"})}addLoadingIndicator(e,t){const i=document.createElement("div");i.className="widgetic-loading-indicator",i.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${t.width}px;\n height: ${t.height}px;\n background: #f5f5f5;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #e0e0e0;\n border-radius: 4px;\n position: relative;\n `,i.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #666;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div>Loading widget...</div>\n </div>\n ';const n=document.createElement("style");n.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(n),e.appendChild(i)}removeLoadingIndicator(e){const t=e.querySelector(".widgetic-loading-indicator");t&&t.parentNode&&t.parentNode.removeChild(t)}createErrorElement(e,t){const i=document.createElement("div");return i.className="widgetic-error",i.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${e.width}px;\n height: ${e.height}px;\n background: #fff5f5;\n color: #e53e3e;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n text-align: center;\n padding: 16px;\n box-sizing: border-box;\n `,i.innerHTML=`\n <div>\n <div style="font-weight: 600; margin-bottom: 4px;">Widget Error</div>\n <div style="font-size: 12px; opacity: 0.8;">Failed to load composition: ${e.compositionId}</div>\n </div>\n `,i}cleanupWidget(e){const t=e.__resizeHandler,i=e.__widgetId;t&&i&&t.unregisterWidget(i);const n=e.__responsiveManager,o=e.__responsiveId;n&&o&&n.unregisterWidget(o);const s=e.__messenger,r=e.__messagingCompositionId;s&&r&&s.unregisterHandler(r);const a=this.loadingTimeouts.get(r);a&&(clearTimeout(a),this.loadingTimeouts.delete(r)),r&&this.iframeRegistry.delete(r),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),B.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=Fo(),s=zo(),r={breakpoint:n,debounceDelay:150},a=`responsive-${i}`;o.registerWidget(a,t,r,(t=>{B.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),s.sendMessage(i,{type:"responsive",instanceId:i,compositionId:i,payload:{mode:t.mode,breakpoint:t.breakpoint,width:t.width,timestamp:t.timestamp},timestamp:Date.now(),version:"1.0"}),e.dispatchEvent(new CustomEvent("widgetic:responsive",{detail:{instanceId:i,compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width},bubbles:!0}))})),e.__responsiveId=a,e.__responsiveManager=o,B.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:a})}setupIframeMediaListener(e,t){const i=Do(),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"),r=s?JSON.parse(s):{};i.handleMediaEvent({type:o,compositionId:t,config:r.media||{},data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=Wo(),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 r={};if(s)try{r=JSON.parse(s).content||{}}catch(e){r={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:r,data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._contentListenerCleanup=()=>{window.removeEventListener("message",n)}}}class jo{constructor(){this.batchClient=wo(),this.moduleLoader=ko(),this.customElementRenderer=new Oo,this.iframeRenderer=new No,this.renderedWidgets=new Map}renderWidget(e){return t(this,void 0,void 0,(function*(){const t=this.generateWidgetId(e.compositionId),i=this.createLoadingElement(e.container);e.container&&i&&e.container.appendChild(i);try{const n=yield this.batchClient.getComposition(e.compositionId),o=yield this.batchClient.getWidget(n.widgetId),s=this.determineRenderMode(e.renderMode,o);let r;if("custom-element"===s)try{r=yield this.moduleLoader.loadModule(o)}catch(s){const r=yield this.renderWithIframe(t,e,n,o);return this.removeLoadingElement(i),r}const a="iframe"===s?yield this.renderWithIframe(t,e,n,o):yield this.renderWithCustomElement(t,e,n,o,r);return this.removeLoadingElement(i),this.renderedWidgets.set(t,a),this.emitWidgetEvent("ready",{widgetId:t,compositionId:e.compositionId,renderMode:a.renderMode,loadTime:(null==r?void 0:r.loadTime)||0,cached:(null==r?void 0:r.cached)||!1}),a}catch(n){if(this.removeLoadingElement(i),this.emitWidgetEvent("error",{widgetId:t,compositionId:e.compositionId,error:n instanceof Error?n.message:String(n),fallback:"iframe"}),e.container){const t=this.createErrorElement(e.compositionId,n);e.container.appendChild(t)}try{const i=yield this.renderFallback(t,e);if(e.container){const t=e.container.querySelector(".widgetic-error");t&&t.remove()}return i}catch(e){throw new Error(`Widget rendering failed: ${n}. Fallback also failed: ${e}`)}}}))}renderWidgets(e){return t(this,void 0,void 0,(function*(){const i=e.map((e=>e.compositionId)),n=yield this.batchClient.getCompositions(i),o=new Map(n.map((e=>[e.id,e]))),s=new Set;for(const t of e)if("iframe"!==t.renderMode){const e=o.get(t.compositionId);e&&e.widgetId&&s.add(e.widgetId)}const r=s.size>0?yield this.batchClient.getWidgets(Array.from(s)):[],a=new Map(r.map((e=>[e.id,e]))),d=r.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));d.length>0&&(yield this.moduleLoader.preloadModules(d));const c=e.map((e=>t(this,void 0,void 0,(function*(){const t=o.get(e.compositionId)||{id:e.compositionId,widgetId:"default",name:"Composition",settings:{},config:{},version:"1.0.0"},i=a.get(t.widgetId)||{id:t.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(e,t,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(e){return t(this,void 0,void 0,(function*(){const t=this.renderedWidgets.get(e);if(!t)return null;t.cleanup(),this.renderedWidgets.delete(e);const i={compositionId:t.compositionData.id,renderMode:t.renderMode,container:t.element.parentElement||void 0};return this.batchClient.clearCache(),this.moduleLoader.invalidateModule(t.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(e,i,n){return t(this,void 0,void 0,(function*(){const t=this.generateWidgetId(e.compositionId);if("custom-element"===this.determineRenderMode(e.renderMode,n))try{const o=yield this.moduleLoader.loadModule(n);return this.renderWithCustomElement(t,e,i,n,o)}catch(e){}return this.renderWithIframe(t,e,i,n)}))}renderWithCustomElement(e,i,n,o,s){return t(this,void 0,void 0,(function*(){const t=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(t.element),{id:e,element:t.element,compositionData:n,widgetData:o,loadedModule:s,renderMode:"custom-element",cleanup:()=>{t.element.remove()}}}))}renderWithIframe(e,i,n,o){return t(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(e,i){return t(this,void 0,void 0,(function*(){const t=document.createElement("div");return t.className="widgetic-fallback",t.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(t),{id:e,element:t,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:()=>{t.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 Ho=null;function Vo(){return Ho||(Ho=new jo),Ho}const Ko=e=>null!==e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"===Object.prototype.toString.call(e);function Go(e){if(Array.isArray(e))return e.map(Go);if(!Ko(e))return e;const t={};for(const[i,n]of Object.entries(e)){t[i.replace(/[_-](\w)/g,((e,t)=>t?t.toUpperCase():""))]=Array.isArray(n)?n.map(Go):Ko(n)?Go(n):n}return t}function Yo(e){if(Array.isArray(e))return e.map(Yo);if(!Ko(e))return e;const t={};for(const[i,n]of Object.entries(e)){t[i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()]=Array.isArray(n)?n.map(Yo):Ko(n)?Yo(n):n}return t}class Qo{constructor(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache=new Map;const e=tn(),t=new K({basePath:e.basePath,apiKey:e.apiKey,credentials:"include"});this.authApi=new Oi(t),this.compositionsApi=new Pi(t)}checkAuthentication(){return t(this,void 0,void 0,(function*(){try{if(this.sessionCache&&Date.now()<this.sessionCacheExpiry)return{isAuthenticated:!0,session:this.sessionCache,user:this.sessionCache.user,canEdit:!0};const e=Go(yield this.authApi.getSession());return e&&e.accessToken&&e.user?(this.sessionCache=e,this.sessionCacheExpiry=Date.now()+3e5,B.info("User authenticated for editing",{userId:e.user.id,email:e.user.email}),{isAuthenticated:!0,session:e,user:e.user,canEdit:!0}):{isAuthenticated:!1,canEdit:!1}}catch(e){return B.debug("Authentication check failed",{error:e}),e instanceof Response&&e.status,{isAuthenticated:!1,canEdit:!1}}}))}checkCompositionOwnership(e){return t(this,void 0,void 0,(function*(){var t;try{const i=this.ownershipCache.get(e);if(i)return i;const n=yield this.checkAuthentication();if(!n.isAuthenticated||!(null===(t=n.session)||void 0===t?void 0:t.user)){const t={isOwner:!1,canEdit:!1,error:"User not authenticated"};return this.ownershipCache.set(e,t),t}const o=Go(yield this.compositionsApi.getCompositionById({id:e}));if(!o){const t={isOwner:!1,canEdit:!1,error:"Composition not found"};return this.ownershipCache.set(e,t),t}const s=o.creatorId===n.session.user.id,r={isOwner:s,canEdit:s,composition:o,error:s?void 0:"User does not own this composition"};return this.ownershipCache.set(e,r),setTimeout((()=>{this.ownershipCache.delete(e)}),12e4),B.debug("Composition ownership checked",{compositionId:e,isOwner:s,userId:n.session.user.id,compositionCreatorId:o.creatorId}),r}catch(t){B.warn("Failed to check composition ownership",{compositionId:e,error:t});const i={isOwner:!1,canEdit:!1,error:t instanceof Error?t.message:"Unknown error"};return this.ownershipCache.set(e,i),i}}))}canEditComposition(e){return t(this,void 0,void 0,(function*(){return(yield this.checkCompositionOwnership(e)).canEdit}))}getCurrentUser(){return t(this,void 0,void 0,(function*(){return(yield this.checkAuthentication()).user||null}))}clearCache(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache.clear(),B.debug("Authentication cache cleared")}checkMultipleCompositions(e){return t(this,void 0,void 0,(function*(){const i=new Map;return(yield this.checkAuthentication()).isAuthenticated?(yield Promise.all(e.map((e=>t(this,void 0,void 0,(function*(){const t=yield this.checkCompositionOwnership(e);i.set(e,t)}))))),i):(e.forEach((e=>{i.set(e,{isOwner:!1,canEdit:!1,error:"User not authenticated"})})),i)}))}isEditingEnabled(){return Yi.ENABLE_EDITING}}let Jo=null;function Xo(){return Jo||(Jo=new Qo),Jo}class Zo{constructor(e={}){this.host=null,this.container=null,this.content=null,this.destroyed=!1,this.options=Object.assign({target:"widgetic-portal",className:"",style:"",clickThrough:!1,zIndex:99999999},e),this.createPortal()}createPortal(){this.host=this.findOrCreateHost(),this.container=document.createElement("div"),this.container.className=(this.options.className?this.options.className+" ":"")+"widgetic-portal-contents",this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough?"none":"auto"};\n ${this.options.style}\n `,this.options.clickThrough?this.container.style.pointerEvents="none":this.container.style.pointerEvents="auto",this.host.appendChild(this.container),B.debug("Portal created",{target:this.options.target,host:this.host,container:this.container})}findOrCreateHost(){let e=null;if(this.options.target instanceof HTMLElement)return this.options.target;if("string"==typeof this.options.target){const t=`.${this.options.target}`;e=document.querySelector(t)}return e||(e=document.createElement("div"),e.classList.add("string"==typeof this.options.target?this.options.target:"widgetic-portal"),document.body.appendChild(e),B.debug("Portal host created",{target:this.options.target,host:e})),e}mount(e){this.destroyed?B.warn("Cannot mount content to destroyed portal"):this.container?(this.content&&this.unmount(),e.style.pointerEvents="auto",this.content=e,this.container.appendChild(e),B.debug("Content mounted to portal",{content:e})):B.error("Portal container not available")}unmount(){this.content&&this.container&&this.container.contains(this.content)&&(this.container.removeChild(this.content),this.content=null,B.debug("Content unmounted from portal"))}destroy(){if(!this.destroyed){if(this.unmount(),this.container&&this.host&&this.host.contains(this.container)&&this.host.removeChild(this.container),this.host&&0===this.host.childNodes.length&&this.host.parentNode){const e="string"==typeof this.options.target?this.options.target:"widgetic-portal";this.host.classList.contains(e)&&this.host.parentNode.removeChild(this.host)}this.destroyed=!0,this.host=null,this.container=null,this.content=null,B.debug("Portal destroyed")}}getContainer(){return this.container}isDestroyed(){return this.destroyed}updateOptions(e){this.destroyed?B.warn("Cannot update options on destroyed portal"):(this.options=Object.assign(Object.assign({},this.options),e),this.container&&(void 0!==e.className&&(this.container.className=(e.className?e.className+" ":"")+"widgetic-portal-contents"),void 0!==e.style&&(this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough,"none"};\n ${this.options.style}\n `),void 0!==e.clickThrough&&(this.container.style.pointerEvents=(e.clickThrough,"none"))),B.debug("Portal options updated",{options:this.options}))}}function es(e){return new Zo(e)}class ts{constructor(e={}){this.config=e,this.loadPromise=null,this.sdkInstance=null,this.isLoading=!1,this.loadTimeout=3e4,this.config=Object.assign({basePath:e.basePath||this.getUISdkBaseUrl(),version:e.version||"latest",debug:e.debug||!1},e)}getUISdkBaseUrl(){return"development"===Yi.NODE_ENV?Yi.CLIENT_URL:`${Yi.PRODUCTION_URL}/ui-sdk`}loadUISdk(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance)return this.sdkInstance;if(this.loadPromise)return this.loadPromise;this.isLoading=!0,this.loadPromise=this.performLoad();try{return this.sdkInstance=yield this.loadPromise,B.info("UI SDK loaded successfully",{basePath:this.config.basePath,version:this.config.version}),this.sdkInstance}catch(e){throw B.error("Failed to load UI SDK",{error:e,config:this.config}),this.loadPromise=null,e}finally{this.isLoading=!1}}))}performLoad(){return t(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const i=setTimeout((()=>{t(new Error("UI SDK load timeout"))}),this.loadTimeout);try{if(window.WidgeticUI)return clearTimeout(i),void e(window.WidgeticUI);const n=document.createElement("script");n.src=`${this.config.basePath}/widgetic-ui.js`,n.async=!0,n.crossOrigin="anonymous",n.onload=()=>{clearTimeout(i),window.WidgeticUI?(B.debug("UI SDK script loaded from external source"),e(window.WidgeticUI)):t(new Error("UI SDK script loaded but WidgeticUI not available"))},n.onerror=()=>{clearTimeout(i),t(new Error("Failed to load UI SDK script"))},document.head.appendChild(n),B.debug("Loading UI SDK",{src:n.src})}catch(e){clearTimeout(i),t(e)}}))}))}isLoaded(){return null!==this.sdkInstance}isLoadingState(){return this.isLoading}getInstance(){return this.sdkInstance}initializeUISdk(e){return t(this,void 0,void 0,(function*(){const t=yield this.loadUISdk();return yield t.init(Object.assign(Object.assign({},this.config),e)),B.info("UI SDK initialized",{config:Object.assign(Object.assign({},this.config),e)}),t}))}cleanup(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance){try{yield this.sdkInstance.destroy()}catch(e){B.warn("Error during UI SDK cleanup",{error:e})}this.sdkInstance=null}this.loadPromise=null,this.isLoading=!1,window.WidgeticUI&&delete window.WidgeticUI,B.debug("UI SDK cleanup complete")}))}preload(){return t(this,void 0,void 0,(function*(){try{yield this.loadUISdk(),B.debug("UI SDK preloaded successfully")}catch(e){B.warn("UI SDK preload failed",{error:e})}}))}}let is=null;function ns(e){return is||(is=new ts(e)),is}class os{constructor(e={}){this.options=e,this.sessions=new Map,this.defaultOptions={showEditButton:!0,editButtonText:"✏️ Edit",editButtonPosition:"top-right",enableClickToEdit:!0,autoDetectAuth:!0},this.options=Object.assign(Object.assign({},this.defaultOptions),e)}addOverlay(e,i){return t(this,void 0,void 0,(function*(){try{if(!this.options.autoDetectAuth)return void(yield this.createOverlay(e,i,!0));const t=Xo(),n=yield t.checkCompositionOwnership(i);n.canEdit?(yield this.createOverlay(e,i,!0),B.debug("Editor overlay added for owned composition",{compositionId:i})):B.debug("Editor overlay not added - user cannot edit",{compositionId:i,reason:n.error})}catch(e){B.warn("Failed to add editor overlay",{compositionId:i,error:e})}}))}createOverlay(e,i,n){return t(this,void 0,void 0,(function*(){if(this.sessions.has(i))return;const t=document.createElement("div");if(t.className="widgetic-editor-overlay",t.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 10000;\n pointer-events: none;\n ${this.getOverlayStyles()}\n `,this.options.showEditButton&&n){const e=this.createEditButton(i);t.appendChild(e)}this.options.enableClickToEdit&&n&&this.addClickToEdit(t,i);const o=e.parentElement;if(o){"static"===window.getComputedStyle(o).position&&(o.style.position="relative"),o.appendChild(t)}else e.style.position="relative",e.appendChild(t);const s={compositionId:i,isOpen:!1,overlay:t};this.sessions.set(i,s),B.debug("Editor overlay created",{compositionId:i})}))}createEditButton(e){const i=document.createElement("button");return i.className="widgetic-edit-button",i.textContent=this.options.editButtonText||"✏️ Edit",i.style.cssText=`\n position: absolute;\n ${this.getButtonPositionStyles()}\n background: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n padding: 8px 12px;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n pointer-events: auto;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n transition: all 0.2s ease;\n z-index: 10001;\n ${this.getCustomButtonStyles()}\n `,i.addEventListener("mouseenter",(()=>{i.style.background="#0056b3",i.style.transform="scale(1.05)"})),i.addEventListener("mouseleave",(()=>{i.style.background="#007bff",i.style.transform="scale(1)"})),i.addEventListener("click",(i=>t(this,void 0,void 0,(function*(){i.preventDefault(),i.stopPropagation(),yield this.openEditor(e)})))),i}getButtonPositionStyles(){const e="10px";switch(this.options.editButtonPosition||"top-right"){case"top-left":return`top: ${e}; left: ${e};`;case"top-right":default:return`top: ${e}; right: ${e};`;case"bottom-left":return`bottom: ${e}; left: ${e};`;case"bottom-right":return`bottom: ${e}; right: ${e};`}}getCustomButtonStyles(){return this.options.editButtonStyle?Object.entries(this.options.editButtonStyle).map((([e,t])=>`${this.camelToKebab(e)}: ${t};`)).join(" "):""}getOverlayStyles(){return this.options.overlayStyle?Object.entries(this.options.overlayStyle).map((([e,t])=>`${this.camelToKebab(e)}: ${t};`)).join(" "):""}camelToKebab(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}addClickToEdit(e,i){e.style.cursor="pointer",e.style.pointerEvents="auto",e.addEventListener("click",(n=>t(this,void 0,void 0,(function*(){n.target===e&&(n.preventDefault(),n.stopPropagation(),yield this.openEditor(i))})))),e.addEventListener("mouseenter",(()=>{e.style.backgroundColor="rgba(0, 123, 255, 0.1)",e.style.border="2px dashed #007bff"})),e.addEventListener("mouseleave",(()=>{e.style.backgroundColor="transparent",e.style.border="none"}))}createEditorContainer(){const e=new Zo({target:"widgetic-editor-portal",className:"widgetic-editor-modal",zIndex:1e5,clickThrough:!1});const t=document.createElement("div");t.className="widgetic-editor-modal-backdrop",t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("div");return i.className="widgetic-editor-content",i.style.cssText="\n width: 90vw;\n height: 90vh;\n max-width: 1200px;\n max-height: 800px;\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n ",t.appendChild(i),e.mount(t),{container:t,portal:e}}openEditor(e){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(e);if(!t)return void B.warn("No editor session found",{compositionId:e});if(t.isOpen)return void B.debug("Editor already open",{compositionId:e});B.info("Opening composition editor",{compositionId:e});const i=ns(),n=yield i.initializeUISdk(),{container:o,portal:s}=this.createEditorContainer(),r=yield n.mountCompositionEditor(o.querySelector(".widgetic-editor-content"),e,{onSave:t=>this.handleEditorSave(e,t),onClose:()=>this.closeEditor(e),onPreview:t=>this.handleEditorPreview(e,t)}),a=zo().createWidgetController(e);if(t.isOpen=!0,t.editorContainer=o,t.editorInstance=r,t.widgetController=a,t.portal=s,t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="none")}B.info("Composition editor opened successfully",{compositionId:e})}catch(t){B.error("Failed to open editor",{compositionId:e,error:t}),this.showError("Failed to open editor. Please try again.",e)}}))}handleEditorSave(e,i){return t(this,void 0,void 0,(function*(){try{B.info("Saving composition changes",{compositionId:e,data:i});const t=this.sessions.get(e);(null==t?void 0:t.widgetController)&&(yield t.widgetController.updateConfig(i),yield t.widgetController.refresh()),yield this.closeEditor(e),B.info("Composition saved successfully",{compositionId:e})}catch(t){B.error("Failed to save composition",{compositionId:e,error:t}),this.showError("Failed to save changes. Please try again.",e)}}))}handleEditorPreview(e,i){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(e);(null==t?void 0:t.widgetController)&&(yield t.widgetController.callFunction("preview",i))}catch(t){B.warn("Preview update failed",{compositionId:e,error:t})}}))}closeEditor(e){return t(this,void 0,void 0,(function*(){const t=this.sessions.get(e);if(t&&t.isOpen)try{if(t.editorInstance&&t.editorContainer){const e=ns().getInstance();e&&(yield e.unmountCompositionEditor(t.editorContainer))}if(t.portal&&t.portal.destroy(),t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="block")}t.isOpen=!1,t.editorContainer=void 0,t.editorInstance=void 0,t.portal=void 0,B.info("Editor closed",{compositionId:e})}catch(t){B.error("Error closing editor",{compositionId:e,error:t})}}))}showError(e,t){const i=document.createElement("div");i.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n background: #dc3545;\n color: white;\n padding: 12px 16px;\n border-radius: 4px;\n z-index: 100001;\n font-size: 14px;\n max-width: 300px;\n ",i.textContent=e,document.body.appendChild(i),setTimeout((()=>{i.parentNode&&i.parentNode.removeChild(i)}),5e3)}removeOverlay(e){const t=this.sessions.get(e);t&&(t.isOpen&&this.closeEditor(e),t.overlay&&t.overlay.parentNode&&t.overlay.parentNode.removeChild(t.overlay),t.portal&&t.portal.destroy(),this.sessions.delete(e),B.debug("Editor overlay removed",{compositionId:e}))}isEditorOpen(e){var t;return(null===(t=this.sessions.get(e))||void 0===t?void 0:t.isOpen)||!1}getActiveSessions(){return Array.from(this.sessions.keys())}cleanup(){for(const e of this.sessions.keys())this.removeOverlay(e);B.debug("Editor overlay cleanup complete")}}let ss=null;function rs(e){return ss||(ss=new os(e)),ss}class as{constructor(e={}){this.options=e,this.instances=new Map,this.widgetElements=new Map,this.widgetConfigs=new Map,this.fullscreenListeners=new Map,this.keyboardListeners=new Map,this.options=Object.assign({enableFullscreen:!0,enableOverlay:!0,enablePopup:!0,defaultOverlayZIndex:5e4,defaultPopupFeatures:"width=800,height=600,scrollbars=yes,resizable=yes"},e),this.setupGlobalKeyHandlers()}initializeWidget(e,t,i){const n={mode:t.displayMode||"inline",isFullscreen:!1,isOverlay:!1,isPopup:!1};return this.instances.set(e,n),this.widgetElements.set(e,i),this.widgetConfigs.set(e,t),this.setupDisplayMode(e,t,i),n}setupDisplayMode(e,t,i){const{displayMode:n}=t;switch(n){case"fullscreen":this.setupFullscreenMode(e,t,i);break;case"overlay":case"modal":this.setupOverlayMode(e,t,i);break;case"popup":this.setupPopupMode(e,t,i)}}setupFullscreenMode(e,t,i){var n;if(!this.options.enableFullscreen||!(null===(n=t.fullscreen)||void 0===n?void 0:n.enabled))return;const o=t.fullscreen.trigger||"click";"manual"!==o&&this.addFullscreenTrigger(e,i,o),t.fullscreen.showControls&&this.addFullscreenControls(e,i)}setupOverlayMode(e,t,i){var n;if(!this.options.enableOverlay||!(null===(n=t.overlay)||void 0===n?void 0:n.enabled))return;const o=t.overlay.trigger||"click";"auto"===o?setTimeout((()=>this.showOverlay(e)),100):"manual"!==o&&this.addOverlayTrigger(e,i,o)}setupPopupMode(e,t,i){var n;if(!this.options.enablePopup||!(null===(n=t.popup)||void 0===n?void 0:n.enabled))return;const o=t.popup.trigger||"click";"manual"!==o&&this.addPopupTrigger(e,i,o)}enterFullscreen(e){return t(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&!t.isFullscreen)try{const i=this.getWidgetElement(e);if(!i)throw new Error(`Widget element not found: ${e}`);const n=es({target:"widgetic-fullscreen",zIndex:100001,className:"fullscreen-widget"}),o=document.createElement("div");o.className="widgetic-fullscreen-container",o.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #000;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 100001;\n ",t.originalStyle=i.style.cssText;const s=document.createComment(`widgetic-fullscreen-placeholder-${e}`);i.parentNode&&(i.parentNode.replaceChild(s,i),t.originalPlaceholder=s),i.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100vw;\n max-height: 100vh;\n border: none;\n ",o.appendChild(i);const r=this.createExitButton((()=>this.exitFullscreen(e)));if(o.appendChild(r),n.mount(o),t.isFullscreen=!0,t.overlayPortal=n,t.fullscreenElement=o,this.setupFullscreenKeyHandler(e),document.documentElement.requestFullscreen)try{yield document.documentElement.requestFullscreen()}catch(e){B.warn("Native fullscreen failed, using CSS fullscreen",{error:e})}B.info("Widget entered fullscreen mode",{widgetId:e})}catch(t){throw B.error("Failed to enter fullscreen",{widgetId:e,error:t}),t}}))}exitFullscreen(e){return t(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&t.isFullscreen)try{const i=this.getWidgetElement(e);i&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(i,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(i.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),document.fullscreenElement&&document.exitFullscreen&&(yield document.exitFullscreen()),t.isFullscreen=!1,t.overlayPortal=void 0,t.fullscreenElement=void 0,this.removeFullscreenKeyHandler(e),B.info("Widget exited fullscreen mode",{widgetId:e})}catch(t){throw B.error("Failed to exit fullscreen",{widgetId:e,error:t}),t}}))}showOverlay(e){return t(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&!t.isOverlay)try{const i=this.getWidgetConfig(e),n=null==i?void 0:i.overlay;if(!n)throw new Error(`No overlay configuration for widget: ${e}`);const o=es({target:"widgetic-overlay",zIndex:n.zIndex||this.options.defaultOverlayZIndex,className:"overlay-widget"}),s=this.createOverlayContainer(e,n),r=this.getWidgetElement(e);if(r){t.originalStyle=r.style.cssText;const i=document.createComment(`widgetic-overlay-placeholder-${e}`);r.parentNode&&(r.parentNode.replaceChild(i,r),t.originalPlaceholder=i),this.styleOverlayWidget(r,n);s.querySelector(".overlay-content").appendChild(r)}o.mount(s),t.isOverlay=!0,t.overlayPortal=o,this.setupOverlayCloseHandlers(e,s,n),B.info("Widget shown in overlay mode",{widgetId:e})}catch(t){throw B.error("Failed to show overlay",{widgetId:e,error:t}),t}}))}hideOverlay(e){return t(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&t.isOverlay)try{const i=this.getWidgetElement(e);i&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(i,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(i.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),t.isOverlay=!1,t.overlayPortal=void 0,this.removeOverlayKeyHandler(e),B.info("Widget overlay hidden",{widgetId:e})}catch(t){throw B.error("Failed to hide overlay",{widgetId:e,error:t}),t}}))}openPopup(e){return t(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(!t||t.isPopup)return(null==t?void 0:t.popupWindow)||null;try{const i=this.getWidgetConfig(e),n=null==i?void 0:i.popup;if(!n)throw new Error(`No popup configuration for widget: ${e}`);const o=this.buildPopupFeatures(n),s=this.generatePopupUrl(e),r=window.open(s,n.target||`widgetic_${e}`,o);if(!r)throw new Error("Popup blocked by browser");return t.isPopup=!0,t.popupWindow=r,this.monitorPopupClose(e,r),B.info("Widget opened in popup",{widgetId:e}),r}catch(t){throw B.error("Failed to open popup",{widgetId:e,error:t}),t}}))}closePopup(e){const t=this.instances.get(e);if(t&&t.isPopup&&t.popupWindow)try{t.popupWindow.close(),t.isPopup=!1,t.popupWindow=null,B.info("Widget popup closed",{widgetId:e})}catch(t){B.error("Failed to close popup",{widgetId:e,error:t})}}getDisplayState(e){return this.instances.get(e)||null}cleanup(e){const t=this.instances.get(e);t&&(t.isFullscreen&&this.exitFullscreen(e),t.isOverlay&&this.hideOverlay(e),t.isPopup&&this.closePopup(e),this.instances.delete(e),this.removeFullscreenKeyHandler(e),this.removeOverlayKeyHandler(e))}cleanupAll(){for(const e of this.instances.keys())this.cleanup(e)}getWidgetElement(e){return this.widgetElements.has(e)?this.widgetElements.get(e):document.querySelector(`[data-widget-id="${e}"]`)||document.querySelector(`[data-widgetic-id="${e}"]`)||document.querySelector(`[composition-id="${e}"]`)||null}getWidgetConfig(e){return this.widgetConfigs.get(e)||null}addFullscreenTrigger(e,t,i){const n=()=>this.enterFullscreen(e);switch(i){case"click":t.addEventListener("click",n);break;case"double-click":t.addEventListener("dblclick",n);break;case"hover":t.addEventListener("mouseenter",n)}}addOverlayTrigger(e,t,i){const n=()=>this.showOverlay(e);switch(i){case"click":t.addEventListener("click",n);break;case"hover":t.addEventListener("mouseenter",n)}}addPopupTrigger(e,t,i){const n=()=>this.openPopup(e);"click"===i&&t.addEventListener("click",n)}createExitButton(e){const t=document.createElement("button");return t.className="widgetic-exit-fullscreen",t.innerHTML="✕",t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",o=t.height||"100%";i&&(t.overlayWidth||t.overlayHeight)&&(n=t.overlayWidth||n,o=t.overlayHeight||o),e.style.cssText=`\n width: ${n};\n height: ${o};\n border: none;\n display: block;\n `,i&&t.overlayResize&&this.applyOverlayResizeMode(e,t.overlayResize)}applyOverlayResizeMode(e,t){if(e.parentElement)switch(t){case"fill-width":e.style.width="100%",e.style.height="auto",e.style.aspectRatio="auto";break;case"fill-height":e.style.height="100%",e.style.width="auto",e.style.aspectRatio="auto";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="100%";break;case"fixed-width":e.style.height="100%";break;case"allow-scale-down":e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.objectFit="contain";break;case"fill":e.style.width="100%",e.style.height="100%",e.style.objectFit="cover"}}buildPopupFeatures(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.centerScreen&&t.push("location=center"),e.allowResize&&t.push("resizable=yes"),e.showToolbar&&t.push("toolbar=yes"),t.length>0?t.join(","):this.options.defaultPopupFeatures||""}generatePopupUrl(e){return"about:blank"}setupGlobalKeyHandlers(){"undefined"!=typeof document&&document.addEventListener("keydown",(e=>{if("Escape"===e.key)for(const[e,t]of this.instances)t.isFullscreen?this.exitFullscreen(e):t.isOverlay&&this.hideOverlay(e)}))}setupFullscreenKeyHandler(e){const t=t=>{"Escape"===t.key&&this.exitFullscreen(e)};this.keyboardListeners.set(`${e}-fullscreen`,t),document.addEventListener("keydown",t)}removeFullscreenKeyHandler(e){const t=this.keyboardListeners.get(`${e}-fullscreen`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-fullscreen`))}setupOverlayCloseHandlers(e,t,i){if(i.closeOnBackdropClick&&t.addEventListener("click",(i=>{i.target===t&&this.hideOverlay(e)})),i.closeOnEscape){const t=t=>{"Escape"===t.key&&this.hideOverlay(e)};this.keyboardListeners.set(`${e}-overlay`,t),document.addEventListener("keydown",t)}}removeOverlayKeyHandler(e){const t=this.keyboardListeners.get(`${e}-overlay`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-overlay`))}monitorPopupClose(e,t){const i=()=>{if(t.closed){const t=this.instances.get(e);t&&(t.isPopup=!1,t.popupWindow=null)}else setTimeout(i,1e3)};setTimeout(i,1e3)}addFullscreenControls(e,t){const i=document.createElement("div");i.className="widgetic-fullscreen-controls",i.style.cssText="\n position: absolute;\n bottom: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.7);\n border-radius: 4px;\n padding: 5px;\n z-index: 1000;\n ";const n=document.createElement("button");n.innerHTML="⛶",n.style.cssText="\n background: none;\n border: none;\n color: white;\n cursor: pointer;\n font-size: 16px;\n ",n.addEventListener("click",(()=>this.enterFullscreen(e))),i.appendChild(n),t.style.position="relative",t.appendChild(i)}}let ds=null;const cs={mobile:480,tablet:768,desktop:1024},ls={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},us={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,DEFAULT_MOBILE_BREAKPOINT:768,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class hs{constructor(e={enabled:!0}){var t;this.isEnabled=!1,this.activeOverlay=null,this.exitIntentListener=null,this.scrollListener=null,this.engagementStartTime=null,this.timeoutId=null,this.config=Object.assign(Object.assign({exitIntentEnabled:!0,scrollTriggerEnabled:!0,timeTriggerEnabled:!0,engagementThresholdEnabled:!0,externalTriggerEnabled:!0},e),{enabled:null===(t=e.enabled)||void 0===t||t}),this.config.breakpoints||(this.config.breakpoints={useBreakpoints:!1,mobile:cs.mobile,tablet:cs.tablet,desktop:cs.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),B.debug("OverlayManager initialized",{config:this.config})}initializeEventListeners(){"undefined"!=typeof window&&(this.config.exitIntentEnabled&&this.initializeExitIntent(),this.config.scrollTriggerEnabled&&this.initializeScrollTrigger(),this.config.engagementThresholdEnabled&&this.startEngagementTracking())}initializeExitIntent(){"undefined"!=typeof document&&(this.exitIntentListener=e=>{e.clientY<=0&&e.movementY<0&&this.emitOverlayTrigger("exit-intent",{mousePosition:{x:e.clientX,y:e.clientY},movementY:e.movementY})},document.addEventListener("mouseleave",this.exitIntentListener))}initializeScrollTrigger(){"undefined"!=typeof window&&(this.scrollListener=()=>{const e=window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100;e>=25&&e<30?this.emitOverlayTrigger("scroll-25",{scrollPercentage:e}):e>=50&&e<55?this.emitOverlayTrigger("scroll-50",{scrollPercentage:e}):e>=75&&e<80&&this.emitOverlayTrigger("scroll-75",{scrollPercentage:e})},window.addEventListener("scroll",this.scrollListener,{passive:!0}))}startEngagementTracking(){this.engagementStartTime=Date.now();setInterval((()=>{if(!this.engagementStartTime)return;const e=Date.now()-this.engagementStartTime;e>=3e4?this.emitOverlayTrigger("engagement-30s",{engagementTimeMs:e}):e>=6e4?this.emitOverlayTrigger("engagement-1m",{engagementTimeMs:e}):e>=12e4&&this.emitOverlayTrigger("engagement-2m",{engagementTimeMs:e})}),1e4)}showOverlay(e){if(this.isEnabled){this.activeOverlay&&(B.debug("Overlay already active, closing previous"),this.hideOverlay());try{const t=this.validateOverlayConfig(e),i=this.createOverlayElement(t);document.body.appendChild(i),this.activeOverlay=i,setTimeout((()=>{i.classList.add("widgetic-overlay-visible")}),50),t.autoClose&&t.autoClose>0&&(this.timeoutId=window.setTimeout((()=>{this.hideOverlay()}),t.autoClose)),B.info("Overlay displayed",{displayMode:t.displayMode,animation:t.animation,autoClose:t.autoClose}),this.emitOverlayEvent("overlay-shown",t)}catch(t){B.error("Failed to show overlay",{error:t,config:e})}}else B.warn("Overlay manager is disabled")}validateOverlayConfig(e){const t=Object.assign({},e);return t.displayMode&&Object.values(ls).includes(t.displayMode)||(t.displayMode=ls.MANUAL),t.animation&&us.SUPPORTED_ANIMATIONS.includes(t.animation)||(t.animation=us.DEFAULT_ANIMATION,B.debug("Using default animation for overlay",{provided:e.animation,defaultUsed:us.DEFAULT_ANIMATION})),t.delay||(t.delay=us.DEFAULT_DELAY_MS),void 0===t.showBackdrop&&(t.showBackdrop=!0),t}hideOverlay(){if(!this.activeOverlay)return;this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.activeOverlay;e.classList.remove("widgetic-overlay-visible"),e.classList.add("widgetic-overlay-hiding"),setTimeout((()=>{e.parentNode&&e.parentNode.removeChild(e)}),300),this.activeOverlay=null,B.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||us.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close" aria-label="Close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&i.addEventListener("click",(()=>this.hideOverlay())),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const n=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",n))};return document.addEventListener("keydown",n),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||cs.mobile;return`\n /* Mobile responsive styles */\n @media (max-width: ${t}px) {\n .widgetic-overlay-content {\n max-width: 95vw;\n margin: 10px;\n }\n \n .widgetic-overlay-body {\n padding: 15px;\n }\n }\n \n /* Tablet responsive styles */\n @media (min-width: ${t+1}px) and (max-width: ${e.tablet||cs.tablet}px) {\n .widgetic-overlay-content {\n max-width: 90vw;\n margin: 15px;\n }\n \n .widgetic-overlay-body {\n padding: 18px;\n }\n }\n `}addOverlayStyles(){const e="widgetic-overlay-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .widgetic-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n }\n \n .widgetic-overlay-backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n \n .widgetic-overlay-visible {\n opacity: 1;\n }\n \n .widgetic-overlay-hiding {\n opacity: 0;\n }\n \n .widgetic-overlay-content {\n position: relative;\n background: white;\n border-radius: 8px;\n max-width: 90vw;\n max-height: 90vh;\n overflow: auto;\n transition: all 0.3s ease;\n }\n \n .widgetic-overlay-close {\n position: absolute;\n top: 10px;\n right: 15px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n z-index: 1;\n color: #6b7280;\n line-height: 1;\n padding: 4px;\n }\n \n .widgetic-overlay-close:hover {\n color: #374151;\n }\n \n .widgetic-overlay-body {\n padding: 20px;\n }\n \n /* Fade animation (default) */\n .widgetic-overlay-fade .widgetic-overlay-content {\n transform: scale(0.95);\n opacity: 0;\n }\n \n .widgetic-overlay-fade.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Slide animations */\n .widgetic-overlay-slide-up .widgetic-overlay-content {\n transform: translateY(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-up.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-down .widgetic-overlay-content {\n transform: translateY(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-down.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-left .widgetic-overlay-content {\n transform: translateX(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-left.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-right .widgetic-overlay-content {\n transform: translateX(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-right.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n /* Zoom animation */\n .widgetic-overlay-zoom .widgetic-overlay-content {\n transform: scale(0.7);\n opacity: 0;\n }\n \n .widgetic-overlay-zoom.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Bounce animation */\n .widgetic-overlay-bounce .widgetic-overlay-content {\n transform: scale(0.3);\n opacity: 0;\n transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n \n .widgetic-overlay-bounce.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Mobile responsive */\n ${this.generateResponsiveCSS()}\n `,document.head.appendChild(t)}emitOverlayTrigger(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-trigger",{detail:{triggerType:e,data:t,timestamp:(new Date).toISOString()}}))}emitOverlayEvent(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-event",{detail:{eventType:e,data:t,timestamp:(new Date).toISOString()}}))}triggerOverlay(e,t={}){const i=Object.assign({displayMode:e,animation:us.DEFAULT_ANIMATION,delay:us.DEFAULT_DELAY_MS,content:"Default overlay content"},t);i.delay&&i.delay>0?setTimeout((()=>{this.showOverlay(i)}),i.delay):this.showOverlay(i)}isOverlayActive(){return null!==this.activeOverlay}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),this.isEnabled=this.config.enabled,B.debug("OverlayManager config updated",{config:this.config})}destroy(){this.activeOverlay&&this.hideOverlay(),this.exitIntentListener&&document.removeEventListener("mouseleave",this.exitIntentListener),this.scrollListener&&window.removeEventListener("scroll",this.scrollListener),this.timeoutId&&clearTimeout(this.timeoutId),B.debug("OverlayManager destroyed")}}let gs=null;class ps{constructor(e={}){this.metrics=[],this.webVitals={},this.widgetMetrics=new Map,this.isTracking=!1,this.config=Object.assign({enableTracking:dn.ENABLE_PERFORMANCE_TRACKING,enableWebVitals:!0,enableWidgetMetrics:!0,enableResourceTracking:!0,enableBudgetMonitoring:!0,sampleRate:dn.PERFORMANCE_SAMPLE_RATE,maxMetricsBuffer:dn.MAX_METRICS_BUFFER,axiomApiEndpoint:dn.AXIOM_API_ENDPOINT,statsigApiEndpoint:dn.STATSIG_API_ENDPOINT,budgets:[{metric:"lcp",threshold:dn.LCP_THRESHOLD,warningThreshold:dn.LCP_WARNING_THRESHOLD,enabled:!0},{metric:"fid",threshold:dn.FID_THRESHOLD,warningThreshold:dn.FID_WARNING_THRESHOLD,enabled:!0},{metric:"cls",threshold:dn.CLS_THRESHOLD,warningThreshold:dn.CLS_WARNING_THRESHOLD,enabled:!0},{metric:"widget-load",threshold:dn.WIDGET_LOAD_THRESHOLD,warningThreshold:dn.WIDGET_LOAD_WARNING_THRESHOLD,enabled:!0},{metric:"bundle-size",threshold:dn.BUNDLE_SIZE_THRESHOLD,warningThreshold:dn.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 n=i.loadEndTime-i.loadStartTime;this.recordMetric("widget-load",n,{compositionId:e,success:t,isLazyLoaded:i.isLazyLoaded,bundleSize:i.bundleSize}),this.checkBudget("widget-load",n),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 n={name:e,value:t,timestamp:performance.now(),metadata:i};this.metrics.push(n),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,n){const o={type:"performance-budget-alert",metric:e,value:t,threshold:i,level:n,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 t(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(e){return t(this,void 0,void 0,(function*(){yield fetch(this.config.reportingEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}))}reportToAxiom(e){return t(this,void 0,void 0,(function*(){const t=this.config.axiomApiEndpoint||"https://api.axiom.co/v1";yield fetch(`${t}/datasets/${this.config.axiomDataset}/ingest`,{method:"POST",headers:{Authorization:`Bearer ${this.config.axiomApiKey}`,"Content-Type":"application/x-ndjson"},body:JSON.stringify(e)+"\n"})}))}reportToStatsig(e){return t(this,void 0,void 0,(function*(){const t=this.config.statsigApiEndpoint||"https://events.statsigapi.net/v1/custom";yield fetch(t,{method:"POST",headers:{"STATSIG-API-KEY":this.config.statsigKey,"Content-Type":"application/json"},body:JSON.stringify({events:[{eventName:"widget_performance",value:e,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 ms=null;function fs(e){return ms||(ms=new ps(e)),ms}class vs{constructor(e={}){this.items=new Map,this.observer=null,this.preloadObserver=null,this.loadingQueue=[],this.activeLoads=0,this.performanceMonitor=fs(),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"),n=(e?this.items.get(e):null)||(i?this.items.get(i):null);n&&(!t.isIntersecting||n.isLoaded||n.isLoading||(n.viewportEntryTime=performance.now(),this.performanceMonitor.recordLazyLoad(n.compositionId,n.viewportEntryTime),this.queueLoad(n)))}}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"),n=(e?this.items.get(e):null)||(i?this.items.get(i):null);!n||n.isPreloaded||n.isLoaded||t.isIntersecting&&this.preloadResources(n)}}register(e,t,i,n={}){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:n.config||{},loadFunction:i,priority:n.priority||5,retryCount:0,isLoading:!1,isLoaded:!1,isPreloaded:!1,resourceUrls:n.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[n,o]of this.items.entries())if(o.compositionId===e){t=n,i=o;break}if(!i)return;this.observer&&this.observer.unobserve(i.element),this.preloadObserver&&this.preloadObserver.unobserve(i.element);const n=this.retryTimeouts.get(t)||this.retryTimeouts.get(i.compositionId);n&&(clearTimeout(n),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 t(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(e){return t(this,void 0,void 0,(function*(){if(!e.isLoading&&!e.isLoaded){e.isLoading=!0,this.activeLoads++,this.performanceMonitor.startWidgetLoad(e.compositionId,{isLazyLoaded:!0,bundleSize:this.estimateBundleSize(e)});try{e.element.classList.add("widgetic-loading"),e.element.classList.remove("widgetic-lazy-loading"),yield e.loadFunction(),e.isLoaded=!0,e.element.classList.remove("widgetic-loading"),e.element.classList.add("widgetic-loaded"),e.element.removeAttribute("data-lazy"),this.observer&&this.observer.unobserve(e.element),this.preloadObserver&&this.preloadObserver.unobserve(e.element),this.performanceMonitor.endWidgetLoad(e.compositionId,!0)}catch(t){if(e.element.classList.add("widgetic-load-error"),this.performanceMonitor.recordWidgetError(e.compositionId,t instanceof Error?t.message:"Load failed"),this.performanceMonitor.endWidgetLoad(e.compositionId,!1),e.retryCount<this.config.retryAttempts){e.retryCount++,this.performanceMonitor.recordWidgetRetry(e.compositionId,`Attempt ${e.retryCount}`);const t=setTimeout((()=>{e.isLoading=!1,this.retryTimeouts.delete(e.compositionId),this.loadItem(e)}),this.config.retryDelay*e.retryCount);this.retryTimeouts.set(e.compositionId,t)}}finally{e.isLoading=!1,this.activeLoads--,this.config.enableProgressiveLoading&&setTimeout((()=>this.processLoadingQueue()),10)}}}))}preloadResources(e){return t(this,void 0,void 0,(function*(){if(e.resourceUrls&&!e.isPreloaded){e.isPreloaded=!0;try{const t=e.resourceUrls.map((e=>this.preloadResource(e)));yield Promise.allSettled(t)}catch(e){}}}))}preloadResource(e){return t(this,void 0,void 0,(function*(){return new Promise(((t,i)=>{const n=document.createElement("link");n.rel="preload",n.href=e,e.endsWith(".js")?n.as="script":e.endsWith(".css")?n.as="style":e.match(/\.(png|jpg|jpeg|gif|webp|svg)$/)?n.as="image":(n.as="fetch",n.setAttribute("crossorigin","anonymous")),n.onload=()=>t(),n.onerror=()=>i(new Error(`Failed to preload ${e}`)),document.head.appendChild(n)}))}))}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(e){const i=this.items.get(e);return i?i.isLoaded?Promise.resolve():new Promise(((e,n)=>{const o=i.loadFunction;i.loadFunction=()=>t(this,void 0,void 0,(function*(){try{yield o(),e()}catch(e){n(e)}})),this.loadItem(i)})):Promise.reject(new Error(`Widget ${e} 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,n=window.innerWidth||document.documentElement.clientWidth;return t.top<i&&t.bottom>0&&t.left<n&&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)),n=this.performanceMonitor.getMetrics().filter((e=>"lazy-load"===e.name)).map((e=>e.value)),o=n.length>0?n.reduce(((e,t)=>e+t),0)/n.length:0,s=e.filter((e=>this.isElementVisible(e.element))),r=s.filter((e=>e.isLoaded)),a=s.length>0?r.length/s.length:0,d=e.filter((e=>e.isPreloaded)),c=e.length>0?d.length/e.length:0;return{totalItems:e.length,loadedItems:t.length,failedItems:i.length,averageLoadTime:o,viewportUtilization:a,preloadSuccess:c}}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 ys=null;class ws{constructor(e={}){this.resources=new Map,this.loadQueue=[],this.activeRequests=0,this.performanceMonitor=fs(),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 t(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 t(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 n={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,n),this.shouldPreload(n,i.preload)?this.preloadResource(n):this.shouldPrefetch(n,i.prefetch)&&setTimeout((()=>this.prefetchResource(n)),this.config.prefetchDelay),n}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(e){return t(this,void 0,void 0,(function*(){if(e.isPreloaded||e.isLoaded)return;const t=performance.now();try{const i=document.createElement("link");i.rel="preload",i.href=e.url,i.as="script"===e.type?"script":"style"===e.type?"style":"font"===e.type?"font":"image"===e.type?"image":"fetch","font"!==e.type&&"fetch"!==e.type||(i.crossOrigin="anonymous"),yield new Promise(((n,o)=>{i.onload=()=>{e.isPreloaded=!0,e.loadTime=performance.now()-t,this.performanceMonitor.recordMetric("preload",e.loadTime,{url:e.url,type:e.type,priority:e.priority}),n()},i.onerror=()=>o(new Error(`Failed to preload ${e.url}`)),document.head.appendChild(i)}))}catch(e){}}))}prefetchResource(e){return t(this,void 0,void 0,(function*(){if(!e.isPrefetched&&!e.isLoaded)try{const t=document.createElement("link");t.rel="prefetch",t.href=e.url,document.head.appendChild(t),e.isPrefetched=!0,this.performanceMonitor.recordMetric("prefetch",1,{url:e.url,type:e.type,priority:e.priority})}catch(e){}}))}loadResources(e){return t(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]})),n=[];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))));n.push(...o)}return n}))}loadResource(e){return t(this,void 0,void 0,(function*(){if(e.isLoaded)return e;const t=performance.now();try{const i=yield fetch(e.url);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);e.isLoaded=!0,e.loadTime=performance.now()-t,e.size=parseInt(i.headers.get("content-length")||"0"),this.performanceMonitor.recordMetric("resource-fetch",e.loadTime,{url:e.url,type:e.type,size:e.size,priority:e.priority})}catch(e){throw e}return e}))}loadBundleWithSplitting(e,i){return t(this,void 0,void 0,(function*(){if(!this.config.enableBundleSplitting)return this.loadBundle(e,i);try{const t=e.replace(/\.js$/,"-core.js");yield this.loadResource(this.registerResource(t,"script",{priority:"critical",compositionId:i}));const n=e.replace(/\.js$/,"-widget.js");yield this.loadResource(this.registerResource(n,"script",{priority:"high",compositionId:i}));const o=e.replace(/\.js$/,"-features.js");this.prefetchResource(this.registerResource(o,"script",{priority:"medium",compositionId:i}))}catch(t){return this.loadBundle(e,i)}}))}loadBundle(e,i){return t(this,void 0,void 0,(function*(){yield this.loadResource(this.registerResource(e,"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)),n=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),r=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:n.length,cachedResources:o.length,totalSize:s,averageLoadTime:r,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 bs=null;function Is(e){return bs||(bs=new ws(e)),bs}class Ts{constructor(e={}){this.rateLimitTracker=new Map,this.globalRateLimit={count:0,windowStart:Date.now(),violations:0},this.behaviorTracker=new Map,this.blockedInstances=new Set,this.suspiciousInstances=new Set,this.cleanupInterval=null,this.config=Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0,maxTextLength:1e5,maxUpdatesPerMinute:60,maxGlobalUpdatesPerMinute:1e3,suspiciousActivityThreshold:5},e),this.startCleanupTask(),B.info("[SecurityManager] Initialized with config:",this.config)}static getInstance(e){return Ts.instance||(Ts.instance=new Ts(e)),Ts.instance}validateTextFieldUpdate(e,t,i,n){const o=`${e}:${t}`;if(this.blockedInstances.has(e))return{allowed:!1,reason:"Instance blocked due to security violations",severity:"high"};if(i.length>this.config.maxTextLength)return this.recordViolation(e,"text_length_exceeded"),{allowed:!1,reason:`Text length exceeds maximum (${this.config.maxTextLength} characters)`,severity:"medium"};if(this.config.enableRateLimit){const t=this.checkRateLimit(o);if(!t.allowed)return this.recordViolation(e,"rate_limit_exceeded"),t}if(this.config.enableBotDetection){const t=this.analyzeBehavior(e,i);if(!t.allowed)return this.recordViolation(e,"suspicious_behavior"),t}let s=i;if(this.config.enableSanitization){const t=this.sanitizeInput(i);if(!t.allowed)return this.recordViolation(e,"malicious_content"),t;s=t.sanitizedText||i}const r=this.analyzeContentPatterns(i);return r.allowed?{allowed:!0,sanitizedText:s}:(this.recordViolation(e,"suspicious_pattern"),r)}sanitizeInput(e){try{const t=/javascript:/gi,i=/\bon\w+\s*=/gi,n=/data:text\/html/gi;if(/<script[^>]*>[\s\S]*?<\/script>/gi.test(e)||t.test(e)||i.test(e)||n.test(e))return{allowed:!1,reason:"Potentially malicious content detected",severity:"high"};let o=e.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/javascript:/gi,"").replace(/\bon\w+\s*=/gi,"").replace(/data:text\/html/gi,"data:text/plain");o=this.sanitizeLinks(o);const s=(o.match(/<[a-z][^>]*>/gi)||[]).length,r=o.replace(/<[^>]+>/g,"").length;if(s>0&&r>0){if(s/r>.1)return{allowed:!1,reason:"Excessive HTML content detected",severity:"medium"}}return{allowed:!0,sanitizedText:o}}catch(e){return B.warn("[SecurityManager] Sanitization error:",e),{allowed:!1,reason:"Input sanitization failed",severity:"medium"}}}sanitizeLinks(e){try{const t=/<a\b(?![^>]*\bhref\s*=)[^>]*>/gi,i=e.replace(/<a\b(?![^>]*\bhref\s*=)[^>]*>([\s\S]*?)<\/a>/gi,"$1").replace(t,""),n=/<a\s+([^>]*href\s*=\s*["'][^"']*["'][^>]*)>/gi;return i.replace(n,((e,t)=>{const i=t.match(/href\s*=\s*["']([^"']*)["']/i);if(!i)return"";const n=i[1],o=["javascript:","data:","vbscript:","file:","ftp:"];for(const e of o)if(n.toLowerCase().startsWith(e))return"";const s=this.isExternalLink(n);let r=t.replace(/\btarget\s*=\s*["'][^"']*["']/gi,"").replace(/\brel\s*=\s*["'][^"']*["']/gi,"").replace(/\bon\w+\s*=\s*["'][^"']*["']/gi,"").trim();return r+=s?' target="_blank" rel="nofollow noopener noreferrer"':' rel="noopener"',`<a ${r}>`}))}catch(t){return B.warn("[SecurityManager] Link sanitization error:",t),e}}isExternalLink(e){try{if(e.startsWith("//"))return!0;if(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("#")||e.startsWith("?"))return!1;if(e.includes("://")){const t=new URL(e),i="undefined"!=typeof window?window.location.hostname:"";return t.hostname!==i}return!1}catch(e){return!0}}checkRateLimit(e){const t=Date.now(),i=this.rateLimitTracker.get(e)||{count:0,windowStart:t,violations:0};return t-i.windowStart>=6e4&&(i.count=0,i.windowStart=t),i.count++,this.rateLimitTracker.set(e,i),i.count>this.config.maxUpdatesPerMinute?(i.violations++,{allowed:!1,reason:"Rate limit exceeded for this widget",severity:"medium"}):(t-this.globalRateLimit.windowStart>=6e4&&(this.globalRateLimit.count=0,this.globalRateLimit.windowStart=t),this.globalRateLimit.count++,this.globalRateLimit.count>this.config.maxGlobalUpdatesPerMinute?(this.globalRateLimit.violations++,{allowed:!1,reason:"Global rate limit exceeded",severity:"high"}):{allowed:!0})}analyzeBehavior(e,t){const i=Date.now(),n=this.behaviorTracker.get(e)||{updateCount:0,averageInterval:0,suspiciousPatterns:0,firstSeen:i,lastSeen:i,textLengthVariations:[],updateIntervals:[]},o=i-n.lastSeen;if(n.updateIntervals.push(o),n.textLengthVariations.push(t.length),n.updateIntervals.length>20&&(n.updateIntervals=n.updateIntervals.slice(-20),n.textLengthVariations=n.textLengthVariations.slice(-20)),n.updateCount++,n.lastSeen=i,n.updateIntervals.length>1){const e=n.updateIntervals.filter((e=>e>0));n.averageInterval=e.reduce(((e,t)=>e+t),0)/e.length}let s=0;if(n.updateIntervals.length>=5){const e=n.updateIntervals.slice(-5);this.calculateVariance(e)<100&&s++}if(n.updateIntervals.length>=3){n.updateIntervals.slice(-3).every((e=>e<100&&e>0))&&s++}if(n.textLengthVariations.length>=5){const e=n.textLengthVariations.slice(-5);1===new Set(e).size&&e[0]>10&&s++}const r=i-n.firstSeen;if(r>0&&n.updateCount>50){n.updateCount/(r/1e3)>2&&s++}if(n.suspiciousPatterns=s,this.behaviorTracker.set(e,n),s>=this.config.suspiciousActivityThreshold){this.suspiciousInstances.add(e);const t=this.rateLimitTracker.get(`${e}:suspicious`);return t&&t.violations>3?(this.blockedInstances.add(e),{allowed:!1,reason:"Instance blocked due to repeated suspicious behavior",severity:"high"}):{allowed:!1,reason:"Suspicious behavior pattern detected",severity:"medium"}}return{allowed:!0}}analyzeContentPatterns(e){if((e.match(/https?:\/\/[^\s]+/g)||[]).length>=5)return{allowed:!1,reason:"Spam-like content pattern detected",severity:"medium"};const t=[/(.)\1{50,}/g,/\b(buy|sale|discount|offer|free|winner|congratulations|urgent|click here)\b.*\b(buy|sale|discount|offer|free|winner|congratulations|urgent|click here)\b/gi,/\$[0-9]{3,}/g];for(const i of t)if(i.test(e))return{allowed:!1,reason:"Spam-like content pattern detected",severity:"medium"};const i=[/\bunion\s+select\b/gi,/\bdrop\s+table\b/gi,/\binsert\s+into\b/gi,/\bdelete\s+from\b/gi,/<iframe[^>]*src/gi,/<object[^>]*data/gi];for(const t of i)if(t.test(e))return{allowed:!1,reason:"Potential injection attempt detected",severity:"high"};return{allowed:!0}}recordViolation(e,t){B.warn(`[SecurityManager] Security violation: ${t}`,{instanceId:e});const i=`${e}:violations`,n=this.rateLimitTracker.get(i)||{count:0,windowStart:Date.now(),violations:0};n.violations++,this.rateLimitTracker.set(i,n),n.violations>=10&&(this.blockedInstances.add(e),B.warn(`[SecurityManager] Blocked instance due to repeated violations: ${e}`)),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-violation",{detail:{instanceId:e,violationType:t,timestamp:Date.now()}}))}calculateVariance(e){if(e.length<2)return 0;const t=e.reduce(((e,t)=>e+t))/e.length;return e.map((e=>Math.pow(e-t,2))).reduce(((e,t)=>e+t))/e.length}startCleanupTask(){this.cleanupInterval=setInterval((()=>{this.cleanup()}),3e5)}cleanup(){const e=Date.now(),t=18e5;for(const[i,n]of this.rateLimitTracker.entries())e-n.windowStart>t&&this.rateLimitTracker.delete(i);for(const[i,n]of this.behaviorTracker.entries())e-n.lastSeen>t&&this.behaviorTracker.delete(i);B.debug("[SecurityManager] Cleanup completed",{rateLimitEntries:this.rateLimitTracker.size,behaviorEntries:this.behaviorTracker.size,blockedInstances:this.blockedInstances.size})}isInstanceBlocked(e){return this.blockedInstances.has(e)}isInstanceSuspicious(e){return this.suspiciousInstances.has(e)}unblockInstance(e){this.blockedInstances.delete(e),this.suspiciousInstances.delete(e),this.behaviorTracker.delete(e);for(const t of this.rateLimitTracker.keys())t.startsWith(e)&&this.rateLimitTracker.delete(t);B.info(`[SecurityManager] Unblocked instance: ${e}`)}getSecurityStats(){return{blockedInstances:this.blockedInstances.size,suspiciousInstances:this.suspiciousInstances.size,rateLimitEntries:this.rateLimitTracker.size,behaviorEntries:this.behaviorTracker.size,globalRateLimit:this.globalRateLimit,config:this.config}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),B.info("[SecurityManager] Configuration updated:",e)}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.rateLimitTracker.clear(),this.behaviorTracker.clear(),this.blockedInstances.clear(),this.suspiciousInstances.clear(),B.info("[SecurityManager] Destroyed")}}function ks(e){return Ts.getInstance(e)}var Ss=Object.freeze({__proto__:null,SecurityManager:Ts,getSecurityManager:ks});class Es{constructor(e){this.intersectionObserver=null,this.isInViewport=!0,this.hasBeenInViewport=!1,this.scrollListener=null,this.lastScrollY=0,this.scrollDistance=0,this.isTriggered=!1,this.debounceTimer=null,this.rafId=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,totalScrollDistance:0,viewportChanges:0},this.widgetId=e.widgetId,this.element=e.element,this.type=e.type,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,threshold:.1,distance:100,direction:"down",debounce:100}}initialize(){this.config.enabled&&(B.debug("Initializing ScrollTrigger",{widgetId:this.widgetId,type:this.type,config:this.config}),this.lastScrollY=window.scrollY,"viewport"===this.type?this.initializeViewportDetection():"distance"===this.type&&this.initializeScrollDistance())}initializeViewportDetection(){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:this.config.threshold||.1,rootMargin:"0px"}),this.intersectionObserver.observe(this.element),B.debug("Viewport detection initialized",{widgetId:this.widgetId,threshold:this.config.threshold})}initializeScrollDistance(){this.scrollListener=this.debounce(this.handleScrollDistance.bind(this),this.config.debounce||100),window.addEventListener("scroll",this.scrollListener,{passive:!0}),B.debug("Scroll distance tracking initialized",{widgetId:this.widgetId,distance:this.config.distance})}handleIntersection(e){if(this.isDestroyed)return;const t=e[e.length-1];if(!t)return;const i=this.isInViewport;if(this.isInViewport=t.isIntersecting,t.isIntersecting&&(this.hasBeenInViewport=!0),this.stats.viewportChanges++,B.debug("Viewport intersection changed",{widgetId:this.widgetId,isIntersecting:this.isInViewport,intersectionRatio:t.intersectionRatio}),i&&!this.isInViewport){if(!this.hasBeenInViewport)return;this.triggerActivated("scroll-out-of-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}else!i&&this.isInViewport&&this.triggerDeactivated("scroll-back-in-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}observeElement(e){!this.isDestroyed&&"viewport"===this.type&&this.intersectionObserver&&e!==this.element&&(this.intersectionObserver.unobserve(this.element),this.element=e,this.intersectionObserver.observe(e),B.debug("ScrollTrigger now watching another element",{widgetId:this.widgetId}))}handleScrollDistance(){this.isDestroyed||(this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame((()=>{const e=window.scrollY,t=e-this.lastScrollY;this.stats.totalScrollDistance+=Math.abs(t);const i=t>0,n=t<0;"down"===this.config.direction&&i?this.scrollDistance+=t:("up"===this.config.direction&&n||"any"===this.config.direction)&&(this.scrollDistance+=Math.abs(t));const o=this.config.distance||100;!this.isTriggered&&this.scrollDistance>=o&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{scrollDistance:this.scrollDistance,direction:i?"down":"up",scrollY:e})),this.lastScrollY=e,B.debug("Scroll distance updated",{widgetId:this.widgetId,scrollDistance:this.scrollDistance,requiredDistance:o,isTriggered:this.isTriggered})})))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),B.debug("Scroll trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}triggerDeactivated(e,t){const i=new CustomEvent("widgetic:trigger-deactivated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),B.debug("Scroll trigger deactivated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return i=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e()}),t)}}updateConfig(e){if(this.isDestroyed)return;const t=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0!==e.threshold&&"viewport"===this.type&&(this.destroy(),this.isDestroyed=!1,this.initializeViewportDetection()),void 0!==e.distance&&"distance"===this.type&&(this.scrollDistance=0,this.isTriggered=!1),B.debug("ScrollTrigger config updated",{widgetId:this.widgetId,oldConfig:t,newConfig:this.config})}reset(){this.isDestroyed||(this.scrollDistance=0,this.isTriggered=!1,this.lastScrollY=window.scrollY,B.debug("ScrollTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{type:this.type,isInViewport:this.isInViewport,scrollDistance:this.scrollDistance,isTriggered:this.isTriggered,currentScrollY:window.scrollY})}isActive(){return"viewport"===this.type?!this.isInViewport:"distance"===this.type&&this.isTriggered}forceActivate(){"viewport"===this.type?this.triggerActivated("scroll-out-of-view",{manual:!0}):"distance"===this.type&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{manual:!0}))}forceDeactivate(){"viewport"===this.type&&this.triggerDeactivated("scroll-back-in-view",{manual:!0})}destroy(){this.isDestroyed||(this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.scrollListener&&(window.removeEventListener("scroll",this.scrollListener),this.scrollListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.isDestroyed=!0,B.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class Cs{constructor(e){this.mouseLeaveListener=null,this.lastMouseY=0,this.isTriggered=!1,this.scrollUpListener=null,this.visibilityChangeListener=null,this.backButtonListener=null,this.touchStartListener=null,this.touchEndListener=null,this.lastScrollY=0,this.scrollUpDistance=0,this.touchStartY=0,this.touchStartTime=0,this.isScrollingUp=!1,this.debounceTimer=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,desktopTriggers:0,mobileTriggers:0,backButtonTriggers:0,scrollUpTriggers:0,tabSwitchTriggers:0},this.widgetId=e.widgetId,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}}}initialize(){var e,t;this.config.enabled&&(B.debug("Initializing ExitIntentTrigger",{widgetId:this.widgetId,config:this.config}),this.lastScrollY=window.scrollY,(null===(e=this.config.desktop)||void 0===e?void 0:e.enabled)&&this.isDesktop()&&this.initializeDesktopTriggers(),(null===(t=this.config.mobile)||void 0===t?void 0:t.enabled)&&this.isMobile()&&this.initializeMobileTriggers())}isDesktop(){return!("ontouchstart"in window)&&!navigator.maxTouchPoints}isMobile(){return"ontouchstart"in window||navigator.maxTouchPoints>0}initializeDesktopTriggers(){var e,t;this.mouseLeaveListener=this.debounce(this.handleMouseLeave.bind(this),(null===(e=this.config.desktop)||void 0===e?void 0:e.delay)||100),this.mouseLeaveListener&&(document.addEventListener("mouseleave",this.mouseLeaveListener),document.addEventListener("mouseout",this.mouseLeaveListener)),B.debug("Desktop exit intent triggers initialized",{widgetId:this.widgetId,sensitivity:null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity})}initializeMobileTriggers(){const e=this.config.mobile;e.backButton&&(this.backButtonListener=this.handleBackButton.bind(this),window.addEventListener("popstate",this.backButtonListener),history.pushState({widgeticExitIntent:!0},"",window.location.href)),e.scrollUp&&(this.scrollUpListener=this.debounce(this.handleScrollUp.bind(this),50),this.scrollUpListener&&window.addEventListener("scroll",this.scrollUpListener,{passive:!0}),this.touchStartListener=this.handleTouchStart.bind(this),this.touchEndListener=this.handleTouchEnd.bind(this),document.addEventListener("touchstart",this.touchStartListener,{passive:!0}),document.addEventListener("touchend",this.touchEndListener,{passive:!0})),e.tabSwitch&&(this.visibilityChangeListener=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeListener)),B.debug("Mobile exit intent triggers initialized",{widgetId:this.widgetId,backButton:e.backButton,scrollUp:e.scrollUp,tabSwitch:e.tabSwitch})}handleMouseLeave(e){var t;if(this.isDestroyed||this.isTriggered)return;const i=(null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity)||10;e.clientY<=i&&null===e.relatedTarget&&(this.isTriggered=!0,this.stats.desktopTriggers++,this.triggerActivated("exit-intent",{source:"desktop",method:"mouse-leave",mouseY:e.clientY,sensitivity:i}))}handleBackButton(e){var t;this.isDestroyed||(null===(t=e.state)||void 0===t?void 0:t.widgeticExitIntent)&&(this.stats.backButtonTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"back-button"}),history.pushState({widgeticExitIntent:!0},"",window.location.href))}handleScrollUp(){var e;if(this.isDestroyed)return;const t=window.scrollY,i=t-this.lastScrollY;if(i<0){this.scrollUpDistance+=Math.abs(i),this.isScrollingUp=!0;const n=(null===(e=this.config.mobile)||void 0===e?void 0:e.sensitivity)||50;this.scrollUpDistance>=n&&t<=100&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"scroll-up",scrollUpDistance:this.scrollUpDistance,currentScrollY:t,sensitivity:n}),this.scrollUpDistance=0)}else this.scrollUpDistance=0,this.isScrollingUp=!1;this.lastScrollY=t}handleTouchStart(e){if(this.isDestroyed||1!==e.touches.length)return;const t=e.touches[0];this.touchStartY=t.clientY,this.touchStartTime=Date.now()}handleTouchEnd(e){if(this.isDestroyed||1!==e.changedTouches.length)return;const t=e.changedTouches[0].clientY,i=Date.now()-this.touchStartTime,n=t-this.touchStartY;n>100&&i<300&&window.scrollY<=50&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"swipe-up",swipeDistance:n,touchDuration:i,scrollY:window.scrollY}))}handleVisibilityChange(){this.isDestroyed||document.hidden&&(this.stats.tabSwitchTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"tab-switch",visibilityState:document.visibilityState}))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),B.debug("Exit intent trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return(...i)=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e.apply(this,i)}),t)}}updateConfig(e){var t,i;if(this.isDestroyed)return;const n=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0===e.enabled&&void 0===(null===(t=e.desktop)||void 0===t?void 0:t.enabled)&&void 0===(null===(i=e.mobile)||void 0===i?void 0:i.enabled)||(this.destroy(),this.isDestroyed=!1,this.initialize()),B.debug("ExitIntentTrigger config updated",{widgetId:this.widgetId,oldConfig:n,newConfig:this.config})}reset(){this.isDestroyed||(this.isTriggered=!1,this.scrollUpDistance=0,this.isScrollingUp=!1,this.lastScrollY=window.scrollY,B.debug("ExitIntentTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{isTriggered:this.isTriggered,scrollUpDistance:this.scrollUpDistance,isScrollingUp:this.isScrollingUp,currentScrollY:window.scrollY,isDesktop:this.isDesktop(),isMobile:this.isMobile()})}isActive(){return this.isTriggered}forceActivate(e="desktop"){this.triggerActivated("exit-intent",{source:e,method:"manual",manual:!0})}destroy(){this.isDestroyed||(this.mouseLeaveListener&&(document.removeEventListener("mouseleave",this.mouseLeaveListener),document.removeEventListener("mouseout",this.mouseLeaveListener),this.mouseLeaveListener=null),this.backButtonListener&&(window.removeEventListener("popstate",this.backButtonListener),this.backButtonListener=null),this.scrollUpListener&&(window.removeEventListener("scroll",this.scrollUpListener),this.scrollUpListener=null),this.visibilityChangeListener&&(document.removeEventListener("visibilitychange",this.visibilityChangeListener),this.visibilityChangeListener=null),this.touchStartListener&&(document.removeEventListener("touchstart",this.touchStartListener),this.touchStartListener=null),this.touchEndListener&&(document.removeEventListener("touchend",this.touchEndListener),this.touchEndListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.isDestroyed=!0,B.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const As={"top-left":["top","left"],"top-center":["top","center"],"top-right":["top","right"],"center-left":["center","left"],center:["center","center"],"center-center":["center","center"],"center-right":["center","right"],"bottom-left":["bottom","left"],"bottom-center":["bottom","center"],"bottom-right":["bottom","right"]};class Rs{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return Rs.instance||(Rs.instance=new Rs),Rs.instance}canShowOverlay(e,t){if(!(null==t?void 0:t.enabled))return!0;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o)),r=s.length<t.maxViews;return B.debug(`[RecurrenceManager] Recurrence check for ${e}`,{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,canShow:r}),r}recordView(e,t){if(!(null==t?void 0:t.enabled))return;const i={timestamp:Date.now(),widgetId:e},n=this.getViewHistory(e,t);n.push(i);const o=60*t.timePeriodHours*60*1e3,s=Date.now(),r=n.filter((e=>s-e.timestamp<=o));this.saveViewHistory(e,t,r),B.debug(`[RecurrenceManager] Recorded view for ${e}`,{totalViews:r.length,timePeriodHours:t.timePeriodHours})}getViewHistory(e,t){if(!this.isLocalStorageAvailable())return[];try{const i=this.getStorageKey(e,t),n=localStorage.getItem(i);if(!n)return[];const o=JSON.parse(n);return o.version!==this.storageVersion?[]:Array.isArray(o.views)?o.views:[]}catch(t){return B.warn(`[RecurrenceManager] Failed to load view history for ${e}`,{error:t}),[]}}saveViewHistory(e,t,i){if(this.isLocalStorageAvailable())try{const n=this.getStorageKey(e,t),o={version:this.storageVersion,widgetId:e,views:i,lastUpdated:Date.now()};localStorage.setItem(n,JSON.stringify(o))}catch(t){B.warn(`[RecurrenceManager] Failed to save view history for ${e}`,{error:t})}}getStorageKey(e,t){const i=(null==t?void 0:t.storageKeySuffix)?`-${t.storageKeySuffix}`:"";return`${this.storageKey}-${e}${i}`}isLocalStorageAvailable(){try{const e="__localStorage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}getStats(e,t){if(!(null==t?void 0:t.enabled))return null;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o));return{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,remainingViews:Math.max(0,t.maxViews-s.length),canShow:s.length<t.maxViews,lastView:s.length>0?s[s.length-1].timestamp:null,viewHistory:s.map((e=>e.timestamp))}}clearHistory(e,t){if(!(null==t?void 0:t.enabled)||!this.isLocalStorageAvailable())return;const i=this.getStorageKey(e,t);localStorage.removeItem(i),B.debug(`[RecurrenceManager] Cleared view history for ${e}`)}cleanup(){if(!this.isLocalStorageAvailable())return;const e=[];for(let t=0;t<localStorage.length;t++){const i=localStorage.key(t);if(null==i?void 0:i.startsWith(this.storageKey))try{const t=JSON.parse(localStorage.getItem(i)||"{}"),n=Date.now()-864e5;t.lastUpdated<n&&e.push(i)}catch(t){e.push(i)}}e.forEach((e=>localStorage.removeItem(e))),e.length>0&&B.debug(`[RecurrenceManager] Cleaned up ${e.length} old view records`)}}class xs{constructor(e){var t;this.scrollTrigger=null,this.exitIntentTrigger=null,this.portal=null,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,this.placeholder=null,this.isInOverlay=!1,this.isDestroyed=!1,this.triggerInstances=new Map,this.keydownListener=null,this.recurrenceManager=Rs.getInstance(),this.delayTimer=null,this.domReadyListener=null,this.fullWidthRestore=null,this.onTriggerActivated=e=>this.handleTriggerActivated(e),this.onTriggerDeactivated=e=>this.handleTriggerDeactivated(e),this.onOverlayClose=e=>this.handleOverlayClose(e),this.widgetId=e.widgetId,this.element=e.element,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.mode=this.config.mode||"site",this.displayWhenShown=null!==(t=e.displayWhenShown)&&void 0!==t?t:"",this.originalParent=this.element.parentElement,this.originalNextSibling=this.element.nextSibling,this.initialize()}getDefaultConfig(){return{mode:"site",scroll:{enabled:!0,threshold:.1,distance:100,direction:"down"},exitIntent:{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}},overlay:{position:"bottom-right",offset:{x:20,y:20},className:"",style:"",closeButton:!0,backdrop:!1,animation:"slide",background:{enabled:!0,color:"#000",opacity:.5}},recurrence:{enabled:!1,maxViews:1,timePeriodHours:24}}}initialize(){switch(B.debug("Initializing TriggerManager",{widgetId:this.widgetId,mode:this.mode,config:this.config}),this.mode){case"site":break;case"mixed":this.initializeScrollTrigger("viewport");break;case"overlay":this.hideWidget(),this.armOverlayEventTrigger()}this.bindEvents()}armOverlayEventTrigger(){switch(this.config.eventTrigger){case"pageLoad":this.showOnLoad();break;case"delay":this.showAfterDelay();break;case"scroll":this.initializeScrollTrigger("distance");break;default:this.initializeScrollTrigger("distance"),this.initializeExitIntentTrigger()}}whenDomReady(e){this.isDestroyed||("loading"===document.readyState?(this.domReadyListener=()=>{this.domReadyListener=null,this.isDestroyed||e()},document.addEventListener("DOMContentLoaded",this.domReadyListener,{once:!0})):e())}showOnLoad(){this.whenDomReady((()=>this.showOverlay()))}showAfterDelay(){var e,t;if(!1===(null===(e=this.config.delay)||void 0===e?void 0:e.enabled))return;const i=null===(t=this.config.delay)||void 0===t?void 0:t.delayMs,n="number"==typeof i&&Number.isFinite(i)&&i>=0?i:3e3;this.whenDomReady((()=>{null===this.delayTimer&&(this.delayTimer=setTimeout((()=>{this.delayTimer=null,this.showOverlay()}),n),B.debug("Delay trigger armed",{widgetId:this.widgetId,delayMs:n}))}))}initializeScrollTrigger(e){var t;(null===(t=this.config.scroll)||void 0===t?void 0:t.enabled)&&(this.scrollTrigger=new Es({widgetId:this.widgetId,element:this.element,type:e,config:this.config.scroll}),this.triggerInstances.set("scroll",this.scrollTrigger))}initializeExitIntentTrigger(){var e;(null===(e=this.config.exitIntent)||void 0===e?void 0:e.enabled)&&(this.exitIntentTrigger=new Cs({widgetId:this.widgetId,config:this.config.exitIntent}),this.triggerInstances.set("exitIntent",this.exitIntentTrigger))}bindEvents(){document.addEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.addEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.addEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener=this.handleEscapeKey.bind(this),document.addEventListener("keydown",this.keydownListener)}handleTriggerActivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;B.debug("Trigger activated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-out-of-view"===i?this.showOverlay():"overlay"!==this.mode||"scroll-distance"!==i&&"exit-intent"!==i||this.showOverlay(),this.dispatchTriggerEvent("activated",i,n)}handleTriggerDeactivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;B.debug("Trigger deactivated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-back-in-view"===i&&this.hideOverlay(),this.dispatchTriggerEvent("deactivated",i,n)}handleOverlayClose(e){var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===this.widgetId&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}handleEscapeKey(e){"Escape"===e.key&&this.isInOverlay&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}showOverlay(){var e,t,i,n,o;if(!this.isInOverlay&&!this.isDestroyed){if("overlay"===this.mode&&(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)){if(!this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence))return B.debug("Overlay blocked by recurrence limits",{widgetId:this.widgetId,recurrenceConfig:this.config.recurrence}),void this.dispatchEvent("overlay-blocked",{reason:"recurrence-limit",recurrenceStats:this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)})}this.portal||(this.portal=es({target:"widgetic-trigger-portal",className:(null===(t=this.config.overlay)||void 0===t?void 0:t.className)||"",style:(null===(i=this.config.overlay)||void 0===i?void 0:i.style)||"",zIndex:this.getOverlayZIndex(),clickThrough:!this.hasOverlayBackground()})),this.overlayContainer=this.createOverlayContainer(),this.portal.mount(this.overlayContainer),this.leavePlaceholder(),this.overlayContainer.appendChild(this.element),this.element.style.display=this.displayWhenShown,this.applyFullWidthSizing(),this.isInOverlay=!0,"overlay"===this.mode&&(null===(n=this.config.recurrence)||void 0===n?void 0:n.enabled)&&this.recurrenceManager.recordView(this.widgetId,this.config.recurrence),B.debug("Widget moved to overlay",{widgetId:this.widgetId}),this.dispatchEvent("overlay-shown",{mode:this.mode,position:null===(o=this.config.overlay)||void 0===o?void 0:o.position})}}leavePlaceholder(){var e;if("mixed"!==this.mode||this.placeholder)return;const t=this.element.parentNode;if(!t)return;const{width:i,height:n}=this.element.getBoundingClientRect(),o=document.createElement("div");o.setAttribute("data-widgetic-placeholder",this.widgetId),o.setAttribute("aria-hidden","true"),o.style.cssText=`display:block;visibility:hidden;pointer-events:none;width:${i}px;height:${n}px;`,t.insertBefore(o,this.element),this.placeholder=o,null===(e=this.scrollTrigger)||void 0===e||e.observeElement(o)}returnToPlaceholder(){const e=this.placeholder;return!!e&&(this.placeholder=null,!!e.parentNode&&(e.parentNode.replaceChild(this.element,e),!0))}hideOverlay(){var e;this.isInOverlay&&!this.isDestroyed&&(this.restoreFullWidthSizing(),!this.returnToPlaceholder()&&this.originalParent&&(this.originalNextSibling?this.originalParent.insertBefore(this.element,this.originalNextSibling):this.originalParent.appendChild(this.element)),"mixed"===this.mode&&(null===(e=this.scrollTrigger)||void 0===e||e.observeElement(this.element)),this.portal&&this.portal.unmount(),this.overlayContainer=null,this.isInOverlay=!1,B.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,o;const s=document.createElement("div");s.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),c=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),l=this.getOverlayStyles(r,a,this.getOverlayZIndex(),c);if(s.style.cssText=l,d&&this.applyBackgroundStyling(s),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,c);s.appendChild(e)}return(null===(o=this.config.overlay)||void 0===o?void 0:o.animation)&&s.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(s),s}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,o=(null==n?void 0:n.color)||"#000000",s=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${o};\n opacity: ${s};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?99999999:Math.min(Math.floor(t),ln)}getOverlayStyles(e,t,i,n){const[o,s]=As[e]||As["bottom-right"];let r=`\n position: fixed;\n z-index: ${i};\n pointer-events: auto;\n max-height: 90vh;\n `;return n?r+="left: 0; right: 0; width: 100%; max-width: 100vw;":(r+="max-width: 90vw;",r+="left"===s?`left: ${t.x}px;`:"right"===s?`right: ${t.x}px;`:"left: 0; right: 0; margin-left: auto; margin-right: auto; width: -moz-fit-content; width: fit-content;"),r+="top"===o?`top: ${n?0:t.y}px;`:"bottom"===o?`bottom: ${n?0:t.y}px;`:"top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; height: -moz-fit-content; height: fit-content;",r}applyFullWidthSizing(){var e;if(!(null===(e=this.config.overlay)||void 0===e?void 0:e.fullWidth)||this.fullWidthRestore)return;const t=Array.from(this.element.querySelectorAll("iframe"));this.fullWidthRestore={elementWidth:this.element.style.width,iframes:t.map((e=>({iframe:e,width:e.style.width})))},this.element.style.width="100%",t.forEach((e=>{e.style.width="100%"}))}restoreFullWidthSizing(){this.fullWidthRestore&&(this.element.style.width=this.fullWidthRestore.elementWidth,this.fullWidthRestore.iframes.forEach((({iframe:e,width:t})=>{e.style.width=t})),this.fullWidthRestore=null)}createCloseButton(e,t=!1){const i=document.createElement("button");i.className="widgetic-trigger-overlay-close",i.setAttribute("aria-label","Close overlay"),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const o=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=o+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(e){this.isDestroyed||(this.config=Object.assign(Object.assign({},this.config),e),this.triggerInstances.forEach(((e,t)=>{"scroll"===t&&this.config.scroll?e.updateConfig(this.config.scroll):"exitIntent"===t&&this.config.exitIntent&&e.updateConfig(this.config.exitIntent)})),B.debug("TriggerManager config updated",{widgetId:this.widgetId,config:this.config}))}getStats(){var e;const t={widgetId:this.widgetId,mode:this.mode,isInOverlay:this.isInOverlay,isDestroyed:this.isDestroyed,triggerInstances:Array.from(this.triggerInstances.keys())};return this.triggerInstances.forEach(((e,i)=>{"function"==typeof e.getStats&&(t[`${i}Stats`]=e.getStats())})),(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(t.recurrenceStats=this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)),t}forceShowOverlay(){this.showOverlay()}forceHideOverlay(){this.hideOverlay()}getRecurrenceStats(){var e;return(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)?this.recurrenceManager.getStats(this.widgetId,this.config.recurrence):null}clearRecurrenceHistory(){var e;(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(this.recurrenceManager.clearHistory(this.widgetId,this.config.recurrence),B.debug("Recurrence history cleared",{widgetId:this.widgetId}))}canShowOverlay(){var e;return"overlay"!==this.mode||!(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)||this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence)}destroy(){this.isDestroyed||(null!==this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.domReadyListener&&(document.removeEventListener("DOMContentLoaded",this.domReadyListener),this.domReadyListener=null),this.isInOverlay&&this.hideOverlay(),this.placeholder&&(this.placeholder.remove(),this.placeholder=null),this.triggerInstances.forEach((e=>{"function"==typeof e.destroy&&e.destroy()})),this.triggerInstances.clear(),this.portal&&(this.portal.destroy(),this.portal=null),document.removeEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.removeEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.removeEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.recurrenceManager.cleanup(),this.isDestroyed=!0,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,B.debug("TriggerManager destroyed",{widgetId:this.widgetId}))}applyOverlayWidgetStyling(e){var t;if(!("mixed"===this.mode))return;if(!1!==(null===(t=this.config.overlay)||void 0===t?void 0:t.keepDimensions))return;const i=this.config.overlay;if(i){if(i.overlayWidth){const t="number"==typeof i.overlayWidth?`${i.overlayWidth}px`:i.overlayWidth;e.style.width=t,e.style.maxWidth=t}if(i.overlayHeight){const t="number"==typeof i.overlayHeight?`${i.overlayHeight}px`:i.overlayHeight;e.style.height=t,e.style.maxHeight=t}i.overlayResize&&this.applyOverlayResizeMode(e,i.overlayResize)}}applyOverlayResizeMode(e,t){switch(t){case"fill-width":e.style.width="90vw",e.style.height="auto",e.style.maxWidth="90vw";break;case"fill-height":e.style.height="90vh",e.style.width="auto",e.style.maxHeight="90vh";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="90vw",e.style.maxWidth="90vw";break;case"fixed-width":e.style.height="90vh",e.style.maxHeight="90vh";break;case"allow-scale-down":e.style.maxWidth="90vw",e.style.maxHeight="90vh";break;case"fill":e.style.width="90vw",e.style.height="90vh",e.style.maxWidth="90vw",e.style.maxHeight="90vh"}}}var Ds=Object.freeze({__proto__:null,TriggerManager:xs});class Ms{constructor(e={}){var t,i,n,o;this.cspDirectives=new Map,this.cspNonce="",this.encryptionKey=null,this.sensitiveDataCache=new Map,this.contentFilters=new Map,this.moderationQueue=new Map,this.auditEvents=[],this.auditBuffer=new Map,this.threatPatterns=new Map,this.threatScores=new Map,this.consentStatus=new Map,this.dataSubjects=new Map,this.config=Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0,maxTextLength:1e5,maxUpdatesPerMinute:60,maxGlobalUpdatesPerMinute:1e3,suspiciousActivityThreshold:5,auditLogging:!0,threatDetection:!0,csp:{level:"balanced",allowInlineStyles:!1,allowEval:!1,reportOnly:!1},secureData:{classification:"internal",encryptInTransit:!0,encryptAtRest:!1,anonymizeData:!1,dataRetentionDays:90},contentFilter:{enableProfanityFilter:!0,enableSpamDetection:!0,enableMalwareScanning:!0,autoModeration:!1},privacy:{enableGDPRCompliance:!0,enableCCPACompliance:!0,anonymizeUserData:!1,cookieConsent:!0,dataProcessingBasis:"legitimate_interest",dataSubjectRights:!0}},e),this.baseSecurityManager=Ts.getInstance(this.config),this.initializeCSP(),this.initializeDataSecurity(),this.initializeContentFilters(),this.initializeThreatDetection(),this.initializePrivacyControls(),B.info("[AdvancedSecurityManager] Initialized with config:",{cspLevel:null===(t=this.config.csp)||void 0===t?void 0:t.level,dataClassification:null===(i=this.config.secureData)||void 0===i?void 0:i.classification,contentFiltering:null===(n=this.config.contentFilter)||void 0===n?void 0:n.enableProfanityFilter,privacy:null===(o=this.config.privacy)||void 0===o?void 0:o.enableGDPRCompliance})}static getInstance(e){return Ms.instance||(Ms.instance=new Ms(e)),Ms.instance}initializeCSP(){this.config.csp&&(this.cspNonce=this.generateNonce(),this.setupCSPDirectives(),this.applyCSP(),B.info("[AdvancedSecurityManager] CSP initialized with level:",this.config.csp.level))}generateNonce(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}setupCSPDirectives(){var e,t;const{level:i,allowedDomains:n=[],allowInlineStyles:o,allowEval:s}=this.config.csp,r=["'self'","https://widgetic.com","https://cdn.widgetic.com",...n];switch(i){case"strict":this.cspDirectives.set("default-src",["'self'"]),this.cspDirectives.set("script-src",["'self'",`'nonce-${this.cspNonce}'`]),this.cspDirectives.set("style-src",["'self'",`'nonce-${this.cspNonce}'`]),this.cspDirectives.set("img-src",["'self'","data:","https:"]),this.cspDirectives.set("connect-src",["'self'",...r]),this.cspDirectives.set("font-src",["'self'","https:"]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["'self'"]),this.cspDirectives.set("frame-ancestors",["'self'"]);break;case"balanced":this.cspDirectives.set("default-src",["'self'",...r]),this.cspDirectives.set("script-src",["'self'",`'nonce-${this.cspNonce}'`,...r,...s?["'unsafe-eval'"]:[]]),this.cspDirectives.set("style-src",["'self'",`'nonce-${this.cspNonce}'`,...r,...o?["'unsafe-inline'"]:[]]),this.cspDirectives.set("img-src",["'self'","data:","blob:","https:",...r]),this.cspDirectives.set("connect-src",["'self'",...r]),this.cspDirectives.set("font-src",["'self'","https:",...r]),this.cspDirectives.set("media-src",["'self'","blob:","https:",...r]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["'self'",...r]),this.cspDirectives.set("frame-ancestors",["'self'",...r]);break;case"permissive":this.cspDirectives.set("default-src",["'self'",...r,"https:"]),this.cspDirectives.set("script-src",["'self'","'unsafe-inline'","'unsafe-eval'",...r,"https:"]),this.cspDirectives.set("style-src",["'self'","'unsafe-inline'",...r,"https:"]),this.cspDirectives.set("img-src",["*","data:","blob:"]),this.cspDirectives.set("connect-src",["*"]),this.cspDirectives.set("font-src",["*"]),this.cspDirectives.set("media-src",["*"]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["*"])}(null===(e=this.config.csp)||void 0===e?void 0:e.customDirectives)&&Object.entries(this.config.csp.customDirectives).forEach((([e,t])=>{this.cspDirectives.set(e,t)})),(null===(t=this.config.csp)||void 0===t?void 0:t.reportUri)&&this.cspDirectives.set("report-uri",[this.config.csp.reportUri])}applyCSP(){var e;if("undefined"==typeof document)return;const t=this.buildCSPString();let i=document.querySelector('meta[http-equiv="Content-Security-Policy"]');i||(i=document.createElement("meta"),i.httpEquiv="Content-Security-Policy",document.head.appendChild(i)),(null===(e=this.config.csp)||void 0===e?void 0:e.reportOnly)&&(i.httpEquiv="Content-Security-Policy-Report-Only"),i.content=t,B.info("[AdvancedSecurityManager] CSP applied:",t)}buildCSPString(){const e=[];return this.cspDirectives.forEach(((t,i)=>{const n=i.replace(/([A-Z])/g,"-$1").toLowerCase();e.push(`${n} ${t.join(" ")}`)})),e.join("; ")}initializeDataSecurity(){return t(this,void 0,void 0,(function*(){var e;if(null===(e=this.config.secureData)||void 0===e?void 0:e.encryptAtRest)try{this.encryptionKey=yield crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),B.info("[AdvancedSecurityManager] Data encryption initialized")}catch(e){B.error("[AdvancedSecurityManager] Failed to initialize encryption:",e)}}))}initializeContentFilters(){this.config.contentFilter&&(this.addDefaultContentFilters(),this.config.contentFilter.customFilters&&this.config.contentFilter.customFilters.forEach((e=>{this.contentFilters.set(e.id,e)})),B.info("[AdvancedSecurityManager] Content filtering initialized with filters:",Array.from(this.contentFilters.keys())))}addDefaultContentFilters(){var e,i,n;(null===(e=this.config.contentFilter)||void 0===e?void 0:e.enableProfanityFilter)&&this.contentFilters.set("profanity",{id:"profanity",name:"Profanity Filter",description:"Filters inappropriate language",type:"keyword",keywords:["damn","hell","crap","stupid","idiot"],severity:"medium",action:"warn"}),(null===(i=this.config.contentFilter)||void 0===i?void 0:i.enableSpamDetection)&&(this.contentFilters.set("spam",{id:"spam",name:"Spam Detection",description:"Detects spam content patterns including links",type:"regex",pattern:/(click here|buy now|limited time|act now|free money|make money fast|visit.*site|check.*out|earn.*\$|guaranteed.*income|work.*from.*home|lose.*weight.*fast)/gi,severity:"high",action:"block"}),this.contentFilters.set("link_spam",{id:"link_spam",name:"Link Spam Detection",description:"Detects spam patterns in links and URLs",type:"custom",severity:"medium",action:"warn",customHandler:(e,i)=>t(this,void 0,void 0,(function*(){return this.detectLinkSpam(e)}))})),(null===(n=this.config.contentFilter)||void 0===n?void 0:n.enableMalwareScanning)&&this.contentFilters.set("malware",{id:"malware",name:"Malware Scanner",description:"Scans for malicious content patterns",type:"regex",pattern:/(javascript:|data:text\/html|<script|eval\(|document\.write)/gi,severity:"critical",action:"block"})}initializeThreatDetection(){this.config.threatDetection&&(this.addDefaultThreatPatterns(),this.config.customThreatPatterns&&this.config.customThreatPatterns.forEach((e=>{this.threatPatterns.set(e.id,e)})),B.info("[AdvancedSecurityManager] Threat detection initialized with patterns:",Array.from(this.threatPatterns.keys())))}addDefaultThreatPatterns(){this.threatPatterns.set("sql_injection",{id:"sql_injection",name:"SQL Injection Detection",description:"Detects SQL injection attempts",type:"injection",severity:"high",responseAction:"block",indicators:[{type:"pattern",condition:/(union|select|insert|update|delete|drop|create|alter)\s/gi,weight:8},{type:"pattern",condition:/('|")\s*(or|and)\s*('|")/gi,weight:9}]}),this.threatPatterns.set("xss",{id:"xss",name:"Cross-Site Scripting Detection",description:"Detects XSS attempts",type:"injection",severity:"high",responseAction:"block",indicators:[{type:"pattern",condition:/<script[^>]*>|javascript:|on\w+\s*=/gi,weight:9},{type:"content",condition:e=>e.includes("alert(")||e.includes("prompt("),weight:7}]}),this.threatPatterns.set("data_exfiltration",{id:"data_exfiltration",name:"Data Exfiltration Detection",description:"Detects potential data exfiltration attempts",type:"exfiltration",severity:"critical",responseAction:"quarantine",indicators:[{type:"behavior",condition:e=>e.dataVolumePerMinute>1e6,weight:8},{type:"frequency",condition:e=>e.requestsPerMinute>100,weight:6,timeWindow:6e4}]})}initializePrivacyControls(){this.config.privacy&&(this.config.privacy.cookieConsent&&this.initializeConsentManagement(),this.config.privacy.dataSubjectRights&&this.initializeDataSubjectRights(),B.info("[AdvancedSecurityManager] Privacy controls initialized"))}initializeConsentManagement(){if("undefined"!=typeof localStorage){const e=localStorage.getItem("widgetic_privacy_consent");if(e)try{const t=JSON.parse(e);this.consentStatus.set("general",t.general||!1),this.consentStatus.set("analytics",t.analytics||!1),this.consentStatus.set("marketing",t.marketing||!1)}catch(e){B.warn("[AdvancedSecurityManager] Failed to parse existing consent:",e)}}}initializeDataSubjectRights(){B.info("[AdvancedSecurityManager] Data subject rights initialized")}validateContent(e,i){return t(this,arguments,void 0,(function*(e,t,i={}){var n;const o=[];let s=t;try{const r=this.baseSecurityManager.validateTextFieldUpdate(e,i.fieldId||"content",t,i);if(!r.allowed)return o.push({filterId:"basic_security",filterName:"Basic Security",severity:r.severity||"medium",reason:r.reason||"Basic security validation failed"}),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation",outcome:"blocked",details:{reason:r.reason,contentLength:t.length},classification:"internal",severity:"medium",userId:i.userId,sessionId:i.sessionId}),{allowed:!1,violations:o};if(r.sanitizedText&&(s=r.sanitizedText),this.config.threatDetection){const t=yield this.detectThreats(e,s,i);if(t.violations.length>0){if(o.push(...t.violations),!t.allowed)return{allowed:!1,violations:o};t.filteredContent&&(s=t.filteredContent)}}if(this.config.contentFilter){const n=yield this.applyContentFilters(s,i);if(n.violations.length>0){if(o.push(...n.violations),!n.allowed)return yield this.logAuditEvent({type:"content_filtered",widgetId:e,action:"content_blocked",outcome:"blocked",details:{violations:n.violations,originalLength:t.length},classification:"internal",severity:"medium",userId:i.userId,sessionId:i.sessionId}),{allowed:!1,violations:o};n.filteredContent&&(s=n.filteredContent)}}return 0===o.length&&(yield this.logAuditEvent({type:"data_accessed",widgetId:e,action:"content_validated",outcome:"success",details:{contentLength:t.length,filtered:s!==t},classification:(null===(n=this.config.secureData)||void 0===n?void 0:n.classification)||"internal",severity:"low",userId:i.userId,sessionId:i.sessionId})),{allowed:!0,filteredContent:s!==t?s:void 0,violations:o}}catch(t){return B.error("[AdvancedSecurityManager] Content validation error:",t),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation_error",outcome:"failure",details:{error:t instanceof Error?t.message:"Unknown error"},classification:"internal",severity:"high",userId:i.userId,sessionId:i.sessionId}),o.push({filterId:"system_error",filterName:"System Error",severity:"critical",reason:"Content validation system error"}),{allowed:!1,violations:o}}}))}applyContentFilters(e,i){return t(this,void 0,void 0,(function*(){const t=[];let n=e,o=!1;for(const[e,s]of this.contentFilters)try{const r=yield this.applyFilter(s,n,i);if(r.violations&&t.push(...r.violations),!r.allowed){if("block"===s.action){o=!0;break}"moderate"===s.action&&this.moderationQueue.set(`${Date.now()}-${e}`,{content:n,filter:s,context:i,timestamp:Date.now()})}r.filteredContent&&(n=r.filteredContent)}catch(i){B.error(`[AdvancedSecurityManager] Filter ${e} error:`,i),t.push({filterId:e,filterName:s.name,severity:"medium",reason:"Filter processing error"})}return{allowed:!o,filteredContent:n!==e?n:void 0,violations:t}}))}applyFilter(e,i,n){return t(this,void 0,void 0,(function*(){switch(e.type){case"regex":return this.applyRegexFilter(e,i);case"keyword":return this.applyKeywordFilter(e,i);case"custom":return e.customHandler?yield e.customHandler(i,n):{allowed:!0};default:return{allowed:!0}}}))}applyRegexFilter(e,t){if(!e.pattern)return{allowed:!0};const i="string"==typeof e.pattern?new RegExp(e.pattern,"gi"):e.pattern,n=t.match(i);if(n&&n.length>0){const o=n.map((t=>({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Pattern matched: ${t}`}))),s=t.replace(i,"[FILTERED]");return{allowed:"block"!==e.action,filtered:!0,filteredContent:s,violations:o,confidence:.9}}return{allowed:!0}}applyKeywordFilter(e,t){if(!e.keywords||0===e.keywords.length)return{allowed:!0};const i=t.toLowerCase(),n=[];let o=t;for(const t of e.keywords){const s=t.toLowerCase();if(i.includes(s)){n.push({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Keyword detected: ${t}`});const i=new RegExp(t,"gi");o=o.replace(i,"[FILTERED]")}}return n.length>0?{allowed:"block"!==e.action,filtered:!0,filteredContent:o,violations:n,confidence:.8}:{allowed:!0}}detectLinkSpam(e){return t(this,void 0,void 0,(function*(){const t=[];let i=0;try{const n=/<a[^>]*href\s*=\s*["']([^"']*)["'][^>]*>([^<]*)<\/a>/gi,o=[];let s;for(;null!==(s=n.exec(e));)o.push({url:s[1],text:s[2],match:s[0]});o.length>5&&(i+=3,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Excessive number of links detected: ${o.length}`}));for(const e of o){["bit.ly","tinyurl","t.co","goo.gl","ow.ly","tiny.cc"].some((t=>e.url.includes(t)))&&(i+=2,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`URL shortener detected: ${e.url}`}));["click here","read more","visit now","buy now","order now","download now","get started","try free","join now","sign up"].some((t=>e.text.toLowerCase().includes(t.toLowerCase())))&&(i+=1,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"low",reason:`Suspicious link text: "${e.text}"`}));[".tk",".ml",".ga",".cf",".buzz",".click"].some((t=>e.url.includes(t)))&&(i+=2,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Suspicious domain: ${e.url}`})),e.text.includes("http")&&!e.url.includes(e.text.replace(/^https?:\/\//,""))&&(i+=3,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"high",reason:`Mismatched link text and URL: "${e.text}" -> ${e.url}`}))}const r=i>=5,a=Math.min(i/10,1);return{allowed:!r,filtered:t.length>0,violations:t,confidence:a,requiresModeration:i>=3&&i<5}}catch(e){return B.error("[AdvancedSecurityManager] Link spam detection error:",e),{allowed:!0,violations:[{filterId:"link_spam",filterName:"Link Spam Detection",severity:"low",reason:"Link spam detection failed"}]}}}))}detectThreats(e,i,n){return t(this,void 0,void 0,(function*(){const t=[];let o=0,s=!1;for(const[r,a]of this.threatPatterns){let d=0;for(const e of a.indicators){d+=this.evaluateIndicator(e,i,n)}const c=Math.min(10,d);o+=c,c>=7&&(t.push({filterId:r,filterName:a.name,severity:a.severity,reason:a.description}),"block"!==a.responseAction&&"quarantine"!==a.responseAction||(s=!0),yield this.logAuditEvent({type:"threat_detected",widgetId:e,action:"threat_pattern_matched",outcome:s?"blocked":"suspicious",details:{patternId:r,patternName:a.name,threatScore:c,indicators:a.indicators.length},classification:"confidential",severity:a.severity,userId:n.userId,sessionId:n.sessionId}))}const r=`${e}:${n.userId||"anonymous"}`;return this.threatScores.set(r,(this.threatScores.get(r)||0)+o),{allowed:!s,violations:t}}))}evaluateIndicator(e,t,i){try{switch(e.type){case"pattern":if("string"==typeof e.condition||e.condition instanceof RegExp){return("string"==typeof e.condition?new RegExp(e.condition,"gi"):e.condition).test(t)?e.weight:0}break;case"content":if("function"==typeof e.condition)return e.condition(t)?e.weight:0;break;case"behavior":case"frequency":if("function"==typeof e.condition)return e.condition(i)?e.weight:0}return 0}catch(e){return B.warn("[AdvancedSecurityManager] Indicator evaluation error:",e),0}}logAuditEvent(e){return t(this,void 0,void 0,(function*(){if(!this.config.auditLogging)return;const t=Object.assign({id:this.generateEventId(),timestamp:(new Date).toISOString(),ipAddress:this.getClientIP(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"Unknown",classification:"internal",severity:"low",correlationId:this.generateCorrelationId(),details:{}},e),i=t.widgetId;this.auditBuffer.has(i)||this.auditBuffer.set(i,[]),this.auditBuffer.get(i).push(t),this.auditEvents.push(t),this.auditEvents.length>1e3&&this.auditEvents.splice(0,this.auditEvents.length-1e3);const n=this.getLogLevel(t.severity);B[n](`[SecurityAudit] ${t.type}:`,{id:t.id,widgetId:t.widgetId,action:t.action,outcome:t.outcome,severity:t.severity,userId:t.userId}),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-audit",{detail:t}))}))}getCSPNonce(){return this.cspNonce}updateCSPConfig(e){this.config.csp||(this.config.csp={level:"balanced",allowInlineStyles:!1,allowEval:!1,reportOnly:!1}),this.config.csp=Object.assign(Object.assign({},this.config.csp),e),this.setupCSPDirectives(),this.applyCSP(),this.logAuditEvent({type:"configuration_changed",widgetId:"system",action:"csp_config_updated",outcome:"success",details:{newConfig:e},classification:"internal",severity:"medium"})}recordConsent(e,t,i,n={}){if(this.consentStatus.set(t,i),"undefined"!=typeof localStorage){const e=JSON.parse(localStorage.getItem("widgetic_privacy_consent")||"{}");e[t]=i,e.timestamp=Date.now(),localStorage.setItem("widgetic_privacy_consent",JSON.stringify(e))}this.logAuditEvent({type:"privacy_consent",widgetId:e,action:"consent_"+(i?"granted":"revoked"),outcome:"success",details:{consentType:t,granted:i},classification:"confidential",severity:"medium",userId:n.userId,sessionId:n.sessionId}),B.info(`[AdvancedSecurityManager] Privacy consent ${i?"granted":"revoked"}:`,{consentType:t,widgetId:e,userId:n.userId})}hasConsent(e){return this.consentStatus.get(e)||!1}getSecurityStats(){const e=this.auditEvents.filter((e=>"threat_detected"===e.type)).length,t=this.auditEvents.filter((e=>"content_filtered"===e.type)).length,i=this.baseSecurityManager.getSecurityStats().blockedInstances;return{auditEvents:this.auditEvents.length,threatDetections:e,contentFiltered:t,blockedInstances:i}}exportAuditLogs(e,t){var i;let n=this.auditEvents;return e&&(n=n.filter((t=>t.widgetId===e))),t&&(n=n.filter((e=>e.classification===t))),(null===(i=this.config.privacy)||void 0===i?void 0:i.anonymizeUserData)?n.map((e=>Object.assign(Object.assign({},e),{userId:e.userId?"anonymized":void 0,ipAddress:e.ipAddress?"anonymized":void 0,userAgent:"anonymized"}))):n}generateEventId(){return`audit_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateCorrelationId(){return`corr_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getClientIP(){return"client_ip"}getLogLevel(e){switch(e){case"low":case"medium":default:return"info";case"high":return"warn";case"critical":return"error"}}}class Ls{constructor(e,t){this._active=!0,this.id=`sub_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.compositionId=e,this.handler=t}isActive(){return this._active}unsubscribe(){this._active=!1}}class Ws{constructor(e){this.pollTimer=null,this.lastPoll=0,this.interval=e.interval,this.endpoint=e.endpoint,this.subscriptions=e.subscriptions,this.realtimeManager=e.realtimeManager}start(){return t(this,void 0,void 0,(function*(){this.pollTimer||(B.info("[PollingFallback] Starting polling fallback",{interval:this.interval,subscriptions:this.subscriptions.size}),this.pollTimer=setInterval((()=>{this.pollForUpdates()}),this.interval),yield this.pollForUpdates())}))}stop(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),B.info("[PollingFallback] Polling fallback stopped")}pollForUpdates(){return t(this,void 0,void 0,(function*(){if(0!==this.subscriptions.size)try{const e=yield fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.realtimeManager.getApiKey()},body:JSON.stringify({compositionIds:Array.from(this.subscriptions),since:this.lastPoll})});if(!e.ok)throw new Error(`Polling failed: ${e.status}`);const t=yield e.json();for(const e of t.updates||[])yield this.realtimeManager.handlePolledUpdate(e);this.lastPoll=Date.now()}catch(e){B.error("[PollingFallback] Polling error:",e)}}))}}class Os{constructor(e){this.socket=null,this.connectionState="disconnected",this.connectionId=null,this.subscriptions=new Map,this.allSubscriptions=new Map,this.reconnectAttempts=0,this.reconnectTimer=null,this.messageQueue=new Map,this.retryTimer=null,this.heartbeatTimer=null,this.lastHeartbeat=0,this.heartbeatTimeout=null,this.pollingFallback=null,this.connectionStartTime=0,this.messageStats={sent:0,received:0,errors:0};const t={enabled:!0,wsUrl:"wss://realtime.widgetic.com",authentication:{type:"apikey",credentials:""},features:{contentUpdates:!0,styleUpdates:!0,configUpdates:!1,dataUpdates:!0},security:{validateUpdates:!0,rateLimitPerMinute:30,allowedUpdateTypes:["content","style","data"]},reconnection:{enabled:!0,maxAttempts:5,baseDelay:1e3,maxDelay:3e4},fallback:{enabled:!0,pollInterval:5e3},heartbeat:{enabled:!0,interval:3e4,timeout:1e4}};this.config=Object.assign(Object.assign(Object.assign({},t),e),{authentication:Object.assign(Object.assign({},t.authentication),e.authentication),features:Object.assign(Object.assign({},t.features),e.features),security:Object.assign(Object.assign({},t.security),e.security),reconnection:Object.assign(Object.assign({},t.reconnection),e.reconnection),fallback:Object.assign(Object.assign({},t.fallback),e.fallback),heartbeat:Object.assign(Object.assign({},t.heartbeat),e.heartbeat)}),this.securityManager=function(e){return Ms.getInstance(e)}(),this.performanceMonitor=fs(),this.setupEventListeners()}static getInstance(e){return Os.instance||(Os.instance=new Os(e||{})),Os.instance}initialize(){return t(this,void 0,void 0,(function*(){this.config.enabled?"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(B.info("[RealtimeManager] Initializing real-time connection"),yield this.connect()):B.info("[RealtimeManager] Real-time updates disabled")}))}connect(){return t(this,void 0,void 0,(function*(){if("connected"!==this.connectionState&&"connecting"!==this.connectionState){this.connectionState="connecting",this.connectionStartTime=Date.now();try{const e=this.buildWebSocketUrl();B.info("[RealtimeManager] Connecting to WebSocket:",e),this.socket=new WebSocket(e),this.socket.onopen=this.handleConnect.bind(this),this.socket.onmessage=this.handleMessage.bind(this),this.socket.onclose=this.handleDisconnect.bind(this),this.socket.onerror=this.handleError.bind(this)}catch(e){throw this.connectionState="error",B.error("[RealtimeManager] Connection failed:",e),yield this.handleConnectionError(e),e}}}))}subscribe(e,t){const i=new Ls(e,t);return this.subscriptions.has(e)||this.subscriptions.set(e,new Set),this.subscriptions.get(e).add(i),this.allSubscriptions.set(i.id,i),"connected"===this.connectionState?this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}):this.queueMessage(e,{type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}),B.info("[RealtimeManager] Subscribed to composition:",{compositionId:e,subscriptionId:i.id,totalSubscriptions:this.allSubscriptions.size}),i}unsubscribe(e){e.unsubscribe();const t=this.subscriptions.get(e.compositionId);t&&(t.delete(e),0===t.size&&this.subscriptions.delete(e.compositionId)),this.allSubscriptions.delete(e.id),"connected"===this.connectionState&&this.sendMessage({type:"unsubscribe",compositionId:e.compositionId,subscriptionId:e.id,timestamp:Date.now()}),B.info("[RealtimeManager] Unsubscribed from composition:",{compositionId:e.compositionId,subscriptionId:e.id,remainingSubscriptions:this.allSubscriptions.size})}getActiveSubscriptions(){return new Set(this.subscriptions.keys())}getApiKey(){return this.config.authentication.credentials}handlePolledUpdate(e){return t(this,void 0,void 0,(function*(){try{const t={type:e.type,compositionId:e.compositionId,data:e.data,userId:e.userId,timestamp:e.timestamp,version:e.version,partial:e.partial};yield this.processUpdate(t,{fromPolling:!0})}catch(e){B.error("[RealtimeManager] Failed to process polled update:",e)}}))}buildWebSocketUrl(){const e=this.config.wsUrl,t=new URLSearchParams;switch(this.config.authentication.type){case"apikey":t.append("apikey",this.config.authentication.credentials);break;case"jwt":t.append("token",this.config.authentication.credentials);break;case"session":t.append("session",this.config.authentication.credentials)}return t.append("client","embed-sdk"),t.append("version","1.0.0"),`${e}?${t.toString()}`}handleConnect(){var e;this.connectionState="connected",this.reconnectAttempts=0;const t=Date.now()-this.connectionStartTime;B.info("[RealtimeManager] Connected to real-time service",{connectionTime:t,subscriptions:this.subscriptions.size}),null===(e=this.performanceMonitor)||void 0===e||e.recordCustomMetric("realtime_connection_time",t),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.startHeartbeat(),this.processMessageQueue(),this.reestablishSubscriptions(),this.emitEvent("connected",{connectionTime:t})}handleMessage(e){return t(this,void 0,void 0,(function*(){this.messageStats.received++;try{const t=JSON.parse(e.data);switch(t.type){case"widget_update":yield this.handleWidgetUpdate(t);break;case"subscription_confirmed":this.handleSubscriptionConfirmed(t);break;case"heartbeat":this.handleHeartbeat(t);break;case"error":this.handleServerError(t);break;case"authentication":this.handleAuthentication(t);break;default:B.warn("[RealtimeManager] Unknown message type:",t.type)}}catch(e){this.messageStats.errors++,B.error("[RealtimeManager] Message parsing failed:",e)}}))}handleWidgetUpdate(e){return t(this,void 0,void 0,(function*(){const{compositionId:t,updateType:i,data:n,userId:o,timestamp:s,version:r,partial:a}=e;if(!this.config.features[`${i}Updates`])return void B.warn("[RealtimeManager] Update type disabled:",i);if(!this.config.security.allowedUpdateTypes.includes(i))return void B.warn("[RealtimeManager] Update type not allowed:",i);const d=this.subscriptions.get(t);if(!d||0===d.size)return void B.debug("[RealtimeManager] No subscriptions for composition:",t);const c={type:i,compositionId:t,data:n,userId:o,timestamp:s,version:r,partial:a};yield this.processUpdate(c,{fromWebSocket:!0})}))}processUpdate(e){return t(this,arguments,void 0,(function*(e,t={}){var i;try{if(this.config.security.validateUpdates){const t=yield this.securityManager.validateContent(e.compositionId,JSON.stringify(e.data),{userId:e.userId});if(!t.allowed)return B.warn("[RealtimeManager] Update blocked by security:",{compositionId:e.compositionId,violations:t.violations}),void this.emitEvent("security_violation",{compositionId:e.compositionId,violations:t.violations,update:e});if(t.filteredContent)try{e.data=JSON.parse(t.filteredContent)}catch(e){B.warn("[RealtimeManager] Failed to parse filtered content, using original")}}const n=this.subscriptions.get(e.compositionId);if(!n)return;const o=[];for(const t of n)t.isActive()&&o.push(t.handler(e).catch((i=>{B.error("[RealtimeManager] Handler execution failed:",{subscriptionId:t.id,compositionId:e.compositionId,error:i})})));yield Promise.allSettled(o),B.debug("[RealtimeManager] Update applied:",{compositionId:e.compositionId,type:e.type,handlerCount:o.length,source:t.fromWebSocket?"websocket":"polling"}),null===(i=this.performanceMonitor)||void 0===i||i.recordCustomMetric("realtime_updates_processed",1),this.emitEvent("update_applied",{compositionId:e.compositionId,type:e.type,handlerCount:o.length})}catch(t){B.error("[RealtimeManager] Update processing failed:",t),this.emitEvent("update_error",{compositionId:e.compositionId,error:t instanceof Error?t.message:"Unknown error",update:e})}}))}handleSubscriptionConfirmed(e){B.info("[RealtimeManager] Subscription confirmed:",{compositionId:e.compositionId,subscriptionId:e.subscriptionId})}handleHeartbeat(e){this.lastHeartbeat=Date.now(),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null),this.sendMessage({type:"heartbeat_response",timestamp:Date.now()})}handleServerError(e){B.error("[RealtimeManager] Server error:",e.data),this.emitEvent("server_error",{error:e.data})}handleAuthentication(e){var t,i,n;(null===(t=e.data)||void 0===t?void 0:t.success)?(this.connectionId=e.data.connectionId,B.info("[RealtimeManager] Authentication successful:",{connectionId:this.connectionId})):(B.error("[RealtimeManager] Authentication failed:",null===(i=e.data)||void 0===i?void 0:i.error),null===(n=this.socket)||void 0===n||n.close())}handleDisconnect(e){this.connectionState="disconnected",this.connectionId=null,B.warn("[RealtimeManager] Disconnected from real-time service:",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.stopHeartbeat(),this.config.reconnection.enabled&&!e.wasClean&&this.scheduleReconnection(),this.config.fallback.enabled&&this.subscriptions.size>0&&this.enablePollingFallback(),this.emitEvent("disconnected",{code:e.code,reason:e.reason,wasClean:e.wasClean})}handleError(e){var t;this.messageStats.errors++,B.error("[RealtimeManager] WebSocket error:",e),null===(t=this.performanceMonitor)||void 0===t||t.recordCustomMetric("realtime_errors",1),this.emitEvent("error",{event:e})}handleConnectionError(e){return t(this,void 0,void 0,(function*(){B.error("[RealtimeManager] Connection error:",e),this.config.reconnection.enabled?yield this.scheduleReconnection():this.config.fallback.enabled&&this.enablePollingFallback()}))}scheduleReconnection(){return t(this,void 0,void 0,(function*(){if(this.reconnectAttempts>=this.config.reconnection.maxAttempts)return B.error("[RealtimeManager] Max reconnection attempts reached"),this.config.fallback.enabled&&this.enablePollingFallback(),void this.emitEvent("max_reconnect_attempts",{attempts:this.reconnectAttempts});this.connectionState="reconnecting",this.reconnectAttempts++;const e=Math.min(this.config.reconnection.baseDelay*Math.pow(2,this.reconnectAttempts-1),this.config.reconnection.maxDelay);B.info("[RealtimeManager] Scheduling reconnection:",{attempt:this.reconnectAttempts,delay:e,maxAttempts:this.config.reconnection.maxAttempts}),this.reconnectTimer=setTimeout((()=>t(this,void 0,void 0,(function*(){try{yield this.connect()}catch(e){B.error("[RealtimeManager] Reconnection failed:",e),yield this.scheduleReconnection()}}))),e)}))}enablePollingFallback(){!this.pollingFallback&&this.config.fallback.enabled&&(B.info("[RealtimeManager] Enabling polling fallback"),this.pollingFallback=new Ws({interval:this.config.fallback.pollInterval||5e3,endpoint:"/api/widgets/updates",subscriptions:this.getActiveSubscriptions(),realtimeManager:this}),this.pollingFallback.start(),this.emitEvent("fallback_enabled",{interval:this.config.fallback.pollInterval}))}sendMessage(e){if("connected"===this.connectionState&&this.socket)try{this.socket.send(JSON.stringify(e)),this.messageStats.sent++}catch(t){this.messageStats.errors++,B.error("[RealtimeManager] Failed to send message:",t),this.queueMessage(e.compositionId||"global",e)}else this.queueMessage(e.compositionId||"global",e)}queueMessage(e,t){this.messageQueue.has(e)||this.messageQueue.set(e,[]);this.messageQueue.get(e).push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now(),nextRetry:Date.now()+1e3}),this.retryTimer||(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processRetryQueue(){const e=Date.now();let t=!1;for(const[i,n]of this.messageQueue){const o=[];for(const i of n)e>=i.nextRetry?i.retryCount<i.maxRetries?(i.retryCount++,i.nextRetry=e+1e3*Math.pow(2,i.retryCount),this.sendMessage(i.message),i.retryCount<i.maxRetries&&o.push(i)):B.warn("[RealtimeManager] Message retry limit exceeded:",i.message):(o.push(i),t=!0);o.length>0?this.messageQueue.set(i,o):this.messageQueue.delete(i)}this.retryTimer=null,t&&(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processMessageQueue(){if("connected"===this.connectionState){B.info("[RealtimeManager] Processing queued messages:",{queueSize:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)});for(const[e,t]of this.messageQueue)for(const e of t)this.sendMessage(e.message);this.messageQueue.clear(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}}reestablishSubscriptions(){if(0!==this.subscriptions.size){B.info("[RealtimeManager] Re-establishing subscriptions:",{count:this.subscriptions.size});for(const[e,t]of this.subscriptions)for(const i of t)i.isActive()&&this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()})}}startHeartbeat(){this.config.heartbeat.enabled&&(this.stopHeartbeat(),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&(this.sendMessage({type:"heartbeat",timestamp:Date.now()}),this.heartbeatTimeout=setTimeout((()=>{var e;B.warn("[RealtimeManager] Heartbeat timeout"),null===(e=this.socket)||void 0===e||e.close()}),this.config.heartbeat.timeout))}).bind(this),2*this.config.heartbeat.interval),this.lastHeartbeat=Date.now())}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null)}setupEventListeners(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden?this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&this.sendMessage({type:"heartbeat",timestamp:Date.now()})}).bind(this),2*this.config.heartbeat.interval)):this.startHeartbeat()})),"undefined"!=typeof navigator&&"onLine"in navigator&&(window.addEventListener("online",(()=>{B.info("[RealtimeManager] Network back online"),"disconnected"===this.connectionState&&this.connect()})),window.addEventListener("offline",(()=>{B.warn("[RealtimeManager] Network offline"),this.pollingFallback&&this.pollingFallback.stop()})))}emitEvent(e,t){"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent(`widgetic:realtime:${e}`,{detail:Object.assign({manager:this,timestamp:Date.now()},t)}))}getConnectionState(){return this.connectionState}getStats(){return{connectionState:this.connectionState,subscriptions:this.allSubscriptions.size,messageStats:Object.assign({},this.messageStats),reconnectAttempts:this.reconnectAttempts,lastHeartbeat:this.lastHeartbeat,queuedMessages:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)}}disconnect(){B.info("[RealtimeManager] Disconnecting"),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.stopHeartbeat(),this.socket&&(this.socket.close(),this.socket=null),this.connectionState="disconnected",this.subscriptions.clear(),this.allSubscriptions.clear(),this.messageQueue.clear(),this.emitEvent("manual_disconnect",{})}}Os.instance=null;class _s{constructor(e={}){var t,i,n,o;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionSubscriptions=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},e),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},e.security)}),this.apiConfig=new K(Object.assign(Object.assign({basePath:this.config.apiBaseUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:3000")},this.config.apiKey&&{apiKey:this.config.apiKey}),this.config.accessToken&&{accessToken:this.config.accessToken})),this.widgetsApi=new Fi(this.apiConfig),this.compositionsApi=new Pi(this.apiConfig),this.securityManager=Ts.getInstance(this.config.security||{}),this.displayManager=new as,this.performanceMonitor=fs(),(null===(t=e.realtime)||void 0===t?void 0:t.enabled)&&(this.realtimeManager=function(e){return Os.getInstance(e)}(e.realtime)),this.setupResponsiveTracking(),this.setupEventListeners(),B.info("[WidgetManager] Initialized with config:",{realtimeEnabled:!!(null===(i=e.realtime)||void 0===i?void 0:i.enabled),securityEnabled:!!(null===(n=e.security)||void 0===n?void 0:n.enableSanitization),performanceEnabled:!!(null===(o=e.performance)||void 0===o?void 0:o.enabled)})}static getInstance(e){return _s.instance||(_s.instance=new _s(e)),_s.instance}initialize(){return t(this,void 0,void 0,(function*(){if(this.isInitialized)B.warn("[WidgetManager] Already initialized");else try{this.realtimeManager&&(yield this.realtimeManager.initialize(),B.info("[WidgetManager] Real-time manager initialized")),this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),B.info("[WidgetManager] Successfully initialized")}catch(e){throw B.error("[WidgetManager] Initialization failed:",e),this.emitError({code:"INIT_FAILED",message:"Widget manager initialization failed",widgetId:"system",timestamp:Date.now(),details:{error:e instanceof Error?e.message:"Unknown error"}}),e}}))}registerWidget(e,i,n){return t(this,void 0,void 0,(function*(){try{const t=yield this.validateWidgetConfig(i);if(!t.allowed)throw new Error(`Widget validation failed: ${t.reason}`);const o={id:e,config:i,element:n,state:{ready:!1,error:null,width:i.width,height:i.height},displayState:{mode:i.displayMode,isFullscreen:!1,isOverlay:!1,isPopup:!1},updateHandlers:new Map,lastUpdate:Date.now()},s=this.displayManager.initializeWidget(e,i,n);if(o.displayState=s,i.triggers)try{const t=new xs({widgetId:e,element:n,config:i.triggers});this.triggerManagers.set(e,t),B.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:e,triggers:i.triggers})}catch(t){B.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}return this.realtimeManager&&i.compositionId&&(yield this.setupRealtimeUpdates(o)),this.widgets.set(e,o),this.widgetConfigs.set(e,i),o.state.ready=!0,B.info("[WidgetManager] Widget registered:",{widgetId:e,compositionId:i.compositionId,realtimeEnabled:!!o.realtimeSubscription}),this.emitEvent({type:"widget_registered",widgetId:e,data:{config:i},timestamp:Date.now()}),o}catch(t){throw B.error("[WidgetManager] Widget registration failed:",t),this.emitError({code:"REGISTRATION_FAILED",message:"Widget registration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}}),t}}))}setupRealtimeUpdates(e){return t(this,void 0,void 0,(function*(){if(this.realtimeManager&&e.config.compositionId)try{const i=e.config.compositionId;if(this.compositionWidgets.has(i)||this.compositionWidgets.set(i,new Set),this.compositionWidgets.get(i).add(e.id),this.compositionSubscriptions.has(i))B.info("[WidgetManager] Using existing real-time subscription for composition:",{compositionId:i,widgetCount:this.compositionWidgets.get(i).size});else{const e=e=>t(this,void 0,void 0,(function*(){yield this.handleCompositionUpdate(i,e)})),n=this.realtimeManager.subscribe(i,e);this.compositionSubscriptions.set(i,n),B.info("[WidgetManager] Real-time subscription created for composition:",{compositionId:i,subscriptionId:n.id,widgetCount:this.compositionWidgets.get(i).size})}e.realtimeSubscription=this.compositionSubscriptions.get(i)}catch(e){throw B.error("[WidgetManager] Failed to setup real-time updates:",e),e}}))}handleCompositionUpdate(e,i){return t(this,void 0,void 0,(function*(){var t,n;try{B.debug("[WidgetManager] Processing composition update:",{compositionId:e,updateType:i.type,timestamp:i.timestamp,affectedWidgets:(null===(t=this.compositionWidgets.get(e))||void 0===t?void 0:t.size)||0});const o=this.compositionWidgets.get(e);if(!o||0===o.size)return void B.warn("[WidgetManager] No widgets found for composition:",e);const s=[];for(const e of o){const t=this.widgets.get(e);t&&s.push(this.handleWidgetUpdate(t,i))}if(yield Promise.allSettled(s),"content"===i.type||"data"===i.type){const t=this.compositionData.get(e),n={id:e,widgetId:e,content:"content"===i.type?i.data:(null==t?void 0:t.content)||{},theme:(null==t?void 0:t.theme)||{},version:i.version||"1.0.0"};"data"===i.type&&(null==t?void 0:t.content)&&(n.content=Object.assign(Object.assign({},t.content),i.data)),this.compositionData.set(e,n)}this.emitEvent({type:"composition_updated",widgetId:e,data:{compositionId:e,updateType:i.type,updateData:i.data,timestamp:i.timestamp,affectedWidgets:Array.from(o)},timestamp:Date.now()}),null===(n=this.performanceMonitor)||void 0===n||n.recordCustomMetric("composition_updates_applied",1)}catch(t){B.error("[WidgetManager] Composition update failed:",t),this.emitError({code:"COMPOSITION_UPDATE_FAILED",message:"Composition update processing failed",widgetId:e,timestamp:Date.now(),details:{compositionId:e,updateType:i.type,error:t instanceof Error?t.message:"Unknown error"}})}}))}handleWidgetUpdate(e,i){return t(this,void 0,void 0,(function*(){try{switch(e.lastUpdate=Date.now(),i.type){case"content":yield this.handleContentUpdate(e,i);break;case"style":yield this.handleStyleUpdate(e,i);break;case"config":yield this.handleConfigUpdate(e,i);break;case"data":yield this.handleDataUpdate(e,i);break;default:B.warn("[WidgetManager] Unknown update type:",i.type)}this.emitEvent({type:"widget_updated",widgetId:e.id,data:{compositionId:e.config.compositionId,updateType:i.type,updateData:i.data,timestamp:i.timestamp},timestamp:Date.now()})}catch(t){B.error("[WidgetManager] Widget update failed:",t),this.emitError({code:"WIDGET_UPDATE_FAILED",message:"Widget update processing failed",widgetId:e.id,timestamp:Date.now(),details:{compositionId:e.config.compositionId,updateType:i.type,error:t instanceof Error?t.message:"Unknown error"}})}}))}handleContentUpdate(e,i){return t(this,void 0,void 0,(function*(){var t;if(e.config.compositionId){const t=this.compositionData.get(e.config.compositionId),n={id:e.config.compositionId,widgetId:e.config.compositionId,content:i.data,theme:(null==t?void 0:t.theme)||{},version:i.version||(null==t?void 0:t.version)||"1.0.0"};this.compositionData.set(e.config.compositionId,n)}yield this.applyContentToWidget(e,i.data);const n=null===(t=e.updateHandlers)||void 0===t?void 0:t.get("content");n&&(yield n(i.data))}))}handleStyleUpdate(e,i){return t(this,void 0,void 0,(function*(){var t;yield this.applyStylesToWidget(e,i.data);const n=null===(t=e.updateHandlers)||void 0===t?void 0:t.get("style");n&&(yield n(i.data))}))}handleConfigUpdate(e,i){return t(this,void 0,void 0,(function*(){var t;const n=Object.assign(Object.assign({},e.config),i.data),o=yield this.validateWidgetConfig(n);if(!o.allowed)throw new Error(`Config update validation failed: ${o.reason}`);if(e.config=n,this.widgetConfigs.set(e.id,n),i.data.displayMode||i.data.resize||i.data.width||i.data.height)try{this.displayManager.cleanup(e.id);const t=this.displayManager.initializeWidget(e.id,n,e.element);e.displayState=t,B.debug("[WidgetManager] Display management updated:",{widgetId:e.id,displayMode:n.displayMode})}catch(t){B.warn("[WidgetManager] Failed to update display management:",{widgetId:e.id,error:t instanceof Error?t.message:"Unknown error"})}const s=null===(t=e.updateHandlers)||void 0===t?void 0:t.get("config");s&&(yield s(i.data))}))}handleDataUpdate(e,i){return t(this,void 0,void 0,(function*(){var t;const n=null===(t=e.updateHandlers)||void 0===t?void 0:t.get("data");n?yield n(i.data):yield this.applyContentToWidget(e,i.data)}))}applyContentToWidget(e,i){return t(this,void 0,void 0,(function*(){try{if("string"==typeof i)if("iframe"===e.element.tagName.toLowerCase()){const t=e.element;t.contentWindow&&t.contentWindow.postMessage({type:"widgetic_content_update",content:i},Yi.CLIENT_URL||"*")}else{const t=yield this.sanitizeContent(i,e.id);e.element.innerHTML=t}else if("object"==typeof i)if("iframe"===e.element.tagName.toLowerCase()){const t=e.element;t.contentWindow&&t.contentWindow.postMessage({type:"widgetic_data_update",data:i},Yi.CLIENT_URL||"*")}else e.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:i}));B.debug("[WidgetManager] Content applied to widget:",{widgetId:e.id,contentType:typeof i})}catch(e){throw B.error("[WidgetManager] Failed to apply content:",e),e}}))}applyStylesToWidget(e,i){return t(this,void 0,void 0,(function*(){try{"object"==typeof i?Object.entries(i).forEach((([t,i])=>{"string"!=typeof i&&"number"!=typeof i||(e.element.style[t]=i)})):"string"==typeof i&&(e.element.style.cssText+=i),B.debug("[WidgetManager] Styles applied to widget:",{widgetId:e.id,stylesType:typeof i})}catch(e){throw B.error("[WidgetManager] Failed to apply styles:",e),e}}))}sanitizeContent(e,i){return t(this,void 0,void 0,(function*(){const t=this.securityManager.validateTextFieldUpdate(i,"content",e);if(!t.allowed)throw new Error(`Content blocked by security: ${t.reason}`);return t.sanitizedText||e}))}validateWidgetConfig(e){return t(this,void 0,void 0,(function*(){var t;if(!e.compositionId)return{allowed:!1,reason:"Missing composition ID",severity:"high"};if(null===(t=this.config.security)||void 0===t?void 0:t.enableSanitization){const t=JSON.stringify(e),i=this.securityManager.validateTextFieldUpdate(e.compositionId,"config",t);if(!i.allowed)return{allowed:!1,reason:i.reason,severity:i.severity||"medium"}}return{allowed:!0}}))}setContent(e,i){return t(this,arguments,void 0,(function*(e,i,n={}){var o;try{B.debug("[WidgetManager] Setting dynamic content:",{compositionId:e,contentType:typeof i,options:n});const s={content:i};void 0!==n.validate&&(s.validate=n.validate),void 0!==n.partial&&(s.partial=n.partial),void 0!==n.version&&(s.version=n.version),void 0!==n.source&&(s.source=n.source);const r=yield this.compositionsApi.setDynamicContent({id:e,setDynamicContentRequest:Yo(s)}),a=this.getWidgetsByComposition(e),d=this.compositionData.get(e);let c=i;n.partial&&(null==d?void 0:d.content)&&(c=this.mergeContent(d.content,i));const l={id:e,widgetId:e,content:c,theme:(null==d?void 0:d.theme)||{},version:n.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(e,l);const u=a.map((i=>t(this,void 0,void 0,(function*(){var t;try{yield this.applyContentToWidget(i,c);const o=null===(t=i.updateHandlers)||void 0===t?void 0:t.get("content");o&&(yield o(c)),i.lastUpdate=Date.now(),B.debug("[WidgetManager] Content applied to widget:",{widgetId:i.id,compositionId:e,source:n.source})}catch(e){throw B.error("[WidgetManager] Failed to update widget content:",{widgetId:i.id,error:e instanceof Error?e.message:"Unknown error"}),e}}))));return yield Promise.all(u),this.emitEvent({type:"content_updated",widgetId:e,data:{content:c,source:n.source,version:n.version,partial:n.partial},timestamp:Date.now()}),B.info("[WidgetManager] Content updated successfully via API:",{compositionId:e,widgetCount:a.length,source:n.source,realtimeUpdateSent:r.realtimeUpdateSent}),{success:null!==(o=r.success)&&void 0!==o&&o,validationResult:r.validationResult}}catch(t){const i=t instanceof Error?t.message:"Unknown error";return this.emitError({code:"CONTENT_UPDATE_FAILED",message:`Failed to set content: ${i}`,widgetId:e,timestamp:Date.now(),details:{error:i,options:n}}),{success:!1,error:i}}}))}getContentSchema(e){return t(this,void 0,void 0,(function*(){try{B.debug("[WidgetManager] Getting widget content schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetContentSchema({id:e});return B.debug("[WidgetManager] Content schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw B.error("[WidgetManager] Failed to get content schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get content schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}getDesignSchema(e){return t(this,void 0,void 0,(function*(){try{B.debug("[WidgetManager] Getting widget design schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetDesignSchema({id:e});return B.debug("[WidgetManager] Design schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw B.error("[WidgetManager] Failed to get design schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get design schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}validateContent(e,i){return t(this,void 0,void 0,(function*(){var t,n;try{B.debug("[WidgetManager] Validating content:",{compositionId:e});const o=yield this.compositionsApi.validateCompositionContent({id:e,body:Yo(i)});return B.debug("[WidgetManager] Content validation completed:",{compositionId:e,valid:null!==(t=o.valid)&&void 0!==t&&t}),{valid:null!==(n=o.valid)&&void 0!==n&&n,errors:o.errors,warnings:o.warnings,sanitizedContent:o.sanitizedContent}}catch(e){throw B.error("[WidgetManager] Content validation failed:",e),e}}))}getContent(e){const t=this.compositionData.get(e);return(null==t?void 0:t.content)||null}mergeContent(e,t){if(!e||"object"!=typeof e)return t;if(!t||"object"!=typeof t)return e;const i=Object.assign({},e);for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&!Array.isArray(n)?i[e]=this.mergeContent(i[e],n):i[e]=n;return i}registerUpdateHandler(e,t,i){const n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);n.updateHandlers||(n.updateHandlers=new Map),n.updateHandlers.set(t,i),B.info("[WidgetManager] Update handler registered:",{widgetId:e,updateType:t})}unregisterWidget(e){return t(this,void 0,void 0,(function*(){var t,i;const n=this.widgets.get(e);if(n)try{const o=n.config.compositionId;if(o&&this.compositionWidgets.has(o)&&(this.compositionWidgets.get(o).delete(e),0===this.compositionWidgets.get(o).size)){const e=this.compositionSubscriptions.get(o);e&&(null===(t=this.realtimeManager)||void 0===t||t.unsubscribe(e),this.compositionSubscriptions.delete(o),this.compositionWidgets.delete(o),B.info("[WidgetManager] Cleaned up composition subscription:",{compositionId:o,subscriptionId:e.id}))}try{this.displayManager.cleanup(e),B.debug("[WidgetManager] Display management cleaned up:",{widgetId:e})}catch(t){B.warn("[WidgetManager] Failed to cleanup display management:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}const s=this.triggerManagers.get(e);if(s)try{s.destroy(),this.triggerManagers.delete(e),B.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:e})}catch(t){B.warn("[WidgetManager] Failed to cleanup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.widgets.delete(e),this.widgetConfigs.delete(e),B.info("[WidgetManager] Widget unregistered:",{widgetId:e,compositionId:o,remainingWidgetsForComposition:(null===(i=this.compositionWidgets.get(o||""))||void 0===i?void 0:i.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:e,data:{compositionId:o},timestamp:Date.now()})}catch(t){B.error("[WidgetManager] Widget unregistration failed:",t),this.emitError({code:"UNREGISTRATION_FAILED",message:"Widget unregistration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}})}else B.warn("[WidgetManager] Widget not found for unregistration:",e)}))}getWidget(e){return this.widgets.get(e)}getAllWidgets(){return Array.from(this.widgets.values())}getWidgetsByComposition(e){const t=this.compositionWidgets.get(e);return t?Array.from(t).map((e=>this.widgets.get(e))).filter((e=>void 0!==e)):[]}setupResponsiveTracking(){if("undefined"==typeof window)return;const e=()=>{const e={mode:"mobile"===Jn().getDeviceType()?"mobile":"desktop",breakpoint:768,width:window.innerWidth,timestamp:Date.now()};this.responsiveState&&this.responsiveState.mode===e.mode||(this.responsiveState=e,this.emitEvent({type:"responsive_change",widgetId:"system",data:e,timestamp:Date.now()}),this.handleResponsiveChange(e))};let t;e(),window.addEventListener("resize",(()=>{clearTimeout(t),t=setTimeout(e,250)}))}handleResponsiveChange(e){for(const t of this.widgets.values())try{const i=this.widgetConfigs.get(t.id);if(i&&t.displayState){this.displayManager.cleanup(t.id);const n=this.displayManager.initializeWidget(t.id,i,t.element);t.displayState=n,B.debug("[WidgetManager] Responsive update applied:",{widgetId:t.id,mode:e.mode,width:e.width})}this.emitEvent({type:"widget_responsive_change",widgetId:t.id,data:e,timestamp:Date.now()})}catch(e){B.error("[WidgetManager] Responsive change handling failed for widget:",{widgetId:t.id,error:e})}}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}addErrorHandler(e){this.errorHandlers.add(e)}removeErrorHandler(e){this.errorHandlers.delete(e)}emitEvent(e){const t=this.eventListeners.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){B.error("[WidgetManager] Event handler failed:",e)}}))}emitError(e){this.errorHandlers.forEach((t=>{try{t(e)}catch(e){B.error("[WidgetManager] Error handler failed:",e)}}))}setupEventListeners(){"undefined"!=typeof window&&(this.realtimeManager&&(document.addEventListener("widgetic:realtime:connected",(()=>{this.emitEvent({type:"realtime_connected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:disconnected",(()=>{this.emitEvent({type:"realtime_disconnected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:error",(e=>{this.emitError({code:"REALTIME_ERROR",message:"Real-time connection error",widgetId:"system",timestamp:Date.now(),details:e.detail})}))),document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})})))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,compositionSubscriptions:this.compositionSubscriptions.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return t(this,void 0,void 0,(function*(){B.info("[WidgetManager] Destroying widget manager");const e=Array.from(this.widgets.keys());yield Promise.allSettled(e.map((e=>this.unregisterWidget(e))));for(const[e,t]of this.triggerManagers)try{t.destroy(),B.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:e})}catch(t){B.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),B.debug("[WidgetManager] Display manager cleaned up")}catch(e){B.warn("[WidgetManager] Failed to cleanup display manager:",{error:e instanceof Error?e.message:"Unknown error"})}this.realtimeManager&&this.realtimeManager.disconnect(),this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionSubscriptions.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,_s.instance=null,B.info("[WidgetManager] Widget manager destroyed")}))}getActiveCompositions(){return Array.from(this.compositionWidgets.keys()).filter((e=>this.compositionWidgets.get(e).size>0))}getCompositionData(e){return this.compositionData.get(e)}}function Ps(e){return _s.getInstance(e)}_s.instance=null;var zs=Object.freeze({__proto__:null,WidgetManager:_s,getWidgetManager:Ps});let qs=!1;class Us{constructor(e={}){var t,i,n,o,s,r,a,d,c,l,u,h,g,p,m,f,v,y,w,b,I,T;this.version=Hi,this.instances=new Map,this.isInitialized=!1,this.renderer=Vo(),this.widgetControllers=new Map,this.authDetector=Xo(),this.editorOverlay=rs(),this.displayManager=(ds||(ds=new as(T)),ds),this.resizeHandler=function(e){return Uo||(Uo=new qo(e)),Uo}(),this.authenticationStatus=null,this.overlayManager=null,this.hostObserverStarted=!1,this.config=Object.assign({renderMode:"auto",performance:{enabled:!1,config:{}},lazyLoading:{enabled:!0,config:{}}},e),this.browserCapabilities=lo(),this.messenger=zo(this.config.messagingOptions);const k=this.config.logLevel||(this.config.debug?"debug":"info");if(B.setLevel(k),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(t=this.config.performance)||void 0===t?void 0:t.enabled)){!function(e={}){ms=new ps(e)}(Object.assign({enableTracking:dn.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:dn.AXIOM_API_KEY,axiomDataset:dn.AXIOM_DATASET,axiomApiEndpoint:dn.AXIOM_API_ENDPOINT,statsigKey:dn.STATSIG_API_KEY,statsigApiEndpoint:dn.STATSIG_API_ENDPOINT},null===(i=this.config.performance)||void 0===i?void 0:i.config))}!1!==(null===(n=this.config.lazyLoading)||void 0===n?void 0:n.enabled)&&function(e={}){ys=new vs(e)}((null===(o=this.config.lazyLoading)||void 0===o?void 0:o.config)||{}),void 0!==this.config.debug&&(U.setDebug(this.config.debug),this.config.debug&&U.setLevel("debug")),!1!==(null===(s=this.config.resourceOptimization)||void 0===s?void 0:s.enabled)&&function(e={}){bs=new ws(e)}((null===(r=this.config.resourceOptimization)||void 0===r?void 0:r.config)||{}),this.config.editorOptions&&(this.editorOverlay=rs(this.config.editorOptions)),!1!==(null===(a=this.config.overlayConfig)||void 0===a?void 0:a.enabled)&&(this.overlayManager=function(e){return gs||(gs=new hs(e)),gs}({enabled:!0,defaultMode:null===(d=this.config.overlayConfig)||void 0===d?void 0:d.defaultMode,exitIntentEnabled:null===(c=this.config.overlayConfig)||void 0===c?void 0:c.exitIntentEnabled,scrollTriggerEnabled:null===(l=this.config.overlayConfig)||void 0===l?void 0:l.scrollTriggerEnabled,timeTriggerEnabled:null===(u=this.config.overlayConfig)||void 0===u?void 0:u.timeTriggerEnabled,engagementThresholdEnabled:null===(h=this.config.overlayConfig)||void 0===h?void 0:h.engagementThresholdEnabled,externalTriggerEnabled:null===(g=this.config.overlayConfig)||void 0===g?void 0:g.externalTriggerEnabled,breakpoints:{useBreakpoints:(null===(m=null===(p=this.config.overlayConfig)||void 0===p?void 0:p.breakpoints)||void 0===m?void 0:m.useBreakpoints)||!1,mobile:(null===(v=null===(f=this.config.overlayConfig)||void 0===f?void 0:f.breakpoints)||void 0===v?void 0:v.mobile)||480,tablet:(null===(w=null===(y=this.config.overlayConfig)||void 0===y?void 0:y.breakpoints)||void 0===w?void 0:w.tablet)||768,desktop:(null===(I=null===(b=this.config.overlayConfig)||void 0===b?void 0:b.breakpoints)||void 0===I?void 0:I.desktop)||1024}})),B.info("Widgetic Embed SDK v1.0 initialized",{version:Hi,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&B.info("EmbedSDK initialized in debug mode",{config:this.config})}init(){return t(this,void 0,void 0,(function*(){var e,t;if(this.watchPublishedHosts(),yield this.scanPage(),this.isInitialized)B.warn("SDK already initialized");else if(qs||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)B.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,qs=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((e=>{B.warn("Background authentication check failed",{error:e})})),this.config.preloadUISDK&&(null===(e=this.authenticationStatus)||void 0===e?void 0:e.isAuthenticated))try{const e=ns();yield e.preload(),B.info("UI SDK preloaded successfully")}catch(e){B.warn("Failed to preload UI SDK",{error:e})}yield this.scanPage(),B.info("Widgetic Embed SDK initialized successfully",{version:Hi,capabilities:this.browserCapabilities,authenticationStatus:null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated}),yield this.scanPage()}catch(e){throw B.error("SDK initialization failed",{error:e}),e}}))}checkAuthentication(){return t(this,void 0,void 0,(function*(){var e;try{this.authenticationStatus=yield this.authDetector.checkAuthentication(),this.authenticationStatus.isAuthenticated?B.info("User authenticated for editing",{userId:null===(e=this.authenticationStatus.user)||void 0===e?void 0:e.id}):B.debug("User not authenticated for editing")}catch(e){B.debug("Authentication check failed",{error:e}),this.authenticationStatus={isAuthenticated:!1,canEdit:!1}}}))}enhance(){return t(this,void 0,void 0,(function*(){yield this.scanPage()}))}refresh(){return t(this,void 0,void 0,(function*(){B.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){co(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{co()})).observe(document.documentElement,{childList:!0,subtree:!0}))}scanPage(){return t(this,void 0,void 0,(function*(){var e,t,i,n;const o=document.querySelectorAll("widgetic");if(B.debug("Found widgetic host elements",{count:o.length}),0===o.length)return void B.info("No widgets found on page");const s=[];for(const r of Array.from(o))if(Ln(r)&&r instanceof HTMLElement){if(ao(r))continue;try{const o=un(r),a=null===(t=null===(e=o.device)||void 0===e?void 0:e.mobileEnabled)||void 0===t||t;if(!Xn(a,null===(n=null===(i=o.device)||void 0===i?void 0:i.desktopEnabled)||void 0===n||n)){B.debug("Widget skipped due to device restrictions",{compositionId:o.compositionId,deviceRestrictions:o.device,element:r.outerHTML.substring(0,100)+"..."}),r.style.display="none",r.setAttribute("data-device-restricted","true");continue}s.push({element:r,config:o})}catch(e){B.error("Failed to parse widget configuration",{element:r.outerHTML,error:e})}}0!==s.length?yield this.renderWidgetsBatch(s):B.warn("No valid widget configurations found")}))}renderWidgetsBatch(e){return t(this,void 0,void 0,(function*(){try{const t=[],i=e.map((({element:e,config:i})=>{let n=e;if(e.parentNode){const t=document.createElement("div");t.className=`widgetic-host ${e.className}`.trim(),e.getAttribute("style")&&(t.style.cssText=e.getAttribute("style")||""),e.parentNode.replaceChild(t,e),n=t}return t.push(n),{compositionId:i.compositionId,renderMode:po(i.renderMode,this.browserCapabilities),width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:n}})),n=yield this.renderer.renderWidgets(i);for(let i=0;i<n.length;i++){const o=n[i],{config:s}=e[i],r=t[i],a=Mn(s.compositionId),d=this.displayManager.initializeWidget(a,s,o.element);o.element instanceof HTMLElement&&r instanceof HTMLElement&&this.resizeHandler.registerWidget(a,o.element,r.parentElement||r,s);const c={id:a,config:s,element:o.element,displayState:d,state:{ready:!0,error:null,width:"number"==typeof s.width?s.width:parseInt(String(s.width)),height:"number"==typeof s.height?s.height:parseInt(String(s.height))},enterFullscreen:()=>this.displayManager.enterFullscreen(a),exitFullscreen:()=>this.displayManager.exitFullscreen(a),showOverlay:()=>this.displayManager.showOverlay(a),hideOverlay:()=>this.displayManager.hideOverlay(a),openPopup:()=>this.displayManager.openPopup(a),closePopup:()=>this.displayManager.closePopup(a)};this.instances.set(c.id,c),yield this.maybeAddEditorOverlay(o.element,s.compositionId),B.debug("Widget rendered successfully",{instanceId:c.id,compositionId:s.compositionId,renderMode:o.renderMode,displayMode:s.displayMode})}B.info("Batch widget rendering complete",{rendered:n.length,total:e.length})}catch(t){B.error("Batch widget rendering failed",{error:t});for(const{element:t,config:i}of e)try{yield this.renderSingleWidget(t,i)}catch(e){B.error("Individual widget rendering failed",{compositionId:i.compositionId,error:e})}}}))}renderSingleWidget(e,i){return t(this,void 0,void 0,(function*(){try{performance.now(),fs(),Is();const n=function(e){return ys||(ys=new vs(e)),ys}();if(this.shouldUseLazyLoading(e,i))return void n.register(e,i.compositionId,(()=>t(this,void 0,void 0,(function*(){yield this.performActualWidgetRender(e,i)}))),{config:i,priority:this.getWidgetPriority(i),resourceUrls:this.getWidgetResourceUrls(i)});yield this.performActualWidgetRender(e,i)}catch(e){const t=fs(),n=e instanceof Error?e.message:"Render failed";throw t.recordWidgetError(i.compositionId,n),t.endWidgetLoad(i.compositionId,!1),B.error("Widget rendering failed",{error:e,config:i}),e}}))}performActualWidgetRender(e,i){return t(this,void 0,void 0,(function*(){const t=performance.now(),n=fs(),o=Is();try{const s=this.getWidgetResourceUrls(i);if(s.length>0&&(yield o.loadResources(s,{type:"script",priority:"high",compositionId:i.compositionId})),!("render"in this.renderer)||"function"!=typeof this.renderer.render)throw new Error("Widget renderer does not support render method");{const{widgetElement:o,instance:s}=yield this.renderer.render(e,i);if(!o)throw new Error("Widget element not created");const r=performance.now()-t;n.recordWidgetRender(i.compositionId,r),n.endWidgetLoad(i.compositionId,!0),this.instances.set(s.id,s)}}catch(e){const t=fs(),n=e instanceof Error?e.message:"Render failed";throw t.recordWidgetError(i.compositionId,n),t.endWidgetLoad(i.compositionId,!1),B.error("Widget rendering failed",{error:e,config:i}),e}}))}shouldUseLazyLoading(e,t){var i;if(!1===(null===(i=this.config.lazyLoading)||void 0===i?void 0:i.enabled))return!1;if("critical"===t.priority||!0===t.preload)return!1;const n=e.getBoundingClientRect();return!(n.top<window.innerHeight&&n.bottom>0)}getWidgetPriority(e){switch(e.priority){case"critical":return 10;case"high":return 7;case"medium":default:return 5;case"low":return 2}}getWidgetResourceUrls(e){const t=[];return e.scriptUrl&&t.push(e.scriptUrl),e.styleUrl&&t.push(e.styleUrl),e.resourceUrls&&Array.isArray(e.resourceUrls)&&t.push(...e.resourceUrls),t}maybeAddEditorOverlay(e,i){return t(this,void 0,void 0,(function*(){if(!1!==this.config.enableEditing)try{yield this.editorOverlay.addOverlay(e,i)}catch(e){B.debug("Failed to add editor overlay",{compositionId:i,error:e})}}))}getInstances(){return Array.from(this.instances.values())}getInstance(e){return this.instances.get(e)||null}getInstancesByComposition(e){return this.getInstances().filter((t=>t.config.compositionId===e))}getStats(){const e=this.renderer.getStats();return{version:Hi,widgetsRendered:this.instances.size,renderMode:"auto",cacheStats:e.batchCache,messagingActive:this.messenger.isActive(),customEventSubscriptions:this.messenger.getCustomEventSubscriptions(),functionHandlers:this.messenger.getFunctionHandlers(),authenticationStatus:this.authenticationStatus||void 0,editingSessions:this.editorOverlay.getActiveSessions().length}}createWidgetController(e){const t=Array.from(this.instances.values()).find((t=>t.config.compositionId===e));if(!t)return B.warn("Widget instance not found for controller creation",{compositionId:e}),null;const i=this.messenger.createWidgetController(t.id,e);return this.widgetControllers.set(e,i),B.info("Widget controller created",{compositionId:e,instanceId:t.id}),i}getWidgetController(e){return this.widgetControllers.get(e)||null}subscribeToWidget(e,t,i){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.subscribe(t,i)}callWidgetFunction(e,i,...n){return t(this,void 0,void 0,(function*(){let t=this.getWidgetController(e);if(!t&&(t=this.createWidgetController(e),!t))throw new Error(`Cannot create controller for widget: ${e}`);return t.callFunction(i,...n)}))}updateWidgetConfig(e,i){return t(this,void 0,void 0,(function*(){let t=this.getWidgetController(e);if(!t&&(t=this.createWidgetController(e),!t))throw new Error(`Cannot create controller for widget: ${e}`);return t.updateConfig(i)}))}getWidgetState(e,i){return t(this,void 0,void 0,(function*(){let t=this.getWidgetController(e);if(!t&&(t=this.createWidgetController(e),!t))throw new Error(`Cannot create controller for widget: ${e}`);return t.getState(i)}))}setWidgetState(e,i,n){return t(this,void 0,void 0,(function*(){let t=this.getWidgetController(e);if(!t&&(t=this.createWidgetController(e),!t))throw new Error(`Cannot create controller for widget: ${e}`);return t.setState(i,n)}))}emitToWidget(e,t,i,n){let o=this.getWidgetController(e);o||(o=this.createWidgetController(e),o)?o.emit(t,i,n):B.warn(`Cannot create controller for widget: ${e}`)}canEditComposition(e){return t(this,void 0,void 0,(function*(){return this.authDetector.canEditComposition(e)}))}getAuthenticationStatus(){return this.authenticationStatus}refreshAuthentication(){return t(this,void 0,void 0,(function*(){return yield this.checkAuthentication(),this.authenticationStatus}))}openEditor(e){return t(this,void 0,void 0,(function*(){if(!(yield this.canEditComposition(e)))throw new Error(`User cannot edit composition: ${e}`);yield this.editorOverlay.openEditor(e)}))}isEditorOpen(e){return this.editorOverlay.isEditorOpen(e)}closeEditor(e){return t(this,void 0,void 0,(function*(){yield this.editorOverlay.closeEditor(e)}))}setEditingEnabled(e){this.config.enableEditing=e,B.info("Editing mode changed",{enabled:e})}setContent(e,i){return t(this,arguments,void 0,(function*(e,t,i={}){try{const{getWidgetManager:n}=yield Promise.resolve().then((function(){return zs})),o=n();return yield o.setContent(e,t,i)}catch(e){return B.error("[EmbedSDK] Failed to set content:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}))}getContentSchema(e){return t(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return zs})),n=i();return yield n.getContentSchema(t.config.compositionId)}catch(e){throw B.error("[EmbedSDK] Failed to get content schema:",e),e}}))}getDesignSchema(e){return t(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return zs})),n=i();return yield n.getDesignSchema(t.config.compositionId)}catch(e){throw B.error("[EmbedSDK] Failed to get design schema:",e),e}}))}validateContent(e,i){return t(this,void 0,void 0,(function*(){try{const{getWidgetManager:t}=yield Promise.resolve().then((function(){return zs})),n=t();return yield n.validateContent(e,i)}catch(e){throw B.error("[EmbedSDK] Failed to validate content:",e),e}}))}getContent(e){try{return Ps().getContent(e)}catch(e){return B.error("[EmbedSDK] Failed to get content:",e),null}}onContentUpdate(e,t){return this.subscribeToWidget(e,"content_updated",t)}scan(){return t(this,void 0,void 0,(function*(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{const e=document.querySelectorAll("[data-widgetic]"),t=Array.from(e).map((e=>{const t=e.getAttribute("data-widgetic"),i=e.getAttribute("data-id");return t&&i?{id:t,dataId:i,element:e}:null})).filter(Boolean);return yield this.loadWidgets(t),{success:!0,widgets:t,errors:[]}}catch(e){return{success:!1,widgets:[],errors:[e instanceof Error?e.message:"Unknown error"]}}}))}loadWidgets(e){return t(this,void 0,void 0,(function*(){for(const t of e)try{yield this.loadWidget(t)}catch(e){}}))}loadWidget(e){return t(this,void 0,void 0,(function*(){yield new Promise((e=>setTimeout(e,100*Math.random())));const t=this.determineRenderMode();"iframe"===t?this.renderIframe(e):"custom-element"===t&&this.renderCustomElement(e)}))}determineRenderMode(){return"iframe"===this.config.renderMode?"iframe":"custom-element"===this.config.renderMode||"undefined"!=typeof customElements?"custom-element":"iframe"}renderIframe(e){const t=document.createElement("iframe");t.src=`https://widgetic.com/widget/${e.dataId}`,t.style.width=e.element.style.width||"400px",t.style.height=e.element.style.height||"300px",t.style.border="none",e.element.appendChild(t)}renderCustomElement(e){if("undefined"!=typeof customElements){customElements.get("widgetic-widget")||customElements.define("widgetic-widget",class extends HTMLElement{connectedCallback(){this.innerHTML=`<div>Widgetic Widget: ${this.getAttribute("data-widget-id")}</div>`}});const t=document.createElement("widgetic-widget");t.setAttribute("data-widget-id",e.dataId),e.element.appendChild(t)}}getConfig(){return Object.assign({},this.config)}showOverlay(e){this.overlayManager?this.overlayManager.showOverlay(e):B.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():B.warn("Overlay manager not initialized")}triggerOverlay(e,t={}){this.overlayManager?this.overlayManager.triggerOverlay(e,t):B.warn("Overlay manager not initialized")}isOverlayActive(){var e;return(null===(e=this.overlayManager)||void 0===e?void 0:e.isOverlayActive())||!1}destroy(){document.querySelectorAll("iframe").forEach((e=>e.remove()));document.querySelectorAll("widgetic-widget").forEach((e=>e.remove())),this.overlayManager&&(this.overlayManager.destroy(),this.overlayManager=null),this.isInitialized=!1}}let Bs=null;function $s(e){return Bs||(Bs=new Us(e)),Bs}"undefined"!=typeof document&&(co(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{co()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{$s().init().catch((e=>{B.error("Auto-initialization failed",{error:e})}))})):setTimeout((()=>{$s().init().catch((e=>{B.error("Auto-initialization failed",{error:e})}))}),0));class Fs{constructor(){this.debugMode=!1,this.trackedElements=new WeakSet}static getInstance(){return Fs.instance||(Fs.instance=new Fs),Fs.instance}enableDebugMode(){this.debugMode=!0,this.addDebugStyles(),B.info("CSS debugging mode enabled")}disableDebugMode(){this.debugMode=!1,this.removeDebugStyles(),B.info("CSS debugging mode disabled")}analyzeWidget(e){const t=e.getAttribute("data-widgetic-instance")||"unknown",i=[],n=[];this.detectCSSConflicts(e,i),this.checkStyleIsolation(e,n);const o={widgetId:t,conflicts:i,isolationScore:this.calculateIsolationScore(e,i),recommendations:n};return this.debugMode&&this.displayDebugReport(o),o}detectCSSConflicts(e,t){const i=window.getComputedStyle(e);["font-family","font-size","color","background-color","margin","padding","border","box-sizing"].forEach((n=>{const o=i.getPropertyValue(n);i.getPropertyPriority(n),this.isExternalStyle(e,n,o)&&t.push({property:n,widgetValue:this.getWidgetStyleValue(e,n),externalValue:o,specificity:this.calculateSpecificity(e,n),source:this.getStyleSource(e,n)})}))}checkStyleIsolation(e,t){e.getAttribute("data-widgetic-instance")||t.push("Add data-widgetic-instance attribute for proper namespace isolation");const i=window.getComputedStyle(e);Array.from(i).some((e=>e.startsWith("--widgetic-")))||t.push("Use CSS custom properties (--widgetic-*) for better theme isolation");const n=i.getPropertyValue("contain");n.includes("layout")&&n.includes("style")||t.push("Apply CSS containment (contain: layout style paint) for better isolation");"auto"===i.getPropertyValue("z-index")&&this.hasStackingContext(e)&&t.push("Consider explicit z-index management to prevent stacking conflicts")}calculateIsolationScore(e,t){let i=100;i-=10*t.length;const n=window.getComputedStyle(e),o=n.getPropertyValue("contain");o.includes("layout")||(i-=15),o.includes("style")||(i-=15),o.includes("paint")||(i-=10);"isolate"!==n.getPropertyValue("isolation")&&(i-=10);e.getAttribute("data-widgetic-instance")||(i-=15);return"border-box"!==n.getPropertyValue("box-sizing")&&(i-=5),Math.max(0,i)}isExternalStyle(e,t,i){const n=document.createElement(e.tagName.toLowerCase());n.style.cssText=e.getAttribute("style")||"",document.body.appendChild(n);const o=window.getComputedStyle(n).getPropertyValue(t);return document.body.removeChild(n),i!==o&&!this.isWidgetStyle(e,t)}isWidgetStyle(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return!1;return this.getMatchingCSSRules(e).some((e=>{var n;return(null===(n=e.selectorText)||void 0===n?void 0:n.includes(`[data-widgetic-instance="${i}"]`))&&e.style.getPropertyValue(t)}))}getWidgetStyleValue(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return"";const n=this.getMatchingCSSRules(e).find((e=>{var t;return null===(t=e.selectorText)||void 0===t?void 0:t.includes(`[data-widgetic-instance="${i}"]`)}));return(null==n?void 0:n.style.getPropertyValue(t))||""}calculateSpecificity(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return 0;const n=i.selectorText||"";let o=0;return o+=100*(n.match(/#/g)||[]).length,o+=10*(n.match(/[\.\[]/g)||[]).length,o+=(n.match(/[a-zA-Z]/g)||[]).length,o}getStyleSource(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return"unknown";if(i.parentStyleSheet){const e=i.parentStyleSheet;if(e.href)return e.href;if(e.ownerNode)return"inline styles"}return"unknown"}getMatchingCSSRules(e){const t=[];try{for(let i=0;i<document.styleSheets.length;i++){const n=document.styleSheets[i];try{const i=n.cssRules||n.rules;for(let n=0;n<i.length;n++){const o=i[n];o.selectorText&&e.matches(o.selectorText)&&t.push(o)}}catch(e){continue}}}catch(e){B.warn("Failed to analyze CSS rules",{error:e})}return t}hasStackingContext(e){const t=window.getComputedStyle(e),i=t.getPropertyValue("position"),n=t.getPropertyValue("z-index"),o=t.getPropertyValue("transform"),s=t.getPropertyValue("opacity");return"static"!==i&&"auto"!==n||"none"!==o||parseFloat(s)<1}addDebugStyles(){const e="widgetic-css-debug-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n /* CSS Debug Mode Styles */\n widgetic-widget[data-widgetic-instance] {\n outline: 2px dashed #007bff !important;\n outline-offset: 2px !important;\n position: relative !important;\n }\n\n widgetic-widget[data-widgetic-instance]::before {\n content: "Widget: " attr(data-widgetic-instance) !important;\n position: absolute !important;\n top: -20px !important;\n left: 0 !important;\n background: #007bff !important;\n color: white !important;\n padding: 2px 6px !important;\n font-size: 10px !important;\n font-family: monospace !important;\n z-index: 10000 !important;\n pointer-events: none !important;\n }\n\n widgetic-widget[data-error="true"] {\n outline-color: #dc3545 !important;\n }\n\n widgetic-widget[data-loading="true"] {\n outline-color: #ffc107 !important;\n }\n\n widgetic-widget[data-ready="true"] {\n outline-color: #28a745 !important;\n }\n ',document.head.appendChild(t)}removeDebugStyles(){const e=document.getElementById("widgetic-css-debug-styles");e&&e.remove()}displayDebugReport(e){}monitorWidget(e){if(this.trackedElements.has(e))return;this.trackedElements.add(e);new MutationObserver((e=>{e.forEach((e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.debugMode}))})).observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:["style","class"]})}}Fs.instance=null;const Ns=Fs.getInstance();function js(){Ns.enableDebugMode()}function Hs(){Ns.disableDebugMode()}class Vs{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){const i=this.listeners.get(e);return i&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}emit(e,...t){const i=this.listeners.get(e);return!(!i||0===i.size)&&(i.forEach((e=>{try{e(...t)}catch(e){}})),!0)}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}}class Ks extends Vs{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set;const e=new K({basePath:sn()});this.abTestingApi=new Di(e),this.compositionsApi=new Pi(e),this.widgetManager=_s.getInstance(),this.messenger=new _o,this.setupEventListeners()}static getInstance(){return Ks.instance||(Ks.instance=new Ks),Ks.instance}setupEventListeners(){this.widgetManager.addEventListener("widget_ready",(e=>{this.setupWidgetConversionTracking(e.widgetId)})),this.widgetManager.addEventListener("custom_event",(e=>{this.handleWidgetCustomEvent(e)})),this.widgetManager.addEventListener("media_play",(e=>{this.handleMediaEvent("plays",e)})),this.widgetManager.addEventListener("form_submit",(e=>{this.handleFormEvent("submissions",e)})),this.widgetManager.addEventListener("widget_click",(e=>{this.handleClickEvent(e)}))}getTestConfig(e){return t(this,void 0,void 0,(function*(){var i;try{const n=yield this.abTestingApi.getABTestConfig({id:e});if(!n)return U.warn("A/B test not found",{experimentId:e}),null;const o=(yield Promise.all((n.variants||[]).map((e=>t(this,void 0,void 0,(function*(){try{const t=e.composition_id||e.compositionId||"";return{id:e.id||"",compositionId:t,embedCode:this.generateEmbedCode(t),trafficPercentage:e.traffic_percentage||e.trafficPercentage||0}}catch(t){return U.error("Failed to fetch composition for variant",{variantId:e.id,compositionId:e.compositionId,error:t}),null}})))))).filter((e=>null!==e));if(0===o.length)return U.warn("No valid variants found for A/B test",{experimentId:e}),null;const s={experimentId:n.test_id||e,isActive:"running"===n.status,winningVariant:void 0,variants:o,successMetrics:n.success_metrics||["impressions"],primaryMetric:(null===(i=n.success_metrics)||void 0===i?void 0:i[0])||"impressions"};return U.info("A/B test config loaded",{experimentId:e,config:s}),s}catch(t){return t&&"object"==typeof t&&"status"in t&&404===t.status?(U.warn("A/B test not found",{experimentId:e}),null):(U.error("Failed to load A/B test config",{experimentId:e,error:t}),null)}}))}getVariantAssignment(e,i){return t(this,void 0,void 0,(function*(){try{const t=yield this.getTestConfig(e);if(!t)return null;if(t.winningVariant){const i=t.variants.find((e=>e.id===t.winningVariant));if(i){const t={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode};return localStorage.setItem(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t),i}}const n=this.selectVariant(t.variants,i);if(!n)return null;const o={variantId:n.id,compositionId:n.compositionId,embedCode:n.embedCode};return localStorage.setItem(`ab_test_${e}`,JSON.stringify(o)),this.assignments.set(e,o),yield this.setupConversionTracking(e,t,o),n}catch(t){return U.error("Failed to get variant assignment",{experimentId:e,error:t}),null}}))}setupConversionTracking(e,i,n){return t(this,void 0,void 0,(function*(){try{const t=yield this.findTrackingTargets(n.compositionId,i.successMetrics),o={experimentId:e,variantId:n.variantId,metrics:i.successMetrics,trackingTargets:t};this.conversionSetups.set(e,o),U.debug("Conversion tracking setup complete",{experimentId:e,trackingTargets:t})}catch(t){U.error("Failed to setup conversion tracking",{experimentId:e,error:t})}}))}findTrackingTargets(e,i){return t(this,void 0,void 0,(function*(){try{const e={},t={clicks:["button","a","[data-click-track]","[onclick]"],conversions:["form",'button[type="submit"]',"[data-conversion]"],plays:["video","audio","[data-play]",".play-button"],submissions:["form","[data-form]"],downloads:["a[download]","[data-download]"],signups:["form","[data-signup]",".signup-form"]};for(const n of i){const i=t[n]||[];e[n]=i}return e}catch(t){return U.error("Failed to find tracking targets",{compositionId:e,error:t}),{}}}))}selectorExistsInContent(e,t){const i=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")){const e=t.slice(1,-1);return i.includes(e)}if(t.startsWith(".")){const e=t.slice(1);return i.includes(`class="${e}"`)||i.includes(`class='${e}'`)}return i.includes(`<${t}`)}setupWidgetConversionTracking(e){return t(this,void 0,void 0,(function*(){for(const[t,i]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(e))continue;const n=this.messenger.createWidgetController(e);i.metrics.includes("clicks")&&(yield this.setupClickTracking(n,t,i.variantId)),(i.metrics.includes("submissions")||i.metrics.includes("conversions"))&&(yield this.setupFormTracking(n,t,i.variantId)),i.metrics.includes("plays")&&(yield this.setupMediaTracking(n,t,i.variantId)),U.debug("Widget conversion tracking setup",{widgetId:e,experimentId:t})}catch(i){U.error("Failed to setup widget conversion tracking",{widgetId:e,experimentId:t,error:i})}}))}setupClickTracking(e,i,n){return t(this,void 0,void 0,(function*(){e.subscribe("click",(e=>t(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"clicks",{element:e.element,timestamp:e.timestamp})})))),yield e.callFunction("setupEventListener","click",(e=>{var t;this.trackConversion(i,n,"clicks",{target:null===(t=e.target)||void 0===t?void 0:t.tagName,timestamp:Date.now()})}))}))}setupFormTracking(e,i,n){return t(this,void 0,void 0,(function*(){e.subscribe("form-submit",(e=>t(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"submissions",{formData:e.formData,timestamp:e.timestamp})})))),e.subscribe("conversion",(e=>t(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"conversions",{conversionType:e.type,value:e.value,timestamp:e.timestamp})}))))}))}setupMediaTracking(e,i,n){return t(this,void 0,void 0,(function*(){e.subscribe("media-play",(e=>t(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"plays",{mediaType:e.mediaType,duration:e.duration,timestamp:e.timestamp})}))))}))}handleWidgetCustomEvent(e){return t(this,void 0,void 0,(function*(){var t;for(const[i,n]of Array.from(this.conversionSetups.entries()))if((null===(t=e.data)||void 0===t?void 0:t.experimentId)===i){const t=e.data.conversionType||"custom";yield this.trackConversion(i,n.variantId,t,e.data)}}))}handleMediaEvent(e,i){return t(this,void 0,void 0,(function*(){for(const[t,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(e)&&(yield this.trackConversion(t,n.variantId,e,i.data))}))}handleFormEvent(e,i){return t(this,void 0,void 0,(function*(){for(const[t,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(e)&&(yield this.trackConversion(t,n.variantId,e,i.data))}))}handleClickEvent(e){return t(this,void 0,void 0,(function*(){for(const[t,i]of Array.from(this.conversionSetups.entries()))i.metrics.includes("clicks")&&(yield this.trackConversion(t,i.variantId,"clicks",e.data))}))}trackConversion(e,i,n,o,s){return t(this,void 0,void 0,(function*(){try{const t=`${e}_${i}_${(null==s?void 0:s.userId)||(null==s?void 0:s.sessionId)||"anonymous"}`;if(this.trackedConversions.has(t))return void U.debug("Conversion already tracked for this user",{experimentId:e,variantId:i,conversionType:n});const r={event_type:"conversion",data:Yo({experimentId:e,variantId:i,userId:null==s?void 0:s.userId,sessionId:(null==s?void 0:s.sessionId)||this.getSessionId(),conversionType:n,timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:r}),this.trackedConversions.add(t),this.emit("conversion",{experimentId:e,variantId:i,conversionType:n,data:o}),U.info("Conversion tracked",{experimentId:e,variantId:i,conversionType:n,data:o})}catch(t){U.error("Failed to track conversion",{experimentId:e,variantId:i,conversionType:n,error:t})}}))}trackImpression(e,i,n){return t(this,void 0,void 0,(function*(){try{const t={event_type:"impression",data:Yo({experimentId:e,variantId:i,userId:null==n?void 0:n.userId,sessionId:(null==n?void 0:n.sessionId)||this.getSessionId(),timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:t}),U.debug("Impression tracked",{experimentId:e,variantId:i})}catch(t){U.error("Failed to track impression",{experimentId:e,variantId:i,error:t})}}))}validateGoalTracking(e,i){return t(this,void 0,void 0,(function*(){const t=[],n=[];try{for(const n of e){const e=yield this.validateVariantCapabilities(n,i);t.push(...e)}if(t.length>0){const e=Array.from(new Set(t.map((e=>e.metric))));n.push(`Consider adding trackable elements to your compositions for: ${e.join(", ")}`),e.includes("clicks")&&n.push("Add clickable elements like buttons, links, or interactive components"),e.includes("submissions")&&n.push("Add form elements to track form submissions"),e.includes("plays")&&n.push("Add media elements (audio/video) to track media plays"),e.includes("conversions")&&n.push("Implement custom conversion tracking using widgetic:conversion events")}const o=0===t.length;return U.info("Goal tracking validation completed",{variants:e.length,successMetrics:i,issues:t.length,isValid:o}),{isValid:o,issues:t,recommendations:n}}catch(e){return U.error("Goal tracking validation failed",{error:e}),{isValid:!1,issues:[{variant:"all",metric:"system",reason:"Validation system error"}],recommendations:["Please try again or contact support"]}}}))}validateVariantCapabilities(e,i){return t(this,void 0,void 0,(function*(){const t=[];try{const n=document.createElement("div");n.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(n);try{const o={compositionId:e.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},s=`validation_${e.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(s,o,n)){const n=this.messenger.getWidgetController(s);let o=null;if(n)try{o=yield n.callFunction("getCapabilities",[])}catch(t){U.warn("Widget does not expose getCapabilities method",{compositionId:e.composition_id})}for(const n of i){const i=this.checkMetricSupport(e,n,o);i&&t.push(i)}yield this.widgetManager.unregisterWidget(s)}else for(const n of i)t.push({variant:e.name,metric:n,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(n)}}catch(n){U.error("Failed to validate variant capabilities",{variant:e.name,error:n});for(const n of i)t.push({variant:e.name,metric:n,reason:"Validation error occurred"})}return t}))}checkMetricSupport(e,t,i){var n;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(n=i.textCapabilities.fields)||void 0===n?void 0:n.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,n,o;if(["interactive","form","media","gallery"].includes(e.type))return!0;if(null===(t=e.mediaCapabilities)||void 0===t?void 0:t.supportsPlay)return!0;if(null===(i=e.contentCapabilities)||void 0===i?void 0:i.supportsNavigation)return!0;if(null===(o=null===(n=e.textCapabilities)||void 0===n?void 0:n.fields)||void 0===o?void 0:o.length)return!0;const s=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&s.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t){if(!e||0===e.length)return null;const i=t.userId||t.sessionId||"anonymous",n=this.createDeterministicHash(i),o=Math.abs(n)%100;let s=0;for(const t of e)if(s+=t.trafficPercentage,o<s)return t;return e[e.length-1]}createDeterministicHash(e){let t=0;for(let i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return t}createAssignment(e,i,n){return t(this,void 0,void 0,(function*(){try{const t=this.detectDeviceType(n.userAgent),o=Yo({experimentId:e,variantId:i.variantId,userId:n.userId,sessionId:n.sessionId||this.getSessionId(),userAgent:n.userAgent||navigator.userAgent,ipAddress:n.ipAddress,deviceType:t});yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),U.debug("Assignment created in backend",{experimentId:e,variantId:i.variantId})}catch(t){U.error("Failed to create assignment in backend",{experimentId:e,error:t})}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){let e=localStorage.getItem("widgetic_session_id");return e||(e="session_"+Math.random().toString(36).substr(2,9)+"_"+Date.now(),localStorage.setItem("widgetic_session_id",e)),e}detectDeviceType(e){if(!e)return"desktop";const t=e.toLowerCase();return/tablet|ipad|playbook|silk/.test(t)?"tablet":/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(t)?"mobile":"desktop"}}Ks.instance=null;class Gs{constructor(e){this.deviceDetector=Jn(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},e),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),B.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Gs.instance&&e&&(Gs.instance=new Gs(e)),!Gs.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Gs.instance}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){B.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){B.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(B.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),B.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):B.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return t(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),B.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){B.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return t(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void B.warn("[AnalyticsTracker] No API endpoint configured");const i=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),n=yield en(),o=new K({basePath:this.config.apiEndpoint,accessToken:()=>t(this,void 0,void 0,(function*(){return n})),headers:{"X-SDK-Version":`embed-sdk/${Hi}`}}),s=new Li(o);yield s.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:i}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){B.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],B.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){B.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),B.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),B.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),Gs.instance=null,B.debug("[AnalyticsTracker] Destroyed")}}const Ys="undefined"!=typeof HTMLElement?HTMLElement:class{};class Qs extends Ys{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=Ks.getInstance(),this.widgetManager=_s.getInstance(),this.analyticsTracker=Gs.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return t(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return U.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};if(this.renderLoading(),this.assignment=yield this.manager.getVariantAssignment(this.experimentId,e),!this.assignment)return U.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),U.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){U.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){t!==i&&"experiment-id"===e&&this.connectedCallback()}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return t(this,void 0,void 0,(function*(){var e,t,i;if(this.assignment&&this.shadowRoot)try{const i=document.createElement("div");i.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",i.setAttribute("data-ab-experiment",this.experimentId||""),i.setAttribute("data-ab-variant",this.assignment.variantId);const n=this.createEmbedElement(this.assignment.embedCode);if(n){i.appendChild(n);const o={compositionId:this.assignment.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${this.assignment.variantId}_${Date.now()}`,o,n),this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",this.assignment.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(i),this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId},bubbles:!0}))}catch(e){U.error("Failed to render variant",{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}createEmbedElement(e){var t;try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return U.warn("No element found in embed code",{embedCode:e}),null;const o=n.cloneNode(!0);return o.setAttribute("data-ab-experiment",this.experimentId||""),o.setAttribute("data-ab-variant",(null===(t=this.assignment)||void 0===t?void 0:t.variantId)||""),o}catch(t){return U.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),U.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){U.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target;this.isClickableElement(i)&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",{element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||"",timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target;"FORM"===t.tagName&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",{formId:t.id||"unknown",timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",{mediaType:t.tagName.toLowerCase(),duration:t.duration||0,timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return t(this,void 0,void 0,(function*(){if(!this.impressionTracked&&this.experimentId&&this.assignment)try{const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};yield this.manager.trackImpression(this.experimentId,this.assignment.variantId,e),this.impressionTracked=!0,this.analyticsTracker.trackCompositionView({experiment_id:this.experimentId,variant_id:this.assignment.variantId,composition_id:this.assignment.compositionId}),U.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){U.error("Failed to track impression",{experimentId:this.experimentId,error:e})}}))}handleConversionEvent(e){this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),this.analyticsTracker.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;U.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;U.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}cleanup(){if(this.conversionListeners.forEach((e=>e())),this.conversionListeners.clear(),this.widgetInstance)try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){U.warn("Failed to cleanup widget instance",{error:e})}this.impressionTracked=!1,this.assignment=null,this.widgetInstance=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",Qs))}}Qs.register();const Js="undefined"!=typeof HTMLElement?HTMLElement:class{};class Xs extends Js{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.widgetManager=Ps(),B.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)B.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return B.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");B.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){B.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return t(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(B.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),B.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),B.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){B.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return t(this,void 0,void 0,(function*(){try{const t=sn(),i=new K({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new Bi(i),o=yield n.getTranslationConfig({id:e});return(null==o?void 0:o.data)||null}catch(e){throw B.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";B.debug("[TranslationElement] Available languages:",i),B.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return B.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return B.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{B.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}B.debug("[TranslationElement] No matches found, falling back to root language:",n);const o=e[0]||"unknown";return this.trackFallbackUsage(o,n,"root_fallback").catch((e=>{B.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return t(this,void 0,void 0,(function*(){const t=Mn(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{B.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){B.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return t(this,void 0,void 0,(function*(){try{const t=sn(),i=new K({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new Bi(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){B.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,i,n){return t(this,void 0,void 0,(function*(){try{const t={eventType:"fallback_used",language:i,compositionId:this.getCompositionForLanguage(i)||"",metadata:{requestedLanguage:e,selectedLanguage:i,fallbackType:n,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(t),B.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:i,fallbackType:n})}catch(e){B.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return t(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,B.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){B.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",Xs),B.info("[TranslationElement] Custom element registered")))}catch(e){B.error("[TranslationElement] Failed to register custom element:",e)}}}Xs.register();const Zs={WidgeticWidget:Eo,registerWidgeticWidget:Co,getSDK:$s,setApiKey:Zi,setTokenProvider:Qi,StaticApiKeyProvider:$,EndpointTokenProvider:F,FunctionTokenProvider:N,getConfiguration:cn},er={WidgetRenderer:jo,getWidgetRenderer:Vo,CustomElementRenderer:Oo,IframeRenderer:No,AuthManager:ji,detectBrowserCapabilities:lo,determineBestRenderMode:po,parseWidgetConfig:un,generateInstanceId:Mn,isValidWidgetElement:Ln},tr={BatchApiClient:vo,getBatchClient:wo,ModuleLoader:Io,getModuleLoader:ko,WidgeticMessenger:_o,getMessenger:zo,config:Yi,getApiUrl:nn,getCdnUrl:on,getTokenProvider:Ji,getAuthToken:en,DefaultTokenProvider:j,CSSDebugger:Fs,cssDebugger:Ns,enableCSSDebug:js,disableCSSDebug:Hs,log:B},ir=$s();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(Co(),Qs.register(),Xs.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=ir,window.Widgetic={SDK:ir,getSDK:$s,EmbedSDK:Us,config:{API_URL:Yi.API_URL,API_VERSION:Yi.API_VERSION,CLIENT_URL:Yi.CLIENT_URL,PRODUCTION_URL:Yi.PRODUCTION_URL,NODE_ENV:Yi.NODE_ENV},log:B,WidgeticWidget:Eo,registerWidgeticWidget:Co,cssDebugger:Ns,enableCSSDebug:()=>Ns.enableDebugMode(),disableCSSDebug:()=>Ns.disableDebugMode(),analyzeWidget:e=>Ns.analyzeWidget(e),ABTestManager:Ks,ABTestElement:Qs,TranslationElement:Xs});class nr{constructor(){this.textStates=new Map,this.debounceTimers=new Map,this.storageKey="widgetic-text-fields",this.storageVersion="1.0",this.maxStorageAge=6048e5,this.autoRestoreEnabled=!0,this.initialized=!1,this.securityManager=ks(),this.initialize()}static getInstance(){return nr.instance||(nr.instance=new nr),nr.instance}initialize(){this.initialized||(mo()?(this.loadStoredState(),this.cleanupOldEntries(),this.initialized=!0,B.info("[TextFieldManager] Initialized successfully")):B.warn("[TextFieldManager] localStorage not available, text persistence disabled"))}registerTextField(e,t,i={}){const n=this.generateStateKey(e,t);B.debug(`[TextFieldManager] Registering text field: ${e}.${t}`,{config:i});const o=this.textStates.get(n);return o&&i.autoRestore&&this.shouldAutoRestore(o,i)&&B.debug(`[TextFieldManager] Auto-restoring text for ${n}`,{textLength:o.text.length,lastModified:new Date(o.lastModified)}),n}updateTextField(e,t,i,n={},o){const s=this.securityManager.validateTextFieldUpdate(e,t,i,o);if(!s.allowed)return B.warn(`[TextFieldManager] Security validation failed for ${e}.${t}`,{reason:s.reason,severity:s.severity}),void("undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e,fieldId:t,reason:s.reason,severity:s.severity,originalTextLength:i.length,timestamp:Date.now()}})));const r=s.sanitizedText||i,a=this.generateStateKey(e,t);let d=r;n.maxLength&&r.length>n.maxLength&&(B.warn(`[TextFieldManager] Text exceeds maxLength (${n.maxLength}), truncating`),d=r.substring(0,n.maxLength));const c={instanceId:e,fieldId:t,text:d,lastModified:Date.now(),textType:n.textType||"custom",metadata:Object.assign(Object.assign({},o),{characterCount:d.length,wordCount:this.countWords(d),sanitized:r!==i})};this.textStates.set(a,c),n.autoPersist&&n.persistState&&this.debouncePersist(a,n.debounceDelay||1e3),B.debug(`[TextFieldManager] Updated text field: ${a}`,{textLength:d.length,textType:c.textType,sanitized:r!==i})}getTextField(e,t){const i=this.generateStateKey(e,t);return this.textStates.get(i)||null}getWidgetTextFields(e){const t=[];for(const[i,n]of this.textStates)n.instanceId===e&&t.push(n);return t}clearTextField(e,t){const i=this.generateStateKey(e,t);this.textStates.delete(i),this.clearDebounceTimer(i),this.persistState(),B.debug(`[TextFieldManager] Cleared text field: ${i}`)}clearWidgetTextFields(e){const t=[];for(const[i,n]of this.textStates)n.instanceId===e&&t.push(i);t.forEach((e=>{this.textStates.delete(e),this.clearDebounceTimer(e)})),this.persistState(),B.debug(`[TextFieldManager] Cleared ${t.length} text fields for widget: ${e}`)}persistTextFields(){this.persistState()}shouldAutoRestore(e,t){if(!this.autoRestoreEnabled||!t.autoRestore)return!1;const i=t.autoRestoreTimeout||864e5;return Date.now()-e.lastModified<=i&&e.text.trim().length>0}generateStateKey(e,t){return`${e}:${t}`}debouncePersist(e,t){this.clearDebounceTimer(e);const i=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(e)}),t);this.debounceTimers.set(e,i)}clearDebounceTimer(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e))}loadStoredState(){try{const e=localStorage.getItem(this.storageKey);if(!e)return;const t=JSON.parse(e);if(t.version!==this.storageVersion)return B.info("[TextFieldManager] Storage version mismatch, clearing stored data"),void localStorage.removeItem(this.storageKey);t.textStates&&(this.textStates=new Map(Object.entries(t.textStates)),B.debug(`[TextFieldManager] Loaded ${this.textStates.size} text field states from storage`)),"boolean"==typeof t.autoRestoreEnabled&&(this.autoRestoreEnabled=t.autoRestoreEnabled)}catch(e){B.warn("[TextFieldManager] Failed to load stored state:",e),localStorage.removeItem(this.storageKey)}}persistState(){if(mo())try{const e={version:this.storageVersion,textStates:Object.fromEntries(this.textStates),timestamp:Date.now(),autoRestoreEnabled:this.autoRestoreEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e)),B.debug(`[TextFieldManager] Persisted state for ${this.textStates.size} text fields`)}catch(e){B.warn("[TextFieldManager] Failed to persist state:",e)}}cleanupOldEntries(){const e=Date.now()-this.maxStorageAge,t=[];for(const[i,n]of this.textStates)n.lastModified<e&&t.push(i);t.length>0&&(t.forEach((e=>this.textStates.delete(e))),this.persistState(),B.debug(`[TextFieldManager] Cleaned up ${t.length} old text field entries`))}countWords(e){return e.trim().split(/\s+/).filter((e=>e.length>0)).length}setAutoRestoreEnabled(e){this.autoRestoreEnabled=e,this.persistState(),B.debug("[TextFieldManager] Auto-restore "+(e?"enabled":"disabled"))}getStats(){const e=Array.from(this.textStates.values()),t=e.reduce(((e,t)=>e+t.text.length),0),i=e.map((e=>e.lastModified));return{totalFields:e.length,totalCharacters:t,avgCharactersPerField:e.length>0?Math.round(t/e.length):0,oldestEntry:i.length>0?Math.min(...i):null,newestEntry:i.length>0?Math.max(...i):null}}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.textStates.clear(),mo()&&localStorage.removeItem(this.storageKey),B.debug("[TextFieldManager] Cleaned up all data")}configureSecurity(e){this.securityManager.updateConfig(e),B.debug("[TextFieldManager] Security configuration updated")}isInstanceBlocked(e){return this.securityManager.isInstanceBlocked(e)}isInstanceSuspicious(e){return this.securityManager.isInstanceSuspicious(e)}unblockInstance(e){this.securityManager.unblockInstance(e),B.info(`[TextFieldManager] Unblocked instance: ${e}`)}getSecurityStats(){return this.securityManager.getSecurityStats()}validateText(e,t,i,n){return this.securityManager.validateTextFieldUpdate(e,t,i,n)}}function or(){return nr.getInstance()}var sr=Object.freeze({__proto__:null,TextFieldManager:nr,getTextField:function(e,t){return or().getTextField(e,t)},getTextFieldManager:or,registerTextField:function(e,t,i){return or().registerTextField(e,t,i)},updateTextField:function(e,t,i,n,o){or().updateTextField(e,t,i,n,o)}});e.ABTestElement=Qs,e.ABTestManager=Ks,e.AuthError=Ni,e.AuthManager=ji,e.BatchApiClient=vo,e.CSSDebugger=Fs,e.CustomElementRenderer=Oo,e.DefaultTokenProvider=j,e.EmbedSDK=Us,e.EndpointTokenProvider=F,e.FunctionTokenProvider=N,e.HighLevelAPI=Zs,e.IframeRenderer=No,e.LowLevelAPI=tr,e.MidLevelAPI=er,e.ModuleLoader=Io,e.StaticApiKeyProvider=$,e.TranslationElement=Xs,e.WidgetRenderer=jo,e.WidgeticEmbedSDK=Us,e.WidgeticMessenger=_o,e.WidgeticWidget=Eo,e.analyzeWidgetCSS=function(e){return Ns.analyzeWidget(e)},e.config=Yi,e.cssDebugger=Ns,e.default=ir,e.detectBrowserCapabilities=lo,e.determineBestRenderMode=po,e.disableCSSDebug=Hs,e.enableCSSDebug=js,e.generateInstanceId=Mn,e.getApiUrl=nn,e.getAuthManager=Xi,e.getAuthToken=en,e.getBatchClient=wo,e.getCdnUrl=on,e.getConfiguration=cn,e.getMessenger=zo,e.getModuleLoader=ko,e.getSDK=$s,e.getTokenProvider=Ji,e.getWidgetRenderer=Vo,e.isValidWidgetElement=Ln,e.log=B,e.monitorWidgetCSS=function(e){Ns.monitorWidget(e)},e.parseWidgetConfig=un,e.registerWidgeticWidget=Co,e.resetBatchClient=function(){yo=null},e.resetMessenger=function(){Po&&(Po.cleanup(),Po=null)},e.resetModuleLoader=function(){To=null},e.resetWidgetRenderer=function(){Ho&&Ho.cleanupAll(),Ho=null},e.setApiKey=Zi,e.setTokenProvider=Qi,e.toCamel=Go,e.toSnake=Yo,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@widgetic/api-sdk")):"function"==typeof define&&define.amd?define(["exports","@widgetic/api-sdk"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["widgeticEmbed-sdk"]={},e.apiSdk)}(this,(function(e,t){"use strict";function i(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{d(n.next(e))}catch(e){o(e)}}function a(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}d((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const n="https://api.axiom.co/v1",s="widgetic-performance",o="https://events.statsigapi.net/v1/custom",r=!0,a=1,d=1e3,c=2500,l=2e3,u=100,h=50,g=.1,p=.05,m=3e3,v=2e3,f=5e5,y=3e5,b=!1,w="info",I="2.0.3",E="2.0.3";function S(){var e;return`${"undefined"!=typeof process&&"development"===(null===(e={NODE_ENV:"production"})||void 0===e?void 0:e.NODE_ENV)?T.DEV_API_URL:T.PROD_API_URL}${T.VERSION}`}const T={DEV_API_URL:"http://localhost:3000",PROD_API_URL:"https://api.widgetic.com",PROD_CLIENT_URL:"https://widgetic.com",PROD_CDN_URL:"https://cdn.widgetic.com",VERSION:"/api/v1",ENABLE_EDITING:!0},k=350,C=200;let x=b;const A={get enabled(){return x},logLevel:w},M=["apikey","api_key","api-key","servicekey","service_key","service-key","token","access_token","auth_token","secret","password","private_key","authorization","bearer","internal_key","public_api_key","public_internal_key"];function L(e){if("string"==typeof e){const t=e.toLowerCase();for(const i of M)if(t.includes(i))return e.replace(/([a-zA-Z_-]*(?:key|token|secret|password)[a-zA-Z_-]*[:\s=]+)([^\s,}]+)/gi,"$1[REDACTED]");return e}if(null==e)return e;if(Array.isArray(e))return e.map(L);if("object"==typeof e){const t={};for(const[i,n]of Object.entries(e)){const e=i.toLowerCase();M.some((t=>e.includes(t.toLowerCase())||e===t.toLowerCase()))&&"string"==typeof n&&n.length>0?t[i]=`[REDACTED_${n.length}_CHARS]`:t[i]=L(n)}return t}return e}const D=new class{constructor(e=A.logLevel){this.logLevels={debug:0,info:1,warn:2,error:3},this.currentLevel=this.logLevels[e]}shouldLog(e){return A.enabled&&this.logLevels[e]>=this.currentLevel}formatMessage(e,t,...i){const n=(new Date).toISOString();return[`${`[Widgetic SDK] [${e.toUpperCase()}] [${n}]`} ${t}`,...i.map(L)]}debug(e,...t){this.shouldLog("debug")}info(e,...t){this.shouldLog("info")}warn(e,...t){this.shouldLog("warn")}error(e,...t){this.shouldLog("error")}setLevel(e){this.currentLevel=this.logLevels[e]}setDebug(e){!function(e){x=e}(e)}},O={debug:(e,...t)=>D.debug(e,...t),info:(e,...t)=>D.info(e,...t),warn:(e,...t)=>D.warn(e,...t),error:(e,...t)=>D.error(e,...t),setLevel:e=>D.setLevel(e)};class W{constructor(e){this.apiKey=e}getToken(){return i(this,void 0,void 0,(function*(){return this.apiKey}))}isTokenValid(){return i(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class R{constructor(e){this.tokenEndpoint=e.tokenEndpoint||e.endpoint||"",this.refreshEndpoint=e.refreshEndpoint,this.headers=e.headers||{},e.apiKey&&!this.headers.Authorization&&(this.headers.Authorization=`Bearer ${e.apiKey}`)}getToken(){return i(this,void 0,void 0,(function*(){if(this.cachedToken&&(yield this.isTokenValid()))return this.cachedToken;const e=yield fetch(this.tokenEndpoint,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.headers)});if(!e.ok)throw new Error(`Failed to fetch token: ${e.status} ${e.statusText}`);const t=yield e.json();if(this.cachedToken=t.token||t.access_token||t.apiKey,t.expires_in?this.tokenExpiry=Date.now()+1e3*t.expires_in:t.expires_at&&(this.tokenExpiry=new Date(t.expires_at).getTime()),!this.cachedToken)throw new Error("Invalid token response: no token found");return this.cachedToken}))}refreshToken(){return i(this,void 0,void 0,(function*(){if(!this.refreshEndpoint)return this.getToken();const e=yield fetch(this.refreshEndpoint,{method:"POST",headers:Object.assign({"Content-Type":"application/json",Authorization:`Bearer ${this.cachedToken}`},this.headers)});if(!e.ok)throw new Error(`Failed to refresh token: ${e.status} ${e.statusText}`);const t=yield e.json();if(this.cachedToken=t.token||t.access_token||t.apiKey,t.expires_in&&(this.tokenExpiry=Date.now()+1e3*t.expires_in),!this.cachedToken)throw new Error("Invalid token response: no token found");return this.cachedToken}))}isTokenValid(){return i(this,void 0,void 0,(function*(){return!!this.cachedToken&&(!this.tokenExpiry||Date.now()<this.tokenExpiry)}))}}class P{constructor(e,t){this.tokenFunction=e,this.validationFunction=t}getToken(){return i(this,void 0,void 0,(function*(){return yield this.tokenFunction()}))}isTokenValid(){return i(this,void 0,void 0,(function*(){return!this.validationFunction||(yield this.validationFunction())}))}}class z{constructor(e){this.apiKey=e}getToken(){return i(this,void 0,void 0,(function*(){if(!this.apiKey)throw new Error("No API key available. Please configure a TokenProvider or set API keys.");return this.apiKey}))}isTokenValid(){return i(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class _ extends Error{constructor(e,t,i){super(e),this.code=t,this.statusCode=i,this.name="AuthError"}}class F{constructor(e={}){var t,i;this.currentToken=null,this.apiKey=null,this.refreshTimer=null,this.config=Object.assign({apiUrl:e.apiUrl||S(),debug:e.debug||!1},e),this.apiKey=e.apiKey||"undefined"!=typeof process&&((null===(t={NODE_ENV:"production"})||void 0===t?void 0:t.PUBLIC_API_KEY)||(null===(i={NODE_ENV:"production"})||void 0===i?void 0:i.API_KEY))||null}createTokensApiForApiKey(e){const n=new t.Configuration({basePath:this.config.apiUrl,apiKey:()=>i(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${E}`}});return new t.TokensApi(n)}createTokensApiForAccessToken(e){const n=new t.Configuration({basePath:this.config.apiUrl,accessToken:()=>i(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${E}`}});return new t.TokensApi(n)}setApiKey(e){this.apiKey=e,this.currentToken={token:e,tokenType:"API-Key",expiresAt:null,scopes:[]},this.config.debug&&O.debug("AuthManager: API key set")}getValidToken(e){return i(this,void 0,void 0,(function*(){if(this.currentToken&&this.isTokenValid(this.currentToken)){if(F.validatedTokens.has(this.currentToken.token))return this.currentToken.token;if(yield this.validateToken())return this.currentToken.token}if(this.apiKey)return yield this.exchangeApiKeyForJWT(e),this.currentToken.token;throw new _("No authentication method available","NO_AUTH_METHOD")}))}exchangeApiKeyForJWT(e){return i(this,void 0,void 0,(function*(){var t;if(!this.apiKey)throw new _("No API key available for exchange","NO_API_KEY");const i={scopes:(null==e?void 0:e.scopes)||this.getDefaultScopes(),expiresIn:(null==e?void 0:e.expiresIn)||1800};try{const e=this.createTokensApiForApiKey(this.apiKey),n=yield e.exchangeToken({exchangeTokenRequest:i}),s=(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.token)||(null==n?void 0:n.token);if(!s)throw new _("Token exchange response missing token","INVALID_RESPONSE");const o=(null==n?void 0:n.data)||n,r={token:s,tokenType:o.tokenType||"Bearer",expiresAt:o.expiresAt?o.expiresAt instanceof Date?o.expiresAt.toISOString():String(o.expiresAt):null,scopes:o.scopes||[]};return this.setToken(r),this.config.debug&&O.info("AuthManager: Token exchanged successfully",{scopes:r.scopes,expiresAt:r.expiresAt}),r}catch(e){const t=e instanceof _?e:new _(`Token exchange failed: ${e instanceof Error?e.message:String(e)}`,"TOKEN_EXCHANGE_ERROR");throw this.config.onAuthError&&this.config.onAuthError(t),t}}))}validateToken(){return i(this,void 0,void 0,(function*(){var e;if(!this.currentToken)return!1;if(F.validatedTokens.has(this.currentToken.token))return!0;try{const t=this.createTokensApiForAccessToken(this.currentToken.token),i=yield t.validateToken();return!0===(null==i?void 0:i.success)&&!0===(null===(e=i.data)||void 0===e?void 0:e.valid)||!0===(null==i?void 0:i.valid)?(F.validatedTokens.add(this.currentToken.token),!0):(this.clearToken(),!1)}catch(e){return this.config.debug&&O.warn("AuthManager: Token validation failed",e),!1}}))}setToken(e){this.currentToken=e,e.expiresAt&&this.scheduleTokenRefresh(e),this.config.onTokenRefreshed&&this.config.onTokenRefreshed(e.token)}clearToken(){this.currentToken&&F.validatedTokens.delete(this.currentToken.token),this.currentToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}isTokenValid(e){if(!e.expiresAt)return!0;const t=new Date(e.expiresAt).getTime();return Date.now()<t-6e4}scheduleTokenRefresh(e){if(!e.expiresAt||!this.apiKey)return;const t=new Date(e.expiresAt).getTime()-Date.now()-3e5;t>0&&(this.refreshTimer=setTimeout((()=>i(this,void 0,void 0,(function*(){try{yield this.exchangeApiKeyForJWT({scopes:e.scopes}),this.config.debug&&O.info("AuthManager: Token refreshed automatically")}catch(e){this.config.debug&&O.error("AuthManager: Automatic token refresh failed",e),this.config.onTokenExpired&&this.config.onTokenExpired()}}))),t))}getDefaultScopes(){return["compositions:read","widgets:read","projects:read"]}getCurrentTokenInfo(){return this.currentToken}hasAuthMethod(){return!(!this.apiKey&&!this.currentToken)}dispose(){this.clearToken(),this.apiKey=null,this.config.debug&&O.debug("AuthManager: Disposed")}}F.validatedTokens=new Set;const $=I,N={};let U=null,H=null;const j={API_URL:T.PROD_API_URL,API_VERSION:T.VERSION,CLIENT_URL:T.PROD_CLIENT_URL,PRODUCTION_URL:T.PROD_CDN_URL,NODE_ENV:"production",ENABLE_EDITING:T.ENABLE_EDITING,API_KEY:N.PUBLIC_API_KEY,AXIOM_API_KEY:N.PUBLIC_AXIOM_API_KEY,STATSIG_KEY:N.PUBLIC_STATSIG_KEY};function B(e){U=e}function V(){return U}function K(){return H||(H=new F({apiUrl:Q(),debug:ee.enabled})),H}function q(e){K().setApiKey(e)}function G(){return i(this,void 0,void 0,(function*(){if(H&&H.hasAuthMethod())try{return yield H.getValidToken()}catch(e){}if(U)return yield U.getToken();const e=j.API_KEY;if(!e)throw new Error("No authentication method available. Please configure an API key, TokenProvider, or set PUBLIC_API_KEY in environment variables.");return e}))}function Y(e){const t=U;if(!t){const e=j.API_KEY;return{apiKey:e,basePath:Q(),tokenProvider:e?new z(e):void 0}}return{basePath:Q(),tokenProvider:t}}function Q(){return j.API_URL}function J(){return j.PRODUCTION_URL}function X(){return`${Q()}${j.API_VERSION}`}Q();const Z={width:k,height:C},ee={enabled:b},te={AXIOM_API_KEY:j.AXIOM_API_KEY||"",AXIOM_DATASET:s,AXIOM_API_ENDPOINT:n,STATSIG_API_KEY:j.STATSIG_KEY||"",STATSIG_API_ENDPOINT:o,ENABLE_PERFORMANCE_TRACKING:r,PERFORMANCE_SAMPLE_RATE:a,LCP_THRESHOLD:c,LCP_WARNING_THRESHOLD:l,FID_THRESHOLD:u,FID_WARNING_THRESHOLD:h,CLS_THRESHOLD:g,CLS_WARNING_THRESHOLD:p,WIDGET_LOAD_THRESHOLD:m,WIDGET_LOAD_WARNING_THRESHOLD:v,BUNDLE_SIZE_THRESHOLD:f,BUNDLE_SIZE_WARNING_THRESHOLD:y,MAX_METRICS_BUFFER:d};function ie(){return Y()}const ne=2147483647;function se(e){const t=e.getAttribute("composition-id");if(!t)throw new Error("Missing required composition-id attribute");return{compositionId:t,renderMode:oe(e.getAttribute("render-mode")),displayMode:re(e.getAttribute("display-mode")),resize:ae(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||Z.width,height:parseInt(e.getAttribute("height")||"")||Z.height,autoscale:Ee(e),adaptive:de(e.getAttribute("adaptive")),responsive:ce(e.getAttribute("responsive")),device:Oe(e),fullscreen:le(e),triggers:Ae(e),overlay:he(e),popup:we(e),media:Ce(e),content:xe(e)}}function oe(e){switch(e){case"iframe":case"custom-element":return e;default:return"auto"}}function re(e){switch(e){case"overlay":case"popup":case"fullscreen":case"modal":return e;default:return"inline"}}function ae(e){switch(e){case"fill-width":case"fill-height":case"fixed":case"fixed-height":case"fixed-width":case"allow-scale-down":case"fill":return e;default:return"fixed"}}function de(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function ce(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function le(e){if("enabled"===e.getAttribute("fullscreen")||"true"===e.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:ue(e.getAttribute("fullscreen-trigger")),showControls:"false"!==e.getAttribute("fullscreen-controls"),exitOnEscape:"false"!==e.getAttribute("fullscreen-exit-on-escape"),allowAutoEnter:"true"===e.getAttribute("fullscreen-auto-enter")}}function ue(e){switch(e){case"click":case"double-click":case"hover":case"auto":case"manual":return e;default:return"click"}}function he(e){if("enabled"===e.getAttribute("overlay")||"true"===e.getAttribute("overlay-enabled"))return{enabled:!0,position:ye(e.getAttribute("overlay-position")),backdrop:pe(e),background:me(e,pe(e)),closeOnBackdropClick:"false"!==e.getAttribute("overlay-close-on-backdrop"),closeOnEscape:"false"!==e.getAttribute("overlay-close-on-escape"),showCloseButton:"false"!==e.getAttribute("overlay-close-button"),trigger:ve(e.getAttribute("overlay-trigger")),width:e.getAttribute("overlay-width")||void 0,height:e.getAttribute("overlay-height")||void 0,maxWidth:e.getAttribute("overlay-max-width")||void 0,maxHeight:e.getAttribute("overlay-max-height")||void 0,zIndex:parseInt(e.getAttribute("overlay-z-index")||"")||void 0,animation:fe(e.getAttribute("overlay-animation")),overlayWidth:e.getAttribute("overlay-width")||void 0,overlayHeight:e.getAttribute("overlay-height")||void 0,overlayResize:be(e.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==e.getAttribute("keep-dimensions"),embedTarget:e.getAttribute("embed-target")||void 0}}function ge(e){return"true"===e.getAttribute("overlay-backdrop")}function pe(e){return"false"!==e.getAttribute("overlay-backdrop")}function me(e,t){if(!t)return;const i=e.getAttribute("overlay-background-color")||void 0,n=e.getAttribute("overlay-background-opacity"),s=null===n?Number.NaN:Number(n);return{enabled:!0,color:i,opacity:Number.isFinite(s)?s:void 0}}function ve(e){switch(e){case"click":case"hover":case"manual":case"auto":return e;default:return"click"}}function fe(e){switch(e){case"fade":case"slide-up":case"slide-down":case"slide-left":case"slide-right":case"zoom":case"bounce":case"none":return e;case"scale":return"zoom";case"slide":return"slide-up";default:return"fade"}}function ye(e){switch(e){case"top":case"bottom":case"left":case"right":case"top-left":case"top-right":case"bottom-left":case"bottom-right":return e;case"top-center":return"top";case"center-left":return"left";case"center-right":return"right";case"bottom-center":return"bottom";default:return"center"}}function be(e){switch(e){case"fillWidth":return"fill-width";case"fillHeight":return"fill-height";case"fixedSize":return"fixed";case"fixedHeight":return"fixed-height";case"fixedWidth":return"fixed-width";case"allowScaleDown":return"allow-scale-down";case"fill":return"fill";default:return}}function we(e){if("enabled"===e.getAttribute("popup")||"true"===e.getAttribute("popup-enabled"))return{enabled:!0,trigger:Ie(e.getAttribute("popup-trigger")),width:parseInt(e.getAttribute("popup-width")||"")||void 0,height:parseInt(e.getAttribute("popup-height")||"")||void 0,centerScreen:"false"!==e.getAttribute("popup-center"),allowResize:"true"===e.getAttribute("popup-resizable"),showToolbar:"true"===e.getAttribute("popup-toolbar"),target:e.getAttribute("popup-target")||void 0}}function Ie(e){switch(e){case"click":case"manual":return e;default:return"click"}}function Ee(e){const t=e.getAttribute("autoscale");return!!t&&(("true"===t||""===t||"false"!==t)&&(Se(e)||!0))}function Se(e){return e.getAttribute("autoscale-min-height")||e.getAttribute("autoscale-max-height")||e.getAttribute("autoscale-debounce")||e.getAttribute("autoscale-threshold")||e.getAttribute("autoscale-animate")||e.getAttribute("autoscale-animation-duration")?{enabled:!0,minHeight:parseInt(e.getAttribute("autoscale-min-height")||"")||void 0,maxHeight:parseInt(e.getAttribute("autoscale-max-height")||"")||void 0,debounceDelay:parseInt(e.getAttribute("autoscale-debounce")||"")||void 0,threshold:parseInt(e.getAttribute("autoscale-threshold")||"")||void 0,animate:"false"!==e.getAttribute("autoscale-animate"),animationDuration:parseInt(e.getAttribute("autoscale-animation-duration")||"")||void 0}:null}function Te(e){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function ke(e){return"widgetic"===e.tagName.toLowerCase()&&e.hasAttribute("composition-id")}function Ce(e){const t={},i=e.getAttribute("media-auto-pause")||e.getAttribute("data-media-auto-pause");null!==i&&(t.autoPause="true"===i||""===i);const n=e.getAttribute("media-type")||e.getAttribute("data-media-type");n&&["audio","video","both"].includes(n)&&(t.mediaType=n);const s=e.getAttribute("media-priority")||e.getAttribute("data-media-priority");if(s){const e=parseInt(s,10);!isNaN(e)&&e>=0&&e<=10&&(t.priority=e)}const o=e.getAttribute("media-persist-state")||e.getAttribute("data-media-persist-state");null!==o&&(t.persistState="true"===o||""===o);const r=e.getAttribute("media-allow-simultaneous")||e.getAttribute("data-media-allow-simultaneous");if(r){const e=r.split(",").map((e=>e.trim())).filter((e=>["audio","video"].includes(e)));e.length>0&&(t.allowSimultaneous=e)}const a=e.getAttribute("media-auto-resume")||e.getAttribute("data-media-auto-resume");null!==a&&(t.autoResume="true"===a||""===a);const d=e.getAttribute("media-auto-resume-timeout")||e.getAttribute("data-media-auto-resume-timeout");if(d){const e=parseInt(d,10);!isNaN(e)&&e>0&&(t.autoResumeTimeout=e)}const c=e.getAttribute("media-global-volume")||e.getAttribute("data-media-global-volume");return null!==c&&(t.globalVolume="true"===c||""===c),t}function xe(e){const t={},i=e.getAttribute("content-type")||e.getAttribute("data-content-type");i&&["gallery","carousel","slider","stepper","tabs","list","custom"].includes(i)&&(t.contentType=i);const n=e.getAttribute("content-persist-state")||e.getAttribute("data-content-persist-state");null!==n&&(t.persistState="true"===n||""===n);const s=e.getAttribute("content-auto-resume")||e.getAttribute("data-content-auto-resume");null!==s&&(t.autoResume="true"===s||""===s);const o=e.getAttribute("content-auto-resume-timeout")||e.getAttribute("data-content-auto-resume-timeout");if(o){const e=parseInt(o,10);!isNaN(e)&&e>0&&(t.autoResumeTimeout=e)}const r=e.getAttribute("content-track-metadata")||e.getAttribute("data-content-track-metadata");return null!==r&&(t.trackMetadata="true"===r||""===r),Object.keys(t).length>0?t:void 0}function Ae(e){const t=e.getAttribute("embed-target");if("overlay"!==t&&"mixed"!==t)return;const i=function(e){switch(e){case"page-load":return"pageLoad";case"exit-intent":return"exitIntent";case"delay":return"delay";case"scroll":return"scroll";default:return}}(e.getAttribute("event-trigger")),n=parseInt(e.getAttribute("max-views")||""),s=parseInt(e.getAttribute("time-period")||""),o=Number.isFinite(n)&&n>0||Number.isFinite(s)&&s>0;return Object.assign(Object.assign(Object.assign({mode:t,eventTrigger:i},"overlay"===t&&"delay"===i?{delay:{enabled:!0,delayMs:Le(e)}}:{}),"overlay"===t&&"scroll"===i?{scroll:{enabled:!0,threshold:.1,distance:De(e),direction:"down"}}:{}),{overlay:{position:e.getAttribute("overlay-position")||void 0,keepDimensions:"false"!==e.getAttribute("keep-dimensions"),zIndex:Me(e),fullWidth:"true"===e.getAttribute("overlay-full-width")||void 0,overlayWidth:e.getAttribute("overlay-width")||void 0,overlayHeight:e.getAttribute("overlay-height")||void 0,overlayResize:be(e.getAttribute("overlay-resize-mode")),backdrop:ge(e),background:me(e,ge(e)),closeButton:!0},recurrence:o?{enabled:!0,maxViews:Number.isFinite(n)&&n>0?n:Number.MAX_SAFE_INTEGER,timePeriodHours:Number.isFinite(s)&&s>0?s:24}:void 0})}function Me(e){const t=parseInt(e.getAttribute("overlay-z-index")||"");if(Number.isFinite(t)&&!(t<=0))return Math.min(t,ne)}function Le(e){const t=parseInt(e.getAttribute("trigger-delay")||"");return!Number.isFinite(t)||t<0?3e3:Math.min(t,864e5)}function De(e){const t=parseInt(e.getAttribute("trigger-scroll-distance")||"");return Number.isFinite(t)&&t>0?t:100}function Oe(e){const t=e.getAttribute("device-mobile-enabled")||e.getAttribute("data-device-mobile-enabled"),i=e.getAttribute("device-desktop-enabled")||e.getAttribute("data-device-desktop-enabled");if(t||i)return{mobileEnabled:"false"!==t,desktopEnabled:"false"!==i}}const We="DOMAIN_NOT_ALLOWED";function Re(){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 Pe(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 ze(e){return i(this,void 0,void 0,(function*(){try{const t=yield fetch(e,{method:"GET",mode:"cors"});if(!t.ok){const e=yield function(e){return i(this,void 0,void 0,(function*(){if(403!==e.status)return null;try{const t=yield e.json();if(!t||"object"!=typeof t||t.code!==We)return null;const i=t.details&&"object"==typeof t.details?t.details:null,n="string"==typeof(null==i?void 0:i.reason)?i.reason.slice(0,80):void 0;return{code:We,reason:n}}catch(e){return null}}))}(t);return e?{kind:"refused",refusal:e}:{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 t.json());return n?{kind:"payload",payload:n}:{kind:"unavailable"}}catch(e){return{kind:"unavailable"}}}))}function _e(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:{status:"found",payload:e.payload}}function Fe(e){const t=`/embed/compositions/${e}`,i=[];for(const e of Re())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 n=Q().replace(/\/+$/,"");i.push(`${n}${t}`);const s=String(T.PROD_API_URL).replace(/\/+$/,"");return s&&i.push(`${s}${t}`),[...new Set(i)]}function $e(e){return i(this,void 0,void 0,(function*(){const t=Re();for(const i of t){const t=yield ze(`${i}/embed/compositions/${e}`);if("unavailable"!==t.kind)return _e(t)}if("undefined"!=typeof window){const t=window.location.hostname;if("localhost"===t||"127.0.0.1"===t){const t=yield ze(`http://localhost:3000/embed/compositions/${e}`);if("unavailable"!==t.kind)return _e(t)}}const i=yield function(e){const t=Pe(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(Pe(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(e);if(i){for(const t of Fe(e)){const e=yield ze(t);if("refused"===e.kind)return _e(e);if("payload"===e.kind){const t=e.payload;return{status:"found",payload:Object.assign(Object.assign({},t),{embedUrl:t.embedUrl||i})}}}return{status:"found",payload:{embedUrl:i,compositionId:e}}}for(const t of Fe(e)){const e=yield ze(t);if("unavailable"!==e.kind)return _e(e)}return{status:"not-found"}}))}const Ne=new Set;function Ue(e,t){var i;if(Ne.has(e))return;Ne.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function He(e,t,i,n,s){const o=document.createElement("iframe");return o.src=e,o.width=t,o.height=i,o.setAttribute("frameborder","0"),o.setAttribute("allowfullscreen",""),o.style.border="0",o.style.display="block",o.style.maxWidth="100%",n&&o.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,s=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!i&&!n&&!s)return;const o=()=>{const t=e.contentWindow;if(!t)return;const o={type:"widgetic:update"};i&&(o.design=i),n&&(o.content=n),s&&(o.contentItems=s),t.postMessage(o,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&o()})),e.addEventListener("load",(()=>{o(),window.setTimeout(o,80),window.setTimeout(o,400)}))}(o,s),o}class je{constructor(){this.deviceInfo=null}static getInstance(){return je.instance||(je.instance=new je),je.instance}getDeviceInfo(){return this.deviceInfo||(this.deviceInfo=this.detectDevice()),this.deviceInfo}getDeviceType(){return this.getDeviceInfo().type}isMobile(){return this.getDeviceInfo().isMobile}isTablet(){return this.getDeviceInfo().isTablet}isDesktop(){return this.getDeviceInfo().isDesktop}hasTouch(){return this.getDeviceInfo().hasTouch}detectDevice(){const e=navigator.userAgent||"",t=navigator.platform||"",i=navigator.vendor||"",n=navigator.maxTouchPoints||0,s=navigator.hardwareConcurrency||1,o=navigator.deviceMemory,r=this.detectTouchCapability(),a=this.determineDeviceType(e,t,r,n),d={type:a,isMobile:"mobile"===a,isTablet:"tablet"===a,isDesktop:"desktop"===a||"tablet"===a,hasTouch:r,userAgent:e,platform:t,vendor:i,maxTouchPoints:n,hardwareConcurrency:s,deviceMemory:o};return O.debug("Device detected",d),d}detectTouchCapability(){if("ontouchstart"in window)return!0;if(navigator.maxTouchPoints&&navigator.maxTouchPoints>0)return!0;if("onpointerdown"in window)return!0;try{if(void 0!==window.DocumentTouch&&document instanceof window.DocumentTouch)return!0}catch(e){}return!1}determineDeviceType(e,t,i,n){const s=e.toLowerCase(),o=t.toLowerCase();return[/android.*mobile/,/iphone/,/ipod/,/blackberry/,/bb10/,/windows phone/,/iemobile/,/mobile/,/phone/].some((e=>e.test(s)))?"mobile":[/ipad/,/android(?!.*mobile)/,/kindle/,/silk/,/playbook/,/tablet/].some((e=>e.test(s)))?"tablet":[/windows nt/,/macintosh/,/mac os x/,/linux/,/x11/,/cros/].some((e=>e.test(s)))?"desktop":/^(iphone|ipod|android)/.test(o)?"mobile":/^(ipad)/.test(o)?"tablet":/^(win|mac|linux)/.test(o)?"desktop":i?n>=5?"tablet":n<=2?"mobile":"tablet":"desktop"}checkDeviceRestrictions(e=!0,t=!0){const i=this.getDeviceInfo();return i.isMobile&&!e?(O.debug("Widget restricted on mobile device"),!1):!(i.isDesktop&&!t)||(O.debug("Widget restricted on desktop/tablet device"),!1)}getDeviceCapabilities(){const e={userAgent:navigator.userAgent,platform:navigator.platform,vendor:navigator.vendor,language:navigator.language,languages:navigator.languages,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,maxTouchPoints:navigator.maxTouchPoints,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,connection:navigator.connection,standalone:navigator.standalone,webdriver:navigator.webdriver};return e.screen={width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,colorDepth:screen.colorDepth,pixelDepth:screen.pixelDepth,orientation:screen.orientation},e.touch={hasTouch:this.hasTouch(),hasTouchEvents:"ontouchstart"in window,hasPointerEvents:"onpointerdown"in window,hasGestureEvents:"ongesturestart"in window},window.matchMedia&&(e.mediaQueries={hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":"coarse",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":"coarse"}),e}reset(){this.deviceInfo=null}}function Be(){return je.getInstance()}function Ve(e=!0,t=!0){return Be().checkDeviceRestrictions(e,t)}const Ke="data-widgetic-overlay",qe="data-device-restricted",Ge=new WeakMap,Ye=new WeakMap,Qe=new Map;function Je(e,t,i){if(Ge.has(e))return;const n=e.getAttribute("composition-id")||"widget",s=function(e,t){const i=Ye.get(e);if(i)return i;const n=(Qe.get(t)||0)+1;Qe.set(t,n);const s=1===n?t:`${t}-${n}`;return Ye.set(e,s),s}(e,n);let o=()=>{};if(i){const e=e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===s&&(o(),i())};document.addEventListener("widgetic:overlay-shown",e),o=()=>document.removeEventListener("widgetic:overlay-shown",e)}Promise.resolve().then((function(){return Ei})).then((({TriggerManager:i})=>{if(Ge.has(e))return void o();const n=new i({widgetId:s,element:e,config:t,displayWhenShown:"block"});Ge.set(e,n),e.hasAttribute(Ke)&&e.setAttribute(Ke,"armed"),O.debug("[published-host-display] Trigger manager armed",{widgetId:s,mode:t.mode,eventTrigger:t.eventTrigger})})).catch((e=>{o(),O.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:s,error:e})}))}const Xe="data-widgetic-refused";function Ze(e,t,i,n){!function(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(Ke)||(e.style.display="block")}(e),e.appendChild(He(t,n||e.getAttribute("width")||"400",e.getAttribute("height")||"300",e.getAttribute("composition-id")||void 0,i))}function et(e){if(e.getAttribute("data-widgetic-mounted")||e.getAttribute("data-widgetic-mounting")||e.getAttribute(qe)||e.getAttribute(Xe))return!0;const t=e.getAttribute("src");if(t)return Ze(e,t),!0;const i=e.getAttribute("composition-id");if(!i)return!1;const n=function(e){var t,i,n,s,o;let r;try{r=se(e)}catch(e){return O.warn("[published-host-display] Could not read the embed's display settings",{error:e}),{suppressed:!1}}return Ve(null===(i=null===(t=r.device)||void 0===t?void 0:t.mobileEnabled)||void 0===i||i,null===(s=null===(n=r.device)||void 0===n?void 0:n.desktopEnabled)||void 0===s||s)?("overlay"===(null===(o=r.triggers)||void 0===o?void 0:o.mode)&&(e.style.display="none",e.setAttribute(Ke,"pending")),{suppressed:!1,triggers:r.triggers}):(e.style.display="none",e.setAttribute(qe,"true"),O.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:r.compositionId,device:r.device}),{suppressed:!0})}(e);return n.suppressed||(e.setAttribute("data-widgetic-mounting","1"),$e(i).then((t=>{var s;if(e.getAttribute("data-widgetic-mounted"))return;if("refused"===t.status)return e.removeAttribute("data-widgetic-mounting"),e.setAttribute(Xe,t.refusal.code),void Ue(i,t.refusal);const o="found"===t.status?t.payload:null;if(!(null==o?void 0:o.embedUrl))return void e.removeAttribute("data-widgetic-mounting");const{triggers:r}=n;if("overlay"!==(null==r?void 0:r.mode))Ze(e,o.embedUrl,o),r&&Je(e,r);else{const t=(null===(s=r.overlay)||void 0===s?void 0:s.fullWidth)?"100%":void 0;Je(e,r,(()=>Ze(e,o.embedUrl,o,t)))}}))),!0}function tt(e=document){const t=e.querySelectorAll("widgetic");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&et(e)&&(i+=1);return i}function it(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:nt(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:st(),popupBlocking:ot()}}function nt(){if("undefined"==typeof performance||!performance.getEntriesByType)return!1;try{const e=performance.getEntriesByType("navigation");if(e.length>0){const t=e[0];return"h3"===t.nextHopProtocol||"h3-29"===t.nextHopProtocol}return!1}catch(e){return!1}}function st(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function ot(){if("undefined"==typeof window||!window.open)return!1;try{const e=window.open("","widgetic-popup-test","width=1,height=1");return!e||(e.close(),!1)}catch(e){return!0}}function rt(e,t){switch(e){case"custom-element":case"auto":default:return t.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function at(){if("undefined"==typeof localStorage)return!1;try{const e="widgetic-test";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}const dt={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class ct{constructor(e={}){this.compositionCache=new Map,this.widgetCache=new Map,this.pendingCompositionRequests=new Map,this.pendingWidgetRequests=new Map,this.compositionResolvers=new Map,this.widgetResolvers=new Map,this.compositionBatchQueue=[],this.widgetBatchQueue=[],this.compositionBatchTimer=null,this.widgetBatchTimer=null,this.lastBatchError=null,this.config=Object.assign(Object.assign({},dt),e)}getCompositions(e){return i(this,void 0,void 0,(function*(){"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-start");try{const t=[],i=[];for(const n of e){const e=this.getCachedComposition(n);if(e){t.push(e);continue}const s=this.pendingCompositionRequests.get(n);if(s)try{const e=yield s;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchCompositions(i);t.push(...e)}return Object.defineProperty(t,"compositions",{get(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(t,"success",{value:!this.lastBatchError,enumerable:!1,configurable:!0}),Object.defineProperty(t,"error",{value:this.lastBatchError||void 0,enumerable:!1,configurable:!0}),t}finally{"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-end")}}))}getWidgets(e){return i(this,void 0,void 0,(function*(){const t=[],i=[];for(const n of e){const e=this.getCachedWidget(n);if(e){t.push(e);continue}const s=this.pendingWidgetRequests.get(n);if(s)try{const e=yield s;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchWidgets(i);t.push(...e)}return t}))}getComposition(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCompositions([e]);if(0===t.length)throw new Error(`Composition not found: ${e}`);return t[0]}))}getWidget(e){return i(this,void 0,void 0,(function*(){const t=yield this.getWidgets([e]);if(0===t.length)throw new Error(`Widget not found: ${e}`);return t[0]}))}batchCompositions(e){return i(this,void 0,void 0,(function*(){var t;const i=[];for(const t of e)if(this.pendingCompositionRequests.has(t))i.push(this.pendingCompositionRequests.get(t));else{const e=new Promise(((e,i)=>{this.compositionBatchQueue.push(t),this.scheduleCompositionBatch(),this.compositionResolvers.set(t,{resolve:e,reject:i})}));this.pendingCompositionRequests.set(t,e),i.push(e)}const n=yield Promise.allSettled(i),s=n.find((e=>"rejected"===e.status));return this.lastBatchError=s?(null===(t=s.reason)||void 0===t?void 0:t.message)||String(s.reason):null,n.filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}batchWidgets(e){return i(this,void 0,void 0,(function*(){const t=[];for(const i of e)if(this.pendingWidgetRequests.has(i))t.push(this.pendingWidgetRequests.get(i));else{const e=new Promise(((e,t)=>{this.widgetBatchQueue.push(i),this.scheduleWidgetBatch(),this.widgetResolvers.set(i,{resolve:e,reject:t})}));this.pendingWidgetRequests.set(i,e),t.push(e)}return(yield Promise.allSettled(t)).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}scheduleCompositionBatch(){this.compositionBatchTimer||(this.compositionBatchTimer=window.setTimeout((()=>{this.executeCompositionBatch()}),this.config.debounceDelay))}scheduleWidgetBatch(){this.widgetBatchTimer||(this.widgetBatchTimer=window.setTimeout((()=>{this.executeWidgetBatch()}),this.config.debounceDelay))}executeCompositionBatch(){return i(this,void 0,void 0,(function*(){const e=[...this.compositionBatchQueue];if(this.compositionBatchQueue=[],this.compositionBatchTimer=null,0!==e.length)try{const t=yield this.fetchCompositionsBatch(e);for(const e of t.compositions){this.cacheComposition(e);const t=this.compositionResolvers.get(e.id);t&&(t.resolve(e),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.compositionResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}for(const t of e){const e=this.compositionResolvers.get(t);e&&(e.reject(new Error(`Composition not found in batch response: ${t}`)),this.compositionResolvers.delete(t)),this.pendingCompositionRequests.delete(t)}}catch(t){for(const i of e){const e=this.compositionResolvers.get(i);e&&(e.reject(t),this.compositionResolvers.delete(i)),this.pendingCompositionRequests.delete(i)}}}))}executeWidgetBatch(){return i(this,void 0,void 0,(function*(){const e=[...this.widgetBatchQueue];if(this.widgetBatchQueue=[],this.widgetBatchTimer=null,0!==e.length)try{const t=yield this.fetchWidgetsBatch(e);for(const e of t.widgets){this.cacheWidget(e);const t=this.widgetResolvers.get(e.id);t&&(t.resolve(e),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.widgetResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}for(const t of e){const e=this.widgetResolvers.get(t);e&&(e.reject(new Error(`Widget not found in batch response: ${t}`)),this.widgetResolvers.delete(t)),this.pendingWidgetRequests.delete(t)}}catch(t){for(const i of e){const e=this.widgetResolvers.get(i);e&&(e.reject(t),this.widgetResolvers.delete(i)),this.pendingWidgetRequests.delete(i)}}}))}fetchCompositionsBatch(e){return i(this,arguments,void 0,(function*(e,n=1){var s,o,r;try{const n=yield G(),o=new t.Configuration({basePath:X(),apiKey:()=>i(this,void 0,void 0,(function*(){return n})),headers:{"X-SDK-Version":`embed-sdk/${$}`}}),r=new t.CompositionsApi(o),a=yield r.getCompositionsBatch({getCompositionsBatchRequest:{compositionIds:e}}),d=a.compositions||[];return{compositions:d.map((e=>{if(!e||"object"!=typeof e)return e;const{internalConfig:t,adminNotes:i}=e;return function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["internalConfig","adminNotes"])})),errors:null===(s=a.errors)||void 0===s?void 0:s.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(n<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,n-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchCompositionsBatch(e,n+1)}const i=null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.status,s=null===(r=null==t?void 0:t.response)||void 0===r?void 0:r.statusText;if("number"==typeof i){let e=`HTTP ${i}: ${s||"Request failed"}`;switch(i){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these compositions";break;case 404:e="Composition not found: One or more compositions do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}fetchWidgetsBatch(e){return i(this,arguments,void 0,(function*(e,n=1){var s,o,r;try{const n=yield G(),o=new t.Configuration({basePath:X(),apiKey:()=>i(this,void 0,void 0,(function*(){return n})),headers:{"X-SDK-Version":`embed-sdk/${$}`}}),r=new t.WidgetsApi(o),a=yield r.getWidgetsBatch({getWidgetsBatchRequest:{widgetIds:e}});return{widgets:a.widgets||[],errors:null===(s=a.errors)||void 0===s?void 0:s.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(t){if(n<this.config.retryAttempts){const t=this.config.retryBaseDelay*Math.pow(2,n-1);return yield new Promise((e=>setTimeout(e,t))),this.fetchWidgetsBatch(e,n+1)}const i=null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.status,s=null===(r=null==t?void 0:t.response)||void 0===r?void 0:r.statusText;if("number"==typeof i){let e=`HTTP ${i}: ${s||"Request failed"}`;switch(i){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these widgets";break;case 404:e="Widget not found: One or more widgets do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw t}}))}getCachedComposition(e){const t=this.compositionCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.compositionCache.delete(e),null):t.data}getCachedWidget(e){const t=this.widgetCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.widgetCache.delete(e),null):t.data}cacheComposition(e){this.compositionCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}cacheWidget(e){this.widgetCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}clearCache(){this.compositionCache.clear(),this.widgetCache.clear()}getCacheStats(){return{compositions:{size:this.compositionCache.size,entries:Array.from(this.compositionCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},widgets:{size:this.widgetCache.size,entries:Array.from(this.widgetCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},pending:{compositions:this.pendingCompositionRequests.size,widgets:this.pendingWidgetRequests.size},queues:{compositions:this.compositionBatchQueue.length,widgets:this.widgetBatchQueue.length}}}}let lt=null;function ut(){return lt||(lt=new ct),lt}const ht={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:J()};class gt{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},ht),e)}loadModule(e){return i(this,arguments,void 0,(function*(e,t={}){const i=this.getModuleKey(e.id,t.version||e.version),n=this.loadingPromises.get(i);if(n&&!t.force)return n;if(!t.force){const e=this.getCachedModule(i);if(e)return{module:e.module,url:e.url,loadTime:0,cached:!0}}const s=this.doLoadModule(e,t);this.loadingPromises.set(i,s);try{const e=yield s;return this.loadingPromises.delete(i),e}catch(e){throw this.loadingPromises.delete(i),e}}))}loadModules(e){return i(this,arguments,void 0,(function*(e,t={}){const i=new Map,n=new Map;for(const t of e)if(n.set(t.id,t),t.dependencies){this.dependencyGraph.set(t.id,new Set(t.dependencies));for(const e of t.dependencies)i.set(e,t)}const s=this.resolveDependencyOrder(e),o=[];for(const e of s)try{const i=yield this.loadModule(e,t);o.push(i)}catch(e){}return o}))}getLatestVersion(e){return i(this,void 0,void 0,(function*(){try{const t=`${this.config.cdnBaseUrl}/${e}/latest`,i=yield this.fetchWithHttp3(t,{timeout:5e3});if(i.ok){return(yield i.json()).version}}catch(e){}return null}))}preloadModules(e){return i(this,void 0,void 0,(function*(){const t=e.map((e=>this.loadModule(e,{timeout:3e4}).catch((e=>{}))));yield Promise.allSettled(t)}))}invalidateModule(e,t){if(t){const i=this.getModuleKey(e,t);this.moduleCache.delete(i)}else{Array.from(this.moduleCache.keys()).filter((t=>t.startsWith(`${e}@`))).forEach((e=>this.moduleCache.delete(e)))}}clearCache(){this.moduleCache.clear(),this.loadingPromises.clear()}getCacheStats(){return{size:this.moduleCache.size,entries:Array.from(this.moduleCache.entries()).map((([e,t])=>({key:e,version:t.version,age:Date.now()-t.timestamp,ttl:t.ttl,url:t.url}))),loading:this.loadingPromises.size,http3Supported:this.http3Supported}}doLoadModule(e,t){return i(this,void 0,void 0,(function*(){const i=Date.now(),n=t.version||e.version,s=this.resolveModuleUrl(e,n);try{e.dependencies&&e.dependencies.length>0&&(yield this.loadDependencies(e.dependencies));const o=yield this.loadModuleFromUrl(s,{timeout:t.timeout||this.config.loadTimeout,retries:t.retries||this.config.maxRetries});if(!this.validateModule(o))throw new Error(`Invalid module structure for ${e.id}`);const r=this.getModuleKey(e.id,n);return this.cacheModule(r,{module:o,url:s,timestamp:Date.now(),version:n,ttl:this.config.cacheTTL}),{module:o,url:s,loadTime:Date.now()-i,cached:!1}}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load module ${e.id}@${n}: ${i}`)}}))}loadModuleFromUrl(e,t){return i(this,void 0,void 0,(function*(){let i=null;for(let n=1;n<=t.retries;n++)try{if(e.endsWith(".mjs")||e.includes("type=module")){const i=yield this.loadEsModule(e,t.timeout);return this.extractWidgetFromEsModule(i)}const i=yield this.fetchModuleText(e,t.timeout);return this.evaluateUmdModule(i,e)}catch(e){if(i=e instanceof Error?e:new Error(String(e)),n<t.retries){const e=this.config.retryDelay*Math.pow(2,n-1);yield new Promise((t=>setTimeout(t,e)))}}throw i||new Error("Module loading failed")}))}loadEsModule(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{const s=setTimeout((()=>{n(new Error(`Module load timeout: ${e}`))}),t);import(e).then((e=>{clearTimeout(s),i(e)})).catch((e=>{clearTimeout(s),n(e)}))}))}))}fetchModuleText(e,t){return i(this,void 0,void 0,(function*(){const i=yield this.fetchWithHttp3(e,{timeout:t});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return yield i.text()}))}fetchWithHttp3(e,t){return i(this,void 0,void 0,(function*(){null===this.http3Supported&&(this.http3Supported=yield this.detectHttp3Support());const i={signal:AbortSignal.timeout(t.timeout)};return fetch(e,i)}))}detectHttp3Support(){return i(this,void 0,void 0,(function*(){var e;try{if("connection"in navigator&&"effectiveType"in navigator.connection){const e=navigator.connection;return"4g"===e.effectiveType||"5g"===e.effectiveType}const t=`${this.config.cdnBaseUrl}/test-http3`,i=yield fetch(t,{method:"HEAD",signal:AbortSignal.timeout(2e3)}).catch((()=>null));return(null===(e=null==i?void 0:i.headers.get("alt-svc"))||void 0===e?void 0:e.includes("h3"))||!1}catch(e){return!1}}))}extractWidgetFromEsModule(e){const t=e.default||e.Widget||e.widget||e;if(!t)throw new Error("No widget found in module exports");return{id:t.id||"unknown",version:t.version||"1.0.0",component:t.component||t,metadata:t.metadata,dependencies:t.dependencies}}evaluateUmdModule(e,t){const i={window:"undefined"!=typeof window?window:{},document:"undefined"!=typeof document?document:{},console:console,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval},n=new Function("window","document","console","setTimeout","clearTimeout","setInterval","clearInterval",`\n let module = { exports: {} };\n let exports = module.exports;\n \n ${e}\n \n return module.exports.default || module.exports;\n `)(i.window,i.document,i.console,i.setTimeout,i.clearTimeout,i.setInterval,i.clearInterval);if(!n)throw new Error(`Module evaluation failed: ${t}`);return{id:n.id||"unknown",version:n.version||"1.0.0",component:n.component||n,metadata:n.metadata,dependencies:n.dependencies}}loadDependencies(e){return i(this,void 0,void 0,(function*(){const t=e.map((e=>i(this,void 0,void 0,(function*(){try{if("undefined"!=typeof window&&window[e])return}catch(e){}}))));yield Promise.allSettled(t)}))}resolveDependencyOrder(e){const t=new Set,i=new Set,n=[],s=new Map(e.map((e=>[e.id,e]))),o=e=>{if(i.has(e.id))throw new Error(`Circular dependency detected: ${e.id}`);if(!t.has(e.id)){if(i.add(e.id),e.dependencies)for(const t of e.dependencies){const e=s.get(t);e&&o(e)}i.delete(e.id),t.add(e.id),n.push(e)}};for(const i of e)t.has(i.id)||o(i);return n}resolveModuleUrl(e,t){return e.moduleUrl?e.moduleUrl.replace("{{version}}",t):`${this.config.cdnBaseUrl}/${e.id}/${t}/widget.mjs`}validateModule(e){return!!(e&&e.id&&e.version&&e.component)}getModuleKey(e,t){return`${e}@${t}`}getCachedModule(e){const t=this.moduleCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.moduleCache.delete(e),null):t}cacheModule(e,t){this.moduleCache.set(e,t)}}let pt=null;function mt(){return pt||(pt=new gt),pt}const vt="undefined"!=typeof HTMLElement?HTMLElement:class{};class ft extends vt{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(),O.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return i(this,void 0,void 0,(function*(){if(!this.isWidgetConnected){this.isWidgetConnected=!0,O.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 Ue(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(He(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){O.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(O.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(O.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){O.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(e){return i(this,void 0,void 0,(function*(){const t=ut();this.compositionData=yield t.getComposition(e),this.widgetData=yield t.getWidget(this.compositionData.widgetId),O.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:e,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return i(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=mt();this.loadedModule=yield e.loadModule(this.widgetData),O.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return i(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,O.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw O.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(e,t){return i(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.React||!window.ReactDOM)throw new Error("React not available globally");{const i=window.React,n=window.ReactDOM,s=this.getWidgetProps(),o=i.createElement(t,s);n.render(o,e)}}))}initializeVueComponent(e,t){return i(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.Vue)throw new Error("Vue not available globally");{const i=window.Vue,n=this.getWidgetProps();new i({el:e,render:e=>e(t,{props:n})})}}))}initializeSvelteOrVanillaComponent(e,t){return i(this,void 0,void 0,(function*(){var i;const n=this.getWidgetProps();if(t.$$prop_def||(null===(i=t.prototype)||void 0===i?void 0:i.$$prop_def))this.svelteComponent=new t({target:e,props:n});else if(t.prototype&&t.prototype.constructor===t){const i=new t(e,n);"function"==typeof i.render&&(yield i.render())}else if("function"==typeof t)yield t(e,n);else{if(!t||"function"!=typeof t.init)throw new Error("Unknown component type");yield t.init(e,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",s=this.getAttribute("resize")||"responsive";switch(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof n?`${n}px`:n,s){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})),O.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})),O.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})),O.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return i(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){O.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(),O.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function yt(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",ft),O.info("WidgeticWidget custom element registered")))}class bt{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 bt.instance||(bt.instance=new bt),bt.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),s=e.offsetHeight,o=this.getStoredHeight(t);o&&o!==s&&this.setElementHeight(e,o,n.animate,n.animationDuration),this.setupContentMonitoring(e,t,n,s)}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 s=this.animationIds.get(e);s&&(cancelAnimationFrame(s),this.animationIds.delete(e));const o=document.querySelector(`iframe[data-widgetic-id="${e}"], iframe[data-composition-id="${e}"]`);o&&o._autoscaleMessageCleanup&&(o._autoscaleMessageCleanup(),delete o._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 s=864e5;return Date.now()-n.lastUpdated>s?(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),s=n?JSON.parse(n):{};s[e]={compositionId:e,height:t,originalHeight:i,lastUpdated:Date.now()},localStorage.setItem(this.storageKey,JSON.stringify(s))}catch(e){}}setupContentMonitoring(e,t,i,n){const s=this.findContentElement(e);if(!s)return void e.tagName.toLowerCase();const o=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;o(e)}}));e.observe(s),this.observers.set(t,e)}const r=new MutationObserver((()=>{const e=s.scrollHeight;o(e)}));r.observe(s,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,r);const a=s.scrollHeight;o(a)}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,s;if(i.source===e.contentWindow&&("widgetic:autoscale"===(null===(n=i.data)||void 0===n?void 0:n.type)||"autoscale"===(null===(s=i.data)||void 0===s?void 0:s.type))){const{height:n,contentHeight:s}=i.data.payload||i.data;if("number"==typeof n&&n>0){const i=this.getConfigForWidget(t),o=Math.max(i.minHeight||50,Math.min(i.maxHeight||2e3,n));this.setElementHeight(e,o,i.animate,i.animationDuration),this.storeHeight(t,o,e.offsetHeight),e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:e.offsetHeight,newHeight:o,contentHeight:s||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 s=e.offsetHeight;return o=>{const r=this.timeouts.get(t);r&&clearTimeout(r);const a=setTimeout((()=>{const r=Math.max(i.minHeight,Math.min(i.maxHeight,o));Math.abs(r-s)>=i.threshold&&(this.setElementHeight(e,r,i.animate,i.animationDuration),this.storeHeight(t,r,n),s=r,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:s,newHeight:r,contentHeight:o}}))),this.timeouts.delete(t)}),i.debounceDelay);this.timeouts.set(t,a)}}setElementHeight(e,t,i=!0,n=300){if(!i)return void(e.style.height=`${t}px`);const s=e.offsetHeight,o=t-s;if(Math.abs(o)<1)return;const r=this.animationIds.get(e.id||e.tagName);r&&cancelAnimationFrame(r);const a=performance.now(),d=s,c=i=>{const s=i-a,r=Math.min(s/n,1),l=1-Math.pow(1-r,3),u=d+o*l;if(e.style.height=`${u}px`,r<1){const t=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},l=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,l)}clearStoredHeights(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStoredHeights(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return{}}}destroy(){this.observers.forEach((e=>e.disconnect())),this.observers.clear(),this.mutationObservers.forEach((e=>e.disconnect())),this.mutationObservers.clear(),this.timeouts.forEach((e=>clearTimeout(e))),this.timeouts.clear(),this.animationIds.forEach((e=>cancelAnimationFrame(e))),this.animationIds.clear()}}class wt{static getInstance(){return wt.instance||(wt.instance=new wt),wt.instance}constructor(){this.playingWidgets=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_media_state",this.globalVolumeKey="widgetic_global_volume",this.storageVersion="2.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=18e5,this.globalVolumeEnabled=!0,this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()},this.loadPersistedState(),this.loadGlobalVolumeState(),this.setupVisibilityHandler(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumeWidgets()}),1e3)}registerWidget(e,t={}){const i=Object.assign({autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0},t);this.widgetConfigs.set(e,i);const n=this.playingWidgets.get(e);n&&i.persistState?(i.globalVolume&&this.globalVolumeEnabled&&(n.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume),setTimeout((()=>{this.sendRestoreStateCommand(e,n)}),100)):i.globalVolume&&this.globalVolumeEnabled&&setTimeout((()=>{this.sendVolumeCommand(e,this.globalVolumeState.muted?0:this.globalVolumeState.volume)}),100)}unregisterWidget(e){this.handleMediaEvent({type:"stop",compositionId:e,config:this.widgetConfigs.get(e)||{}}),this.playingWidgets.delete(e),this.widgetConfigs.delete(e),this.eventListeners.delete(e)}handleMediaEvent(e){const{type:t,compositionId:i,config:n,data:s}=e;switch(t){case"play":this.handlePlayEvent(i,n,s);break;case"pause":this.handlePauseEvent(i,s);break;case"stop":case"ended":this.handleStopEvent(i);break;case"seeking":this.handleSeekingEvent(i,null==s?void 0:s.position);break;case"volumechange":this.handleVolumeEvent(i,null==s?void 0:s.volume);break;case"trackchange":this.handleTrackChangeEvent(i,s);break;case"playlistchange":this.handlePlaylistChangeEvent(i,s)}this.emitToListeners(i,e),n.persistState&&this.persistState(),this.dispatchGlobalEvent(e)}handlePlayEvent(e,t,i={}){const n=i.mediaType||t.mediaType||"both",s=t.priority||5,o={compositionId:e,mediaType:n,state:"playing",priority:s,startedAt:Date.now(),duration:i.duration,position:i.position||0,title:i.title,volume:i.volume,playlist:i.playlist,autoResume:t.autoResume,lastInteraction:Date.now()};!1!==t.autoPause&&this.pauseConflictingWidgets(e,n,s,t.allowSimultaneous||[]),this.playingWidgets.set(e,o)}handlePauseEvent(e,t={}){const i=this.playingWidgets.get(e);i&&(i.state="paused",i.position=t.position||i.position,i.volume=t.volume||i.volume,i.lastInteraction=Date.now())}handleStopEvent(e){const t=this.playingWidgets.get(e);t&&(t.state="stopped",t.position=0,t.lastInteraction=Date.now())}handleSeekingEvent(e,t){const i=this.playingWidgets.get(e);i&&void 0!==t&&(i.position=t,i.lastInteraction=Date.now())}handleVolumeEvent(e,t){const i=this.playingWidgets.get(e),n=this.widgetConfigs.get(e);i&&void 0!==t&&(i.lastInteraction=Date.now(),(null==n?void 0:n.globalVolume)&&this.globalVolumeEnabled?(this.globalVolumeState={volume:t>0?t:this.globalVolumeState.volume,muted:0===t,lastUpdated:Date.now(),lastChangedBy:e},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(e),i.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):i.volume=t)}handleTrackChangeEvent(e,t={}){const i=this.playingWidgets.get(e);i&&t.playlist&&(i.playlist=Object.assign(Object.assign({},i.playlist),t.playlist),i.position=0,i.title=t.playlist.trackTitle||i.title,i.lastInteraction=Date.now())}handlePlaylistChangeEvent(e,t={}){const i=this.playingWidgets.get(e);i&&t.playlist&&(i.playlist=Object.assign(Object.assign({},i.playlist),t.playlist),i.lastInteraction=Date.now())}pauseConflictingWidgets(e,t,i,n){const s=[];for(const[o,r]of this.playingWidgets){if(o===e||"playing"!==r.state)continue;this.isSimultaneousAllowed(r.mediaType,t,n)||(i>r.priority||i===r.priority&&Date.now()>r.startedAt)&&s.push(o)}for(const e of s)this.sendPauseCommand(e);s.length}isSimultaneousAllowed(e,t,i){return"both"!==e&&"both"!==t&&(e!==t&&(i.includes(e)&&i.includes(t)))}sendPauseCommand(e){var t;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const n=j.CLIENT_URL||"*";null===(t=i.contentWindow)||void 0===t||t.postMessage({type:"widgetic:media:command",command:"pause",compositionId:e},n)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"pause",compositionId:e}}));const n=this.playingWidgets.get(e);n&&(n.state="paused")}}getPlayingWidgets(){return Array.from(this.playingWidgets.values()).filter((e=>"playing"===e.state))}getAllMediaWidgets(){return Array.from(this.playingWidgets.values())}pauseAll(){const e=this.getPlayingWidgets();for(const t of e)this.sendPauseCommand(t.compositionId)}resumeLastPlayed(){const e=Array.from(this.playingWidgets.values()).filter((e=>"paused"===e.state)).sort(((e,t)=>t.startedAt-e.startedAt));if(e.length>0){const t=e[0];this.sendResumeCommand(t.compositionId)}}sendResumeCommand(e){var t;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const n=j.CLIENT_URL||"*";null===(t=i.contentWindow)||void 0===t||t.postMessage({type:"widgetic:media:command",command:"play",compositionId:e},n)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"play",compositionId:e}}))}}addEventListener(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),()=>{const i=this.eventListeners.get(e);if(i){const e=i.indexOf(t);e>-1&&i.splice(e,1)}}}emitToListeners(e,t){const i=this.eventListeners.get(e);if(i)for(const e of i)try{e(t)}catch(e){}}dispatchGlobalEvent(e){document.dispatchEvent(new CustomEvent(`widgetic:media:${e.type}`,{detail:{compositionId:e.compositionId,config:e.config,data:e.data},bubbles:!0}))}loadPersistedState(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);if(t.version!==this.storageVersion)return void this.clearPersistedState();const i=864e5;if(t.timestamp&&Date.now()-t.timestamp>i)return void this.clearPersistedState();for(const[e,i]of Object.entries(t.playingWidgets||{})){const t=i;t.compositionId&&t.mediaType&&t.state&&this.playingWidgets.set(e,t)}}}catch(e){this.clearPersistedState()}}persistState(){try{const e={version:this.storageVersion,playingWidgets:Object.fromEntries(this.playingWidgets),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){}}setupVisibilityHandler(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden&&this.pauseAll()}))}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{this.persistState()}))}clearPersistedState(e=!1){try{localStorage.removeItem(this.storageKey),e&&(localStorage.removeItem(this.globalVolumeKey),this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()})}catch(e){}}getStats(){const e=this.getPlayingWidgets(),t=Array.from(this.playingWidgets.values()).filter((e=>"paused"===e.state)),i=Array.from(this.playingWidgets.values()).filter((e=>e.playlist)),n=Array.from(this.widgetConfigs.values()).filter((e=>e.globalVolume)).length;return{totalWidgets:this.widgetConfigs.size,playingWidgets:e.length,pausedWidgets:t.length,registeredWidgets:this.playingWidgets.size,widgetsWithPlaylists:i.length,globalVolumeWidgets:n,autoResumeEnabled:this.autoResumeEnabled,globalVolumeEnabled:this.globalVolumeEnabled,globalVolume:{volume:this.globalVolumeState.volume,muted:this.globalVolumeState.muted,lastUpdated:this.globalVolumeState.lastUpdated,lastChangedBy:this.globalVolumeState.lastChangedBy},storageVersion:this.storageVersion,currentlyPlaying:e.map((e=>({compositionId:e.compositionId,mediaType:e.mediaType,priority:e.priority,duration:e.startedAt?Date.now()-e.startedAt:0,position:e.position,volume:e.volume,playlist:e.playlist?{currentTrack:e.playlist.currentTrack,totalTracks:e.playlist.totalTracks,trackTitle:e.playlist.trackTitle}:void 0}))),allWidgets:Array.from(this.playingWidgets.values()).map((e=>{var t;return{compositionId:e.compositionId,state:e.state,mediaType:e.mediaType,priority:e.priority,position:e.position,volume:e.volume,lastInteraction:e.lastInteraction,playlist:e.playlist,autoResume:e.autoResume,globalVolume:(null===(t=this.widgetConfigs.get(e.compositionId))||void 0===t?void 0:t.globalVolume)||!1}}))}}destroy(){this.pauseAll(),this.playingWidgets.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.persistState(),this.persistGlobalVolumeState()}autoResumeWidgets(e={}){if(!this.autoResumeEnabled)return;const{autoResumePlayback:t=!0,maxStateAge:i=this.defaultAutoResumeTimeout,respectTimeouts:n=!0}=e,s=Date.now(),o=[];for(const[e,r]of this.playingWidgets){const a=this.widgetConfigs.get(e);(null==a?void 0:a.autoResume)&&a.persistState&&r.lastInteraction&&(!n||s-r.lastInteraction<=(a.autoResumeTimeout||i))&&("playing"===r.state||t&&"paused"===r.state)&&o.push(r)}o.length>0&&(o.sort(((e,t)=>e.priority!==t.priority?t.priority-e.priority:(t.lastInteraction||0)-(e.lastInteraction||0))),t&&"playing"===o[0].state&&this.resumeWidget(o[0].compositionId))}resumeWidget(e){const t=this.playingWidgets.get(e),i=this.widgetConfigs.get(e);return!(!t||!i)&&(this.sendRestoreStateCommand(e,t),"playing"===t.state&&setTimeout((()=>{this.sendPlayCommand(e,t.position)}),100),!0)}sendRestoreStateCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const s={type:"widgetic:media:command",command:"restore",compositionId:e,state:{position:t.position||0,volume:t.volume||1,title:t.title,playlist:t.playlist,duration:t.duration}};if("iframe"===n.tagName.toLowerCase()){const e=j.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(s,e)}n.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:s}))}}sendPlayCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const s={type:"widgetic:media:command",command:"play",compositionId:e,position:t};if("iframe"===n.tagName.toLowerCase()){const e=j.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(s,e)}n.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:s}))}}getPersistedState(e){return this.playingWidgets.get(e)||null}updateWidgetState(e,t){const i=this.playingWidgets.get(e);if(i){const n=Object.assign(Object.assign(Object.assign({},i),t),{lastInteraction:Date.now()});this.playingWidgets.set(e,n);const s=this.widgetConfigs.get(e);(null==s?void 0:s.persistState)&&this.persistState()}}setAutoResumeEnabled(e){this.autoResumeEnabled=e}triggerAutoResume(e={}){this.autoResumeWidgets(e)}loadGlobalVolumeState(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.globalVolumeKey);if(e){const t=JSON.parse(e);"number"==typeof t.volume&&"boolean"==typeof t.muted&&(this.globalVolumeState={volume:Math.max(0,Math.min(1,t.volume)),muted:t.muted,lastUpdated:t.lastUpdated||Date.now(),lastChangedBy:t.lastChangedBy})}}catch(e){}}persistGlobalVolumeState(){try{localStorage.setItem(this.globalVolumeKey,JSON.stringify(this.globalVolumeState))}catch(e){}}syncGlobalVolumeToWidgets(e){const t=this.globalVolumeState.muted?0:this.globalVolumeState.volume;for(const[i,n]of this.widgetConfigs)if(i!==e&&n.globalVolume){this.sendVolumeCommand(i,t);const e=this.playingWidgets.get(i);e&&(e.volume=t)}}sendVolumeCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const s={type:"widgetic:media:command",command:"setVolume",compositionId:e,volume:Math.max(0,Math.min(1,t))};if("iframe"===n.tagName.toLowerCase()){const e=j.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(s,e)}n.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:s}))}}getGlobalVolumeState(){return Object.assign({},this.globalVolumeState)}setGlobalVolume(e,t){const i=Math.max(0,Math.min(1,e));this.globalVolumeState={volume:i,muted:0===i,lastUpdated:Date.now(),lastChangedBy:t||"api"},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets()}toggleGlobalMute(e){return this.globalVolumeState=Object.assign(Object.assign({},this.globalVolumeState),{muted:!this.globalVolumeState.muted,lastUpdated:Date.now(),lastChangedBy:e||"api"}),this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(),this.globalVolumeState.muted}setGlobalVolumeEnabled(e){const t=this.globalVolumeEnabled;this.globalVolumeEnabled=e,e&&!t&&this.syncGlobalVolumeToWidgets()}isGlobalVolumeEnabled(){return this.globalVolumeEnabled}}let It=null;function Et(){return It||(It=wt.getInstance()),It}class St{static getInstance(){return St.instance||(St.instance=new St),St.instance}constructor(){this.contentStates=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_content_positions",this.storageVersion="1.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=864e5,this.debounceTimers=new Map,this.loadPersistedState(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumePositions()}),1e3)}registerWidget(e,t={}){const i=Object.assign({contentType:"custom",persistState:!0,autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,debounceDelay:500,trackMetadata:!1},t);this.widgetConfigs.set(e,i);const n=this.contentStates.get(e);n&&i.persistState&&setTimeout((()=>{this.sendRestorePositionCommand(e,n)}),100)}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e)),this.contentStates.delete(e),this.widgetConfigs.delete(e),this.eventListeners.delete(e)}handleContentPositionEvent(e){const{type:t,compositionId:i,config:n,data:s}=e;switch(t){case"position":case"navigate":this.handlePositionChangeEvent(i,n,s);break;case"complete":this.handleCompleteEvent(i,s);break;case"reset":this.handleResetEvent(i);break;case"metadata":this.handleMetadataEvent(i,s)}this.emitToListeners(i,e),n.persistState&&this.debouncedPersistState(i,n.debounceDelay||500),this.dispatchGlobalEvent(e)}handlePositionChangeEvent(e,t,i={}){const n=this.contentStates.get(e),s={compositionId:e,contentType:t.contentType||"custom",currentIndex:void 0!==i.currentIndex?i.currentIndex:(null==n?void 0:n.currentIndex)||0,totalItems:void 0!==i.totalItems?i.totalItems:(null==n?void 0:n.totalItems)||0,currentItemId:i.currentItemId||(null==n?void 0:n.currentItemId),currentItemTitle:i.currentItemTitle||(null==n?void 0:n.currentItemTitle),lastUpdated:Date.now(),autoResume:t.autoResume,lastInteraction:Date.now(),metadata:t.trackMetadata?Object.assign(Object.assign({},null==n?void 0:n.metadata),i.metadata):void 0};this.contentStates.set(e,s)}handleCompleteEvent(e,t={}){const i=this.contentStates.get(e);i&&(i.lastInteraction=Date.now(),i.metadata&&(i.metadata.completed=!0,i.metadata.completedAt=Date.now(),t.metadata&&Object.assign(i.metadata,t.metadata)))}handleResetEvent(e){const t=this.contentStates.get(e);t&&(t.currentIndex=0,t.currentItemId=void 0,t.currentItemTitle=void 0,t.lastInteraction=Date.now(),t.metadata&&(t.metadata.completed=!1,delete t.metadata.completedAt))}handleMetadataEvent(e,t={}){const i=this.contentStates.get(e);i&&t.metadata&&(i.metadata||(i.metadata={}),Object.assign(i.metadata,t.metadata),i.lastInteraction=Date.now())}loadPersistedState(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);if(t.version!==this.storageVersion)return void this.clearPersistedState();const i=6048e5;if(t.timestamp&&Date.now()-t.timestamp>i)return void this.clearPersistedState();for(const[e,i]of Object.entries(t.contentStates||{})){const t=i;t.compositionId&&t.contentType&&void 0!==t.currentIndex&&this.contentStates.set(e,t)}}}catch(e){this.clearPersistedState()}}debouncedPersistState(e,t){const i=this.debounceTimers.get(e);i&&clearTimeout(i);const n=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(e)}),t);this.debounceTimers.set(e,n)}persistState(){try{const e={version:this.storageVersion,contentStates:Object.fromEntries(this.contentStates),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){}}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.persistState()}))}autoResumePositions(e={}){if(!this.autoResumeEnabled)return;const{autoResumePosition:t=!0,maxStateAge:i=this.defaultAutoResumeTimeout,respectTimeouts:n=!0}=e,s=Date.now(),o=[];for(const[e,r]of this.contentStates){const a=this.widgetConfigs.get(e);(null==a?void 0:a.autoResume)&&a.persistState&&r.lastInteraction&&(!n||s-r.lastInteraction<=(a.autoResumeTimeout||i))&&t&&o.push(r)}o.length>0&&o.forEach((e=>{this.resumeWidgetPosition(e.compositionId)}))}resumeWidgetPosition(e){const t=this.contentStates.get(e),i=this.widgetConfigs.get(e);return!(!t||!i)&&(this.sendRestorePositionCommand(e,t),!0)}sendRestorePositionCommand(e,t){var i;const n=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(n){const s={type:"widgetic:content:command",command:"restorePosition",compositionId:e,state:{currentIndex:t.currentIndex,totalItems:t.totalItems,currentItemId:t.currentItemId,currentItemTitle:t.currentItemTitle,metadata:t.metadata}};if("iframe"===n.tagName.toLowerCase()){const e=j.CLIENT_URL||"*";null===(i=n.contentWindow)||void 0===i||i.postMessage(s,e)}n.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:s}))}}getAllContentWidgets(){return Array.from(this.contentStates.values())}getPersistedPosition(e){return this.contentStates.get(e)||null}updateWidgetPosition(e,t){const i=this.contentStates.get(e);if(i){const n=Object.assign(Object.assign(Object.assign({},i),t),{lastInteraction:Date.now()});this.contentStates.set(e,n);const s=this.widgetConfigs.get(e);(null==s?void 0:s.persistState)&&this.debouncedPersistState(e,s.debounceDelay||500)}}clearPersistedState(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStats(){const e=Array.from(this.contentStates.values()),t=e.reduce(((e,t)=>(e[t.contentType]=(e[t.contentType]||0)+1,e)),{});return{totalWidgets:this.widgetConfigs.size,trackedWidgets:this.contentStates.size,autoResumeEnabled:this.autoResumeEnabled,storageVersion:this.storageVersion,contentTypes:t,allWidgets:e.map((e=>({compositionId:e.compositionId,contentType:e.contentType,currentIndex:e.currentIndex,totalItems:e.totalItems,progress:e.totalItems>0?Math.round(e.currentIndex/(e.totalItems-1)*100):0,lastInteraction:e.lastInteraction,autoResume:e.autoResume,metadata:e.metadata})))}}addEventListener(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),()=>{const i=this.eventListeners.get(e);if(i){const e=i.indexOf(t);e>-1&&i.splice(e,1)}}}emitToListeners(e,t){const i=this.eventListeners.get(e);if(i)for(const e of i)try{e(t)}catch(e){}}dispatchGlobalEvent(e){document.dispatchEvent(new CustomEvent(`widgetic:content:${e.type}`,{detail:{compositionId:e.compositionId,config:e.config,data:e.data},bubbles:!0}))}setAutoResumeEnabled(e){this.autoResumeEnabled=e}triggerAutoResume(e={}){this.autoResumePositions(e)}destroy(){for(const e of this.debounceTimers.values())clearTimeout(e);this.contentStates.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.debounceTimers.clear(),this.persistState()}}let Tt=null;function kt(){return Tt||(Tt=St.getInstance()),Tt}class Ct{constructor(){this.autoScaleManager=bt.getInstance(),yt()}render(e){return i(this,void 0,void 0,(function*(){const{compositionId:t,width:i="100%",height:n="400",resize:s="responsive",autoscale:o=!0,adaptive:r=768,media:a,content:d}=e,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",t),c.setAttribute("width",String(i)),c.setAttribute("height",String(n)),c.setAttribute("resize",s),"boolean"==typeof o?c.setAttribute("autoscale",o?"true":"false"):o&&"object"==typeof o?(c.setAttribute("autoscale","true"),void 0!==o.minHeight&&c.setAttribute("autoscale-min-height",String(o.minHeight)),void 0!==o.maxHeight&&c.setAttribute("autoscale-max-height",String(o.maxHeight)),void 0!==o.debounceDelay&&c.setAttribute("autoscale-debounce",String(o.debounceDelay)),void 0!==o.threshold&&c.setAttribute("autoscale-threshold",String(o.threshold)),void 0!==o.animate&&c.setAttribute("autoscale-animate",String(o.animate)),void 0!==o.animationDuration&&c.setAttribute("autoscale-animation-duration",String(o.animationDuration))):c.setAttribute("autoscale","false"),c.setAttribute("adaptive",String(r)),a&&Object.keys(a).length>0){Et().registerWidget(t,a),this.setupCustomElementMediaListener(c,t)}if(d&&Object.keys(d).length>0){kt().registerWidget(t,d),this.setupCustomElementContentListener(c,t)}return{id:`custom-${t}-${Date.now()}`,element:c,compositionData:{id:t,name:`Composition ${t}`,widgetId:`widget-${t}`,config:{}},widgetData:{id:`widget-${t}`,name:`Widget ${t}`,type:"custom-element",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"custom-element",cleanup:()=>{c._mediaCommandCleanup&&c._mediaCommandCleanup(),c._mediaObserverCleanup&&c._mediaObserverCleanup(),c._contentPositionCleanup&&c._contentPositionCleanup()}}}))}initializeWidget(e,t,n){return i(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(e,t,n){return i(this,void 0,void 0,(function*(){if(t.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const i=window.React,s=window.ReactDOM,o=i.createElement(t,{config:n.config,metadata:n.metadata});s.render(o,e)}else{if(!t._isVue&&!t.__isVue||"undefined"==typeof window||!window.Vue)throw new Error("Framework component detected but framework not available");new(0,window.Vue)({el:e,render:e=>e(t,{props:{config:n.config,metadata:n.metadata}})})}}))}applyElementStyling(e,t,i){const{width:n,height:s,resize:o,autoscale:r,adaptive:a}=i;switch(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof s?`${s}px`:s,e.style.display="block",e.style.overflow="hidden",o){case"fill-width":e.style.width="100%";break;case"responsive":this.makeResponsive(e,a||768)}if(r){("boolean"==typeof r?r:r&&"object"==typeof r&&r.enabled)&&this.enableAutoscale(e,t,r)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const 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=Et(),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 s=(n,s)=>o=>{const r=(e.__widgetConfig||{}).media||{},a="audio"===n.tagName.toLowerCase()?"audio":"video";i.handleMediaEvent({type:s,compositionId:t,config:r,data:{position:n.currentTime,duration:n.duration,volume:n.volume,mediaType:a,title:n.title||n.getAttribute("data-title")||void 0}})},o=()=>{const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");Array.from(t).concat(Array.from(i)).forEach((e=>{e.addEventListener("play",s(e,"play")),e.addEventListener("pause",s(e,"pause")),e.addEventListener("ended",s(e,"ended")),e.addEventListener("seeked",s(e,"seeking")),e.addEventListener("volumechange",s(e,"volumechange"))}))};o();const r=new MutationObserver((()=>{o()}));r.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{r.disconnect()}}setupCustomElementContentListener(e,t){const i=kt(),n=n=>{if(n.detail&&n.detail.type){const s=n.detail.type,o=n.detail.data||n.detail;let r={};try{const t=e.getAttribute("data-content-config");t&&(r=JSON.parse(t))}catch(e){r={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:s,compositionId:t,config:r,data:o})}};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)}}}class xt{constructor(e={}){this.messageHandlers=new Map,this.messageQueue=new Map,this.pendingMessages=new Map,this.heartbeatIntervals=new Map,this.sequenceNumbers=new Map,this.allowedOrigins=new Set,this.customEventSubscriptions=new Map,this.functionCallHandlers=new Map,this.pendingFunctionCalls=new Map,this.widgetControllers=new Map,this.securityOptions=Object.assign({enableSignatureValidation:!1,allowedOrigins:[],messageTimeout:3e4,enableHeartbeat:!1,heartbeatInterval:3e4},e),this.setupAllowedOrigins(this.securityOptions.allowedOrigins),this.setupGlobalMessageListener(),O.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){j.CLIENT_URL&&this.allowedOrigins.add(j.CLIENT_URL),"undefined"!=typeof window&&window.location&&this.allowedOrigins.add(window.location.origin),e&&e.forEach((e=>this.allowedOrigins.add(e)));const t=new Set;this.allowedOrigins.forEach((e=>{try{const i=new URL(e);t.add(i.origin)}catch(i){t.add(e)}})),this.allowedOrigins=t,O.debug("Allowed origins configured",{origins:Array.from(this.allowedOrigins)})}setupGlobalMessageListener(){"undefined"!=typeof window&&window.addEventListener("message",(e=>{this.handleIncomingMessage(e)}))}validateMessage(e){if(!this.allowedOrigins.has(e.origin))return O.warn("Message from unauthorized origin",{origin:e.origin}),null;try{const t="string"==typeof e.data?JSON.parse(e.data):e.data;return this.isValidWidgeticMessage(t)?this.securityOptions.enableSignatureValidation&&!this.validateSignature(t)?(O.warn("Message signature validation failed",{instanceId:t.instanceId}),null):t:(O.warn("Invalid message structure",{message:t}),null)}catch(t){return O.warn("Failed to parse message",{error:t,data:e.data}),null}}isValidWidgeticMessage(e){return e&&"string"==typeof e.type&&"string"==typeof e.instanceId&&"number"==typeof e.timestamp&&"string"==typeof e.version&&void 0!==e.payload}validateSignature(e){return!0}generateSignature(e){const t=JSON.stringify(Object.assign({},e));return btoa(t).substring(0,16)}handleIncomingMessage(e){const t=this.validateMessage(e);if(!t)return;switch(O.debug("Received valid message",{type:t.type,instanceId:t.instanceId}),t.type){case"heartbeat":return void this.handleHeartbeat(t);case"auth":return void this.handleAuthentication(t);case"custom-event":return void this.handleCustomEvent(t);case"function-call":return void this.handleFunctionCall(t);case"function-response":return void this.handleFunctionResponse(t);case"text-field-change":return void this.handleTextFieldChange(t)}const i=this.messageHandlers.get(t.instanceId);if(i)try{i(t)}catch(e){O.error("Message handler error",{error:e,instanceId:t.instanceId})}else O.debug("No handler for message",{instanceId:t.instanceId,type:t.type})}handleHeartbeat(e){O.debug("Heartbeat received",{instanceId:e.instanceId}),this.sendMessage(e.instanceId,{type:"heartbeat",instanceId:e.instanceId,payload:{response:!0},timestamp:Date.now(),version:"1.0"})}handleAuthentication(e){O.debug("Authentication message received",{instanceId:e.instanceId})}handleTextFieldChange(e){const{fieldId:t,text:i,metadata:n}=e.payload;t&&"string"==typeof i?(Promise.resolve().then((function(){return vi})).then((({getSecurityManager:s})=>{const o=s().validateTextFieldUpdate(e.instanceId,t,i,n);if(!o.allowed)return O.warn("Text field change blocked by security",{instanceId:e.instanceId,fieldId:t,reason:o.reason,severity:o.severity}),void document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:t,reason:o.reason,severity:o.severity,originalTextLength:i.length,timestamp:Date.now()},bubbles:!0}));O.debug("Text field change received",{instanceId:e.instanceId,fieldId:t,textLength:i.length,sanitized:!(!o.sanitizedText||o.sanitizedText===i)}),Promise.resolve().then((function(){return Ji})).then((({getTextFieldManager:s})=>{const r=s(),a=o.sanitizedText||i;r.updateTextField(e.instanceId,t,a,{autoPersist:!0,persistState:!0,textType:(null==n?void 0:n.textType)||"custom",debounceDelay:(null==n?void 0:n.debounceDelay)||1e3,maxLength:null==n?void 0:n.maxLength},Object.assign(Object.assign({},n),{securityValidated:!0,sanitized:a!==i}))})).catch((t=>{O.warn("Failed to handle text field change",{error:t,instanceId:e.instanceId})}))})).catch((t=>{O.warn("Failed to validate text field security",{error:t,instanceId:e.instanceId})})),document.dispatchEvent(new CustomEvent("widgetic:text-field-change",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:t,text:i,metadata:n},bubbles:!0}))):O.warn("Invalid text field change message",{instanceId:e.instanceId,payload:e.payload})}handleCustomEvent(e){const{eventName:t,eventData:i,metadata:n}=e.payload,s=this.customEventSubscriptions.get(e.instanceId);if(!s)return;const o=s.get(t);o&&0!==o.size&&(O.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:t,subscriberCount:o.size}),o.forEach((s=>{try{s(i,n)}catch(i){O.error("Custom event callback error",{error:i,eventName:t,instanceId:e.instanceId})}})),document.dispatchEvent(new CustomEvent(`widgetic:custom:${t}`,{detail:{instanceId:e.instanceId,compositionId:e.compositionId,eventName:t,eventData:i,metadata:n},bubbles:!0})))}handleFunctionCall(e){const{functionName:t,args:i,requestId:n}=e.payload,s=this.functionCallHandlers.get(e.instanceId);if(!s)return void this.sendFunctionResponse(e.instanceId,n,!1,void 0,"No function handlers registered");const o=s.get(t);if(o){O.debug("Executing function call",{instanceId:e.instanceId,functionName:t,args:i});try{const t=o(...i);t&&"function"==typeof t.then?t.then((t=>this.sendFunctionResponse(e.instanceId,n,!0,t))).catch((t=>this.sendFunctionResponse(e.instanceId,n,!1,void 0,t.message||"Function execution failed"))):this.sendFunctionResponse(e.instanceId,n,!0,t)}catch(t){this.sendFunctionResponse(e.instanceId,n,!1,void 0,t instanceof Error?t.message:"Function execution failed")}}else this.sendFunctionResponse(e.instanceId,n,!1,void 0,`Function '${t}' not found`)}handleFunctionResponse(e){const{requestId:t,success:i,result:n,error:s}=e.payload,o=this.pendingFunctionCalls.get(t);o?(clearTimeout(o.timeout),this.pendingFunctionCalls.delete(t),i?o.resolve(n):o.reject(new Error(s||"Function call failed"))):O.warn("Received response for unknown function call",{requestId:t})}sendFunctionResponse(e,t,i,n,s){this.sendMessage(e,{type:"function-response",instanceId:e,payload:{requestId:t,success:i,result:n,error:s},timestamp:Date.now(),version:"1.0"})}registerHandler(e,t){this.messageHandlers.set(e,t),O.debug("Message handler registered",{instanceId:e}),this.messageQueue.has(e)||this.messageQueue.set(e,[]),this.sequenceNumbers.set(e,0),this.securityOptions.enableHeartbeat&&this.startHeartbeat(e)}unregisterHandler(e){this.messageHandlers.delete(e),this.messageQueue.delete(e),this.sequenceNumbers.delete(e),this.stopHeartbeat(e),O.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,t){const i=document.querySelector(`[data-widgetic-id="${e}"]`);if(!i||!i.contentWindow)return O.warn("Cannot send message - iframe not found",{instanceId:e}),void this.queueMessage(e,t);const n=this.getNextSequence(e),s=Object.assign(Object.assign({},t),{sequence:n});this.securityOptions.enableSignatureValidation&&(s.signature=this.generateSignature(s));try{i.contentWindow.postMessage(JSON.stringify(s),"*"),O.debug("Message sent",{instanceId:e,type:s.type,sequence:n})}catch(i){O.error("Failed to send message",{error:i,instanceId:e}),this.queueMessage(e,t)}}queueMessage(e,t){const i=this.messageQueue.get(e)||[];i.push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now()}),this.messageQueue.set(e,i),this.scheduleRetry(e)}scheduleRetry(e){if(this.pendingMessages.has(e))return;const t=setTimeout((()=>{this.processMessageQueue(e),this.pendingMessages.delete(e)}),1e3);this.pendingMessages.set(e,t)}processMessageQueue(e){const t=this.messageQueue.get(e);if(!t||0===t.length)return;const i=[];t.forEach((t=>{t.retryCount<t.maxRetries?(t.retryCount++,this.sendMessage(e,t.message),t.retryCount<t.maxRetries&&i.push(t)):O.warn("Message retry limit exceeded",{instanceId:e,message:t.message})})),this.messageQueue.set(e,i)}getNextSequence(e){const t=(this.sequenceNumbers.get(e)||0)+1;return this.sequenceNumbers.set(e,t),t}startHeartbeat(e){if(this.heartbeatIntervals.has(e))return;const t=setInterval((()=>{this.sendMessage(e,{type:"heartbeat",instanceId:e,payload:{ping:Date.now()},timestamp:Date.now(),version:"1.0"})}),this.securityOptions.heartbeatInterval);this.heartbeatIntervals.set(e,t),O.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const t=this.heartbeatIntervals.get(e);t&&(clearInterval(t),this.heartbeatIntervals.delete(e),O.debug("Heartbeat stopped",{instanceId:e}))}cleanup(){this.heartbeatIntervals.forEach((e=>clearInterval(e))),this.heartbeatIntervals.clear(),this.pendingMessages.forEach((e=>clearTimeout(e))),this.pendingMessages.clear(),this.messageHandlers.clear(),this.messageQueue.clear(),this.sequenceNumbers.clear(),O.info("WidgeticMessenger cleanup complete")}createWidgetController(e,t){const n={subscribe:(t,i)=>this.subscribeToCustomEvent(e,t,i),unsubscribe:(t,i)=>{this.unsubscribeFromCustomEvent(e,t,i)},callFunction:(t,...i)=>this.callWidgetFunction(e,t,i),getState:t=>this.callWidgetFunction(e,"getState",t?[t]:[]),setState:(t,i)=>this.callWidgetFunction(e,"setState",[t,i]),updateConfig:t=>this.callWidgetFunction(e,"updateConfig",[t]),refresh:()=>this.callWidgetFunction(e,"refresh",[]),destroy:()=>this.callWidgetFunction(e,"destroy",[]),emit:(t,i,n)=>{this.sendCustomEvent(e,t,i,n)},registerTextField:(t,n)=>i(this,void 0,void 0,(function*(){const{getTextFieldManager:i}=yield Promise.resolve().then((function(){return Ji}));return i().registerTextField(e,t,n)})),updateTextField:(t,n,s)=>i(this,void 0,void 0,(function*(){const{getTextFieldManager:i}=yield Promise.resolve().then((function(){return Ji}));i().updateTextField(e,t,n,{autoPersist:!0,persistState:!0},s)})),getTextField:t=>i(this,void 0,void 0,(function*(){const{getTextFieldManager:i}=yield Promise.resolve().then((function(){return Ji}));return i().getTextField(e,t)})),clearTextField:t=>i(this,void 0,void 0,(function*(){const{getTextFieldManager:i}=yield Promise.resolve().then((function(){return Ji}));i().clearTextField(e,t)})),getTextFields:()=>i(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return Ji}));return t().getWidgetTextFields(e)})),clearAllTextFields:()=>i(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return Ji}));t().clearWidgetTextFields(e)}))};return this.widgetControllers.set(e,n),n}subscribeToCustomEvent(e,t,i){this.customEventSubscriptions.has(e)||this.customEventSubscriptions.set(e,new Map);const n=this.customEventSubscriptions.get(e);n.has(t)||n.set(t,new Set);const s=n.get(t);return s.add(i),O.debug("Subscribed to custom event",{instanceId:e,eventName:t,totalSubscribers:s.size}),()=>{s.delete(i),0===s.size&&n.delete(t),0===n.size&&this.customEventSubscriptions.delete(e)}}unsubscribeFromCustomEvent(e,t,i){const n=this.customEventSubscriptions.get(e);if(!n)return;const s=n.get(t);s&&(i?s.delete(i):s.clear(),0===s.size&&n.delete(t),0===n.size&&this.customEventSubscriptions.delete(e),O.debug("Unsubscribed from custom event",{instanceId:e,eventName:t}))}callWidgetFunction(e,t,i,n=1e4){return new Promise(((s,o)=>{const r=`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,a=setTimeout((()=>{this.pendingFunctionCalls.delete(r),o(new Error(`Function call timeout: ${t}`))}),n);this.pendingFunctionCalls.set(r,{resolve:s,reject:o,timeout:a}),this.sendMessage(e,{type:"function-call",instanceId:e,payload:{functionName:t,args:i,requestId:r},timestamp:Date.now(),version:"1.0"}),O.debug("Sent function call",{instanceId:e,functionName:t,args:i,requestId:r})}))}sendCustomEvent(e,t,i,n){this.sendMessage(e,{type:"custom-event",instanceId:e,payload:{eventName:t,eventData:i,metadata:n},timestamp:Date.now(),version:"1.0"}),O.debug("Sent custom event",{instanceId:e,eventName:t})}registerFunctionHandlers(e,t){this.functionCallHandlers.has(e)||this.functionCallHandlers.set(e,new Map);const i=this.functionCallHandlers.get(e);Object.entries(t).forEach((([e,t])=>{i.set(e,t)})),O.debug("Registered function handlers",{instanceId:e,functions:Object.keys(t)})}unregisterFunctionHandlers(e,t){const i=this.functionCallHandlers.get(e);i&&(t?t.forEach((e=>i.delete(e))):i.clear(),0===i.size&&this.functionCallHandlers.delete(e),O.debug("Unregistered function handlers",{instanceId:e,functions:t||"all"}))}getWidgetController(e){return this.widgetControllers.get(e)||null}removeWidgetController(e){this.customEventSubscriptions.delete(e),this.functionCallHandlers.delete(e);const t=[];this.pendingFunctionCalls.forEach(((i,n)=>{n.startsWith(e)&&(clearTimeout(i.timeout),i.reject(new Error("Widget controller removed")),t.push(n))})),t.forEach((e=>this.pendingFunctionCalls.delete(e))),this.widgetControllers.delete(e),O.debug("Removed widget controller",{instanceId:e})}isActive(){return this.messageHandlers.size>0||this.widgetControllers.size>0}getCustomEventSubscriptions(){let e=0;return this.customEventSubscriptions.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}getFunctionHandlers(){let e=0;return this.functionCallHandlers.forEach((t=>{e+=t.size})),e}getMessagingStats(){return{activeHandlers:this.messageHandlers.size,widgetControllers:this.widgetControllers.size,customEventSubscriptions:this.getCustomEventSubscriptions(),functionHandlers:this.getFunctionHandlers(),pendingFunctionCalls:this.pendingFunctionCalls.size,heartbeatIntervals:this.heartbeatIntervals.size,messageQueues:Array.from(this.messageQueue.entries()).map((([e,t])=>({instanceId:e,queuedMessages:t.length})))}}}let At=null;function Mt(e){return At||(At=new xt(e)),At}class Lt{constructor(e={}){this.options=e,this.resizeObserver=null,this.instances=new Map,this.debounceTimers=new Map,this.options=Object.assign({observeResize:!0,debounceMs:100,enableAdaptive:!0},e),this.options.observeResize&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.handleResize.bind(this)))}registerWidget(e,t,i,n){const s={widgetId:e,element:t,container:i,config:n,originalWidth:n.width,originalHeight:n.height,aspectRatio:n.width/n.height,isObserving:!1};this.instances.set(e,s),this.applyResizeMode(s),this.resizeObserver&&this.options.observeResize&&(this.resizeObserver.observe(i),s.isObserving=!0),O.debug("Widget registered for resize handling",{widgetId:e,resizeMode:n.resize,originalSize:{width:n.width,height:n.height}})}unregisterWidget(e){const t=this.instances.get(e);if(!t)return;this.resizeObserver&&t.isObserving&&this.resizeObserver.unobserve(t.container);const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e)),this.instances.delete(e),O.debug("Widget unregistered from resize handling",{widgetId:e})}static generateIframeCSS(e){const{resize:t,width:i,height:n,autoscale:s}=e;let o="";switch(t){case"fill-width":o=`\n width: 100% !important;\n height: ${n/i*100}vw !important;\n max-height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fill-height":o=`\n height: 100% !important;\n width: ${i/n*100}vh !important;\n max-width: ${i}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed":default:o=`\n width: ${i}px !important;\n height: ${n}px !important;\n flex-shrink: 0;\n object-fit: cover;\n `;break;case"fixed-height":o=`\n width: 100% !important;\n height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed-width":o=`\n width: ${i}px !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"allow-scale-down":o=`\n max-width: ${i}px !important;\n max-height: ${n}px !important;\n width: 100% !important;\n height: auto !important;\n object-fit: contain;\n `;break;case"fill":o=`\n width: 100% !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `}return o.trim()}applyResizeMode(e){const{element:t,container:i,config:n}=e,{resize:s,autoscale:o}=n,r=i.getBoundingClientRect(),a=r.width,d=r.height;let c,l;switch(s){case"fill-width":c=a,l=c/e.aspectRatio,o&&l>d&&(l=d,c=l*e.aspectRatio);break;case"fill-height":l=d,c=l*e.aspectRatio,o&&c>a&&(c=a,l=c/e.aspectRatio);break;case"fixed":default:c=e.originalWidth,l=e.originalHeight;break;case"fixed-height":c=a,l=e.originalHeight;break;case"fixed-width":c=e.originalWidth,l=d;break;case"allow-scale-down":const t=a/e.originalWidth,i=d/e.originalHeight,n=Math.min(1,Math.min(t,i));c=e.originalWidth*n,l=e.originalHeight*n;break;case"fill":c=a,l=d}this.setElementSize(t,c,l,n),this.options.enableAdaptive&&n.adaptive&&this.handleAdaptiveBreakpoint(e,a),O.debug("Resize mode applied",{widgetId:e.widgetId,resizeMode:s,containerSize:{width:a,height:d},newSize:{width:c,height:l}})}setElementSize(e,t,i,n){switch(e.style.width=`${Math.round(t)}px`,e.style.height=`${Math.round(i)}px`,n.resize){case"fill":case"fill-width":case"fill-height":e.style.objectFit=n.autoscale?"contain":"cover";break;default:e.style.objectFit="contain"}e.style.boxSizing="border-box",e.style.display="block"}handleAdaptiveBreakpoint(e,t){if(!e.config.adaptive)return;const i=t<=e.config.adaptive,n=e.element;i?(n.classList.add("widgetic-adaptive-mobile"),n.classList.remove("widgetic-adaptive-desktop"),n.style.maxWidth="100%",n.style.fontSize="14px"):(n.classList.add("widgetic-adaptive-desktop"),n.classList.remove("widgetic-adaptive-mobile"),n.style.fontSize="")}handleResize(e){for(const t of e){const e=t.target;for(const[t,i]of this.instances)if(i.container===e){const e=this.debounceTimers.get(t);e&&clearTimeout(e);const n=window.setTimeout((()=>{this.applyResizeMode(i),this.debounceTimers.delete(t)}),this.options.debounceMs);this.debounceTimers.set(t,n)}}}forceResize(e){const t=this.instances.get(e);t&&this.applyResizeMode(t)}forceResizeAll(){for(const e of this.instances.values())this.applyResizeMode(e)}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.instances.clear()}}let Dt=null;class Ot{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&O.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void O.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const s=t.getBoundingClientRect().width,o=i.initialMode||(s<i.breakpoint?"mobile":"desktop"),r={mode:o,breakpoint:i.breakpoint,width:s,timestamp:Date.now()};this.currentStates.set(e,r),this.callbacks.set(e,n);const a=new ResizeObserver((t=>{this.handleResize(e,t,i)}));a.observe(t),this.observers.set(e,a),n(r),O.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:o,containerWidth:s})}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),O.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 O.warn("Widget not registered for responsive monitoring",{widgetId:e});const s=t<i.breakpoint?"mobile":"desktop";if(s!==i.mode){const o={mode:s,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,o),n(o),O.info("Responsive state changed manually",{widgetId:e,from:i.mode,to:s,width:t,breakpoint:i.breakpoint})}}handleResize(e,t,i){const n=this.debounceTimers.get(e);n&&clearTimeout(n);const s=setTimeout((()=>{this.processResize(e,t,i),this.debounceTimers.delete(e)}),i.debounceDelay||150);this.debounceTimers.set(e,s)}processResize(e,t,i){const n=this.currentStates.get(e),s=this.callbacks.get(e);if(!n||!s)return;const o=t[t.length-1];if(!o)return;const r=o.contentRect.width,a=r<i.breakpoint?"mobile":"desktop";if(a!==n.mode){const t={mode:a,breakpoint:i.breakpoint,width:r,timestamp:Date.now()};this.currentStates.set(e,t),s(t),O.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:a,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),O.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);O.debug("ResponsiveManager cleanup complete")}}let Wt=null;function Rt(){return Wt||(Wt=new Ot),Wt}class Pt{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=bt.getInstance()}renderWidget(e){return i(this,void 0,void 0,(function*(){const{compositionId:t,width:i,height:n,resize:s="fixed",autoscale:o=!1,adaptive:r,responsive:a,container:d,allowFullscreen:c=!0,sandbox:l=this.getDefaultSandboxPermissions(),allowedFeatures:u=this.getDefaultAllowedFeatures(),loading:h="lazy",enableResize:g=!0,compositionData:p,widgetData:m,security:v={},fallback:f={enabled:!0,timeout:1e4,retryCount:3},media:y}=e;if(!i||!n||!d)throw new Error("Missing required parameters: width, height, and container are required");const b=p||{id:t,name:`Composition ${t}`,widgetId:`widget-${t}`,config:{}},w=m||{id:b.widgetId,name:`Widget ${t}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]};try{const p=this.createSecureIframe(t,e);p.src=yield this.buildSecureIframeUrl(t,e),p.title=`Widgetic Widget: ${b.name||t}`,p.loading=h,this.applySandboxSecurity(p,l,u),p.width=i.toString(),p.height=n.toString(),p.frameBorder="0",p.scrolling="no",c&&(p.allowFullscreen=!0,p.setAttribute("allowfullscreen","")),p.title=`Widgetic Widget ${t}`,p.setAttribute("aria-label",`Interactive widget: ${t}`);const m={compositionId:t,renderMode:"iframe",displayMode:"inline",resize:s,width:"number"==typeof i?i:parseInt(i.toString()),height:"number"==typeof n?n:parseInt(n.toString()),autoscale:o,adaptive:r,responsive:a,media:y},I=Lt.generateIframeCSS(m);I&&(p.style.cssText+=I),this.applyIframeStyling(p,t,{width:i,height:n,resize:s,autoscale:o,adaptive:r}),p.style.visibility="hidden",p.style.opacity="0",p.style.transition="opacity 0.3s ease",this.addLoadingIndicator(d,m),this.setupEnhancedIframeMessaging(p,t,v),this.setupLoadingOptimization(p,t,f);const E="lazy"===h,S=new Promise(((e,i)=>{let n=null;E||(n=setTimeout((()=>{i(new Error(`Iframe load timeout for composition: ${t}`))}),f.timeout||1e4)),p.onload=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(d),p.style.visibility="visible",p.style.opacity="1",e()},p.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(d),i(new Error(`Failed to load iframe for composition: ${t}`))}}));if(d.appendChild(p),g&&"undefined"!=typeof ResizeObserver){const e=new Lt({observeResize:!0}),i=`iframe-${t}-${Date.now()}`;p.setAttribute("data-widget-id",i),e.registerWidget(i,p,d,m),p.__resizeHandler=e,p.__widgetId=i}a&&"number"==typeof a&&a>0&&this.setupResponsiveMonitoring(p,d,t,a),this.iframeRegistry.set(t,p),p.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),E||(yield S);const T=`iframe-${t}-${Date.now()}`;if(O.info("Enhanced iframe widget rendered successfully",{compositionId:t,size:{width:i,height:n},resize:s,autoscale:o,responsive:a,sandbox:l.join(" "),features:u.join("; ")}),m.media&&Object.keys(m.media).length>0){Et().registerWidget(t,m.media),this.setupIframeMediaListener(p,t)}if(e.content&&Object.keys(e.content).length>0){kt().registerWidget(t,e.content),this.setupIframeContentListener(p,t)}return{id:T,element:p,compositionData:b,widgetData:w,renderMode:"iframe",cleanup:()=>this.cleanupWidget(p)}}catch(e){throw O.error("Enhanced iframe widget rendering failed",{compositionId:t,error:e}),this.removeLoadingIndicator(d),e}}))}renderWidgets(e){return i(this,void 0,void 0,(function*(){O.debug("Rendering multiple iframe widgets",{count:e.length});const t=e.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(t),n=[];for(let t=0;t<i.length;t++){const s=i[t],o=e[t];if("fulfilled"===s.status)n.push(s.value);else{O.error("Iframe widget rendering failed in batch",{compositionId:o.compositionId,error:s.reason});const e=`error-${o.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(o,s.reason),compositionData:{id:o.compositionId,name:`Composition ${o.compositionId}`,widgetId:`widget-${o.compositionId}`,config:{}},widgetData:{id:`widget-${o.compositionId}`,name:`Widget ${o.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return O.info("Iframe batch rendering complete",{total:e.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||[j.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(e,t){return i(this,void 0,void 0,(function*(){var i;const n=`${j.CLIENT_URL}/embed/${e}`,s=new URLSearchParams;t.width&&s.set("width","number"==typeof t.width?t.width.toString():t.width),t.height&&s.set("height","number"==typeof t.height?t.height.toString():t.height),t.resize&&s.set("resize",t.resize),t.autoscale&&s.set("autoscale","true"),t.adaptive&&s.set("adaptive",t.adaptive.toString()),t.responsive&&"number"==typeof t.responsive&&s.set("responsive",t.responsive.toString()),(null===(i=t.security)||void 0===i?void 0:i.signatureValidation)&&s.set("validateSignature","true"),s.set("sdkVersion","1.0"),s.set("mode","iframe");try{const e=yield G();s.set("apiKey",e)}catch(e){O.warn("Failed to get auth token for iframe",e),j.API_KEY&&s.set("apiKey",j.API_KEY)}const o=`${n}?${s.toString()}`;return O.debug("Built secure iframe URL",{compositionId:e,url:o}),o}))}applyIframeStyling(e,t,i){const{width:n,height:s,resize:o,autoscale:r,adaptive:a}=i;if(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof s?`${s}px`:s,"fill-width"===o)e.style.width="100%",e.style.height="auto",e.style.minHeight="number"==typeof s?`${s}px`:s;r&&this.enableIframeAutoscale(e,t,r),a&&this.makeIframeResponsive(e,a)}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)},O.debug("AutoScale enabled for iframe",{compositionId:t,config:n}))}setupLoadingOptimization(e,t,i){if(!i.enabled)return;const n=i.timeout||1e4,s=i.retryCount||3;let o=0;const r=()=>{o<s?(o++,O.warn(`Iframe loading failed, retrying (${o}/${s})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+o}),1e3*o)):(O.error("Iframe loading failed after retries",{compositionId:t,retryCount:s}),this.handleIframeFallback(e,t))},a=setTimeout((()=>{O.warn("Iframe loading timeout",{compositionId:t,timeout:n}),r()}),n);this.loadingTimeouts.set(t,a),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),O.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{O.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=Mt({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:Q(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),O.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,O.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(O.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:O.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})),O.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})),O.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})),O.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})),O.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})),O.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){Mt().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,s=e.__responsiveId;n&&s&&n.unregisterWidget(s);const o=e.__messenger,r=e.__messagingCompositionId;o&&r&&o.unregisterHandler(r);const a=this.loadingTimeouts.get(r);a&&(clearTimeout(a),this.loadingTimeouts.delete(r)),r&&this.iframeRegistry.delete(r),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),O.debug("Iframe cleanup complete",{compositionId:r})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,i,n){const s=Rt(),o=Mt(),r={breakpoint:n,debounceDelay:150},a=`responsive-${i}`;s.registerWidget(a,t,r,(t=>{O.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),o.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=a,e.__responsiveManager=s,O.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:a})}setupIframeMediaListener(e,t){const i=Et(),n=n=>{var s,o;if(n.source===e.contentWindow&&(null===(o=null===(s=n.data)||void 0===s?void 0:s.type)||void 0===o?void 0:o.startsWith("widgetic:media:"))){const s=n.data.type.replace("widgetic:media:","");if(["play","pause","stop","ended","seeking","volumechange"].includes(s)){const o=e.getAttribute("data-widget-config"),r=o?JSON.parse(o):{};i.handleMediaEvent({type:s,compositionId:t,config:r.media||{},data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=kt(),n=n=>{var s,o;if(n.source===e.contentWindow&&(null===(o=null===(s=n.data)||void 0===s?void 0:s.type)||void 0===o?void 0:o.startsWith("widgetic:content:"))){const s=n.data.type.replace("widgetic:content:","");if(["position","navigate","complete","reset","metadata"].includes(s)){const o=e.getAttribute("data-widgetic-config");let r={};if(o)try{r=JSON.parse(o).content||{}}catch(e){r={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:s,compositionId:t,config:r,data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._contentListenerCleanup=()=>{window.removeEventListener("message",n)}}}class zt{constructor(){this.batchClient=ut(),this.moduleLoader=mt(),this.customElementRenderer=new Ct,this.iframeRenderer=new Pt,this.renderedWidgets=new Map}renderWidget(e){return i(this,void 0,void 0,(function*(){const t=this.generateWidgetId(e.compositionId),i=this.createLoadingElement(e.container);e.container&&i&&e.container.appendChild(i);try{const n=yield this.batchClient.getComposition(e.compositionId),s=yield this.batchClient.getWidget(n.widgetId),o=this.determineRenderMode(e.renderMode,s);let r;if("custom-element"===o)try{r=yield this.moduleLoader.loadModule(s)}catch(o){const r=yield this.renderWithIframe(t,e,n,s);return this.removeLoadingElement(i),r}const a="iframe"===o?yield this.renderWithIframe(t,e,n,s):yield this.renderWithCustomElement(t,e,n,s,r);return this.removeLoadingElement(i),this.renderedWidgets.set(t,a),this.emitWidgetEvent("ready",{widgetId:t,compositionId:e.compositionId,renderMode:a.renderMode,loadTime:(null==r?void 0:r.loadTime)||0,cached:(null==r?void 0:r.cached)||!1}),a}catch(n){if(this.removeLoadingElement(i),this.emitWidgetEvent("error",{widgetId:t,compositionId:e.compositionId,error:n instanceof Error?n.message:String(n),fallback:"iframe"}),e.container){const t=this.createErrorElement(e.compositionId,n);e.container.appendChild(t)}try{const i=yield this.renderFallback(t,e);if(e.container){const t=e.container.querySelector(".widgetic-error");t&&t.remove()}return i}catch(e){throw new Error(`Widget rendering failed: ${n}. Fallback also failed: ${e}`)}}}))}renderWidgets(e){return i(this,void 0,void 0,(function*(){const t=e.map((e=>e.compositionId)),n=yield this.batchClient.getCompositions(t),s=new Map(n.map((e=>[e.id,e]))),o=new Set;for(const t of e)if("iframe"!==t.renderMode){const e=s.get(t.compositionId);e&&e.widgetId&&o.add(e.widgetId)}const r=o.size>0?yield this.batchClient.getWidgets(Array.from(o)):[],a=new Map(r.map((e=>[e.id,e]))),d=r.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));d.length>0&&(yield this.moduleLoader.preloadModules(d));const c=e.map((e=>i(this,void 0,void 0,(function*(){const t=s.get(e.compositionId)||{id:e.compositionId,widgetId:"default",name:"Composition",settings:{},config:{},version:"1.0.0"},i=a.get(t.widgetId)||{id:t.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(e,t,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(e){return i(this,void 0,void 0,(function*(){const t=this.renderedWidgets.get(e);if(!t)return null;t.cleanup(),this.renderedWidgets.delete(e);const i={compositionId:t.compositionData.id,renderMode:t.renderMode,container:t.element.parentElement||void 0};return this.batchClient.clearCache(),this.moduleLoader.invalidateModule(t.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(e,t,n){return i(this,void 0,void 0,(function*(){const i=this.generateWidgetId(e.compositionId);if("custom-element"===this.determineRenderMode(e.renderMode,n))try{const s=yield this.moduleLoader.loadModule(n);return this.renderWithCustomElement(i,e,t,n,s)}catch(e){}return this.renderWithIframe(i,e,t,n)}))}renderWithCustomElement(e,t,n,s,o){return i(this,void 0,void 0,(function*(){const i=yield this.customElementRenderer.render({compositionId:t.compositionId,compositionData:n,widgetData:s,loadedModule:o,width:t.width,height:t.height,resize:t.resize,autoscale:t.autoscale,adaptive:t.adaptive});return t.container&&t.container.appendChild(i.element),{id:e,element:i.element,compositionData:n,widgetData:s,loadedModule:o,renderMode:"custom-element",cleanup:()=>{i.element.remove()}}}))}renderWithIframe(e,t,n,s){return i(this,void 0,void 0,(function*(){return yield this.iframeRenderer.renderWidget({compositionId:t.compositionId,compositionData:n,widgetData:s,width:t.width,height:t.height,resize:t.resize,autoscale:t.autoscale,adaptive:t.adaptive,container:t.container})}))}renderFallback(e,t){return i(this,void 0,void 0,(function*(){const i=document.createElement("div");return i.className="widgetic-fallback",i.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: ${t.compositionId}</small>\n </div>\n `,t.container&&t.container.appendChild(i),{id:e,element:i,compositionData:{id:t.compositionId,name:"Fallback",widgetId:"fallback",config:{}},widgetData:{id:"fallback",name:"Fallback Widget",type:"fallback",version:"1.0.0",moduleUrl:""},renderMode:"iframe",cleanup:()=>{i.remove()}}}))}determineRenderMode(e="auto",t){var i;if("auto"!==e)return e;const n="undefined"!=typeof customElements&&"function"==typeof customElements.define,s=(null==t?void 0:t.moduleUrl)||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.supportsCustomElements);return n&&s?"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",s=this.analyzeError(n,t);return i.innerHTML=`\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">${s.icon}</div>\n <div style="font-weight: 500; margin-bottom: 8px;">${s.title}</div>\n <div style="font-size: 14px; margin-bottom: 12px; color: #666;">\n ${s.description}\n </div>\n <div style="font-size: 12px; margin-bottom: 16px; color: #888;">\n Widget ID: ${e}\n </div>\n ${s.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 _t=null;function Ft(){return _t||(_t=new zt),_t}const $t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"===Object.prototype.toString.call(e);function Nt(e){if(Array.isArray(e))return e.map(Nt);if(!$t(e))return e;const t={};for(const[i,n]of Object.entries(e)){t[i.replace(/[_-](\w)/g,((e,t)=>t?t.toUpperCase():""))]=Array.isArray(n)?n.map(Nt):$t(n)?Nt(n):n}return t}function Ut(e){if(Array.isArray(e))return e.map(Ut);if(!$t(e))return e;const t={};for(const[i,n]of Object.entries(e)){t[i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()]=Array.isArray(n)?n.map(Ut):$t(n)?Ut(n):n}return t}class Ht{constructor(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache=new Map;const e=Y(),i=new t.Configuration({basePath:e.basePath,apiKey:e.apiKey,credentials:"include"});this.authApi=new t.AuthenticationApi(i),this.compositionsApi=new t.CompositionsApi(i)}checkAuthentication(){return i(this,void 0,void 0,(function*(){try{if(this.sessionCache&&Date.now()<this.sessionCacheExpiry)return{isAuthenticated:!0,session:this.sessionCache,user:this.sessionCache.user,canEdit:!0};const e=Nt(yield this.authApi.getSession());return e&&e.accessToken&&e.user?(this.sessionCache=e,this.sessionCacheExpiry=Date.now()+3e5,O.info("User authenticated for editing",{userId:e.user.id,email:e.user.email}),{isAuthenticated:!0,session:e,user:e.user,canEdit:!0}):{isAuthenticated:!1,canEdit:!1}}catch(e){return O.debug("Authentication check failed",{error:e}),e instanceof Response&&e.status,{isAuthenticated:!1,canEdit:!1}}}))}checkCompositionOwnership(e){return i(this,void 0,void 0,(function*(){var t;try{const i=this.ownershipCache.get(e);if(i)return i;const n=yield this.checkAuthentication();if(!n.isAuthenticated||!(null===(t=n.session)||void 0===t?void 0:t.user)){const t={isOwner:!1,canEdit:!1,error:"User not authenticated"};return this.ownershipCache.set(e,t),t}const s=Nt(yield this.compositionsApi.getCompositionById({id:e}));if(!s){const t={isOwner:!1,canEdit:!1,error:"Composition not found"};return this.ownershipCache.set(e,t),t}const o=s.creatorId===n.session.user.id,r={isOwner:o,canEdit:o,composition:s,error:o?void 0:"User does not own this composition"};return this.ownershipCache.set(e,r),setTimeout((()=>{this.ownershipCache.delete(e)}),12e4),O.debug("Composition ownership checked",{compositionId:e,isOwner:o,userId:n.session.user.id,compositionCreatorId:s.creatorId}),r}catch(t){O.warn("Failed to check composition ownership",{compositionId:e,error:t});const i={isOwner:!1,canEdit:!1,error:t instanceof Error?t.message:"Unknown error"};return this.ownershipCache.set(e,i),i}}))}canEditComposition(e){return i(this,void 0,void 0,(function*(){return(yield this.checkCompositionOwnership(e)).canEdit}))}getCurrentUser(){return i(this,void 0,void 0,(function*(){return(yield this.checkAuthentication()).user||null}))}clearCache(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache.clear(),O.debug("Authentication cache cleared")}checkMultipleCompositions(e){return i(this,void 0,void 0,(function*(){const t=new Map;return(yield this.checkAuthentication()).isAuthenticated?(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){const i=yield this.checkCompositionOwnership(e);t.set(e,i)}))))),t):(e.forEach((e=>{t.set(e,{isOwner:!1,canEdit:!1,error:"User not authenticated"})})),t)}))}isEditingEnabled(){return j.ENABLE_EDITING}}let jt=null;function Bt(){return jt||(jt=new Ht),jt}class Vt{constructor(e={}){this.host=null,this.container=null,this.content=null,this.destroyed=!1,this.options=Object.assign({target:"widgetic-portal",className:"",style:"",clickThrough:!1,zIndex:99999999},e),this.createPortal()}createPortal(){this.host=this.findOrCreateHost(),this.container=document.createElement("div"),this.container.className=(this.options.className?this.options.className+" ":"")+"widgetic-portal-contents",this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough?"none":"auto"};\n ${this.options.style}\n `,this.options.clickThrough?this.container.style.pointerEvents="none":this.container.style.pointerEvents="auto",this.host.appendChild(this.container),O.debug("Portal created",{target:this.options.target,host:this.host,container:this.container})}findOrCreateHost(){let e=null;if(this.options.target instanceof HTMLElement)return this.options.target;if("string"==typeof this.options.target){const t=`.${this.options.target}`;e=document.querySelector(t)}return e||(e=document.createElement("div"),e.classList.add("string"==typeof this.options.target?this.options.target:"widgetic-portal"),document.body.appendChild(e),O.debug("Portal host created",{target:this.options.target,host:e})),e}mount(e){this.destroyed?O.warn("Cannot mount content to destroyed portal"):this.container?(this.content&&this.unmount(),e.style.pointerEvents="auto",this.content=e,this.container.appendChild(e),O.debug("Content mounted to portal",{content:e})):O.error("Portal container not available")}unmount(){this.content&&this.container&&this.container.contains(this.content)&&(this.container.removeChild(this.content),this.content=null,O.debug("Content unmounted from portal"))}destroy(){if(!this.destroyed){if(this.unmount(),this.container&&this.host&&this.host.contains(this.container)&&this.host.removeChild(this.container),this.host&&0===this.host.childNodes.length&&this.host.parentNode){const e="string"==typeof this.options.target?this.options.target:"widgetic-portal";this.host.classList.contains(e)&&this.host.parentNode.removeChild(this.host)}this.destroyed=!0,this.host=null,this.container=null,this.content=null,O.debug("Portal destroyed")}}getContainer(){return this.container}isDestroyed(){return this.destroyed}updateOptions(e){this.destroyed?O.warn("Cannot update options on destroyed portal"):(this.options=Object.assign(Object.assign({},this.options),e),this.container&&(void 0!==e.className&&(this.container.className=(e.className?e.className+" ":"")+"widgetic-portal-contents"),void 0!==e.style&&(this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough,"none"};\n ${this.options.style}\n `),void 0!==e.clickThrough&&(this.container.style.pointerEvents=(e.clickThrough,"none"))),O.debug("Portal options updated",{options:this.options}))}}function Kt(e){return new Vt(e)}class qt{constructor(e={}){this.config=e,this.loadPromise=null,this.sdkInstance=null,this.isLoading=!1,this.loadTimeout=3e4,this.config=Object.assign({basePath:e.basePath||this.getUISdkBaseUrl(),version:e.version||"latest",debug:e.debug||!1},e)}getUISdkBaseUrl(){return"development"===j.NODE_ENV?j.CLIENT_URL:`${j.PRODUCTION_URL}/ui-sdk`}loadUISdk(){return i(this,void 0,void 0,(function*(){if(this.sdkInstance)return this.sdkInstance;if(this.loadPromise)return this.loadPromise;this.isLoading=!0,this.loadPromise=this.performLoad();try{return this.sdkInstance=yield this.loadPromise,O.info("UI SDK loaded successfully",{basePath:this.config.basePath,version:this.config.version}),this.sdkInstance}catch(e){throw O.error("Failed to load UI SDK",{error:e,config:this.config}),this.loadPromise=null,e}finally{this.isLoading=!1}}))}performLoad(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const i=setTimeout((()=>{t(new Error("UI SDK load timeout"))}),this.loadTimeout);try{if(window.WidgeticUI)return clearTimeout(i),void e(window.WidgeticUI);const n=document.createElement("script");n.src=`${this.config.basePath}/widgetic-ui.js`,n.async=!0,n.crossOrigin="anonymous",n.onload=()=>{clearTimeout(i),window.WidgeticUI?(O.debug("UI SDK script loaded from external source"),e(window.WidgeticUI)):t(new Error("UI SDK script loaded but WidgeticUI not available"))},n.onerror=()=>{clearTimeout(i),t(new Error("Failed to load UI SDK script"))},document.head.appendChild(n),O.debug("Loading UI SDK",{src:n.src})}catch(e){clearTimeout(i),t(e)}}))}))}isLoaded(){return null!==this.sdkInstance}isLoadingState(){return this.isLoading}getInstance(){return this.sdkInstance}initializeUISdk(e){return i(this,void 0,void 0,(function*(){const t=yield this.loadUISdk();return yield t.init(Object.assign(Object.assign({},this.config),e)),O.info("UI SDK initialized",{config:Object.assign(Object.assign({},this.config),e)}),t}))}cleanup(){return i(this,void 0,void 0,(function*(){if(this.sdkInstance){try{yield this.sdkInstance.destroy()}catch(e){O.warn("Error during UI SDK cleanup",{error:e})}this.sdkInstance=null}this.loadPromise=null,this.isLoading=!1,window.WidgeticUI&&delete window.WidgeticUI,O.debug("UI SDK cleanup complete")}))}preload(){return i(this,void 0,void 0,(function*(){try{yield this.loadUISdk(),O.debug("UI SDK preloaded successfully")}catch(e){O.warn("UI SDK preload failed",{error:e})}}))}}let Gt=null;function Yt(e){return Gt||(Gt=new qt(e)),Gt}class Qt{constructor(e={}){this.options=e,this.sessions=new Map,this.defaultOptions={showEditButton:!0,editButtonText:"✏️ Edit",editButtonPosition:"top-right",enableClickToEdit:!0,autoDetectAuth:!0},this.options=Object.assign(Object.assign({},this.defaultOptions),e)}addOverlay(e,t){return i(this,void 0,void 0,(function*(){try{if(!this.options.autoDetectAuth)return void(yield this.createOverlay(e,t,!0));const i=Bt(),n=yield i.checkCompositionOwnership(t);n.canEdit?(yield this.createOverlay(e,t,!0),O.debug("Editor overlay added for owned composition",{compositionId:t})):O.debug("Editor overlay not added - user cannot edit",{compositionId:t,reason:n.error})}catch(e){O.warn("Failed to add editor overlay",{compositionId:t,error:e})}}))}createOverlay(e,t,n){return i(this,void 0,void 0,(function*(){if(this.sessions.has(t))return;const i=document.createElement("div");if(i.className="widgetic-editor-overlay",i.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 10000;\n pointer-events: none;\n ${this.getOverlayStyles()}\n `,this.options.showEditButton&&n){const e=this.createEditButton(t);i.appendChild(e)}this.options.enableClickToEdit&&n&&this.addClickToEdit(i,t);const s=e.parentElement;if(s){"static"===window.getComputedStyle(s).position&&(s.style.position="relative"),s.appendChild(i)}else e.style.position="relative",e.appendChild(i);const o={compositionId:t,isOpen:!1,overlay:i};this.sessions.set(t,o),O.debug("Editor overlay created",{compositionId:t})}))}createEditButton(e){const t=document.createElement("button");return t.className="widgetic-edit-button",t.textContent=this.options.editButtonText||"✏️ Edit",t.style.cssText=`\n position: absolute;\n ${this.getButtonPositionStyles()}\n background: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n padding: 8px 12px;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n pointer-events: auto;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n transition: all 0.2s ease;\n z-index: 10001;\n ${this.getCustomButtonStyles()}\n `,t.addEventListener("mouseenter",(()=>{t.style.background="#0056b3",t.style.transform="scale(1.05)"})),t.addEventListener("mouseleave",(()=>{t.style.background="#007bff",t.style.transform="scale(1)"})),t.addEventListener("click",(t=>i(this,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),yield this.openEditor(e)})))),t}getButtonPositionStyles(){const e="10px";switch(this.options.editButtonPosition||"top-right"){case"top-left":return`top: ${e}; left: ${e};`;case"top-right":default:return`top: ${e}; right: ${e};`;case"bottom-left":return`bottom: ${e}; left: ${e};`;case"bottom-right":return`bottom: ${e}; right: ${e};`}}getCustomButtonStyles(){return this.options.editButtonStyle?Object.entries(this.options.editButtonStyle).map((([e,t])=>`${this.camelToKebab(e)}: ${t};`)).join(" "):""}getOverlayStyles(){return this.options.overlayStyle?Object.entries(this.options.overlayStyle).map((([e,t])=>`${this.camelToKebab(e)}: ${t};`)).join(" "):""}camelToKebab(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}addClickToEdit(e,t){e.style.cursor="pointer",e.style.pointerEvents="auto",e.addEventListener("click",(n=>i(this,void 0,void 0,(function*(){n.target===e&&(n.preventDefault(),n.stopPropagation(),yield this.openEditor(t))})))),e.addEventListener("mouseenter",(()=>{e.style.backgroundColor="rgba(0, 123, 255, 0.1)",e.style.border="2px dashed #007bff"})),e.addEventListener("mouseleave",(()=>{e.style.backgroundColor="transparent",e.style.border="none"}))}createEditorContainer(){const e=new Vt({target:"widgetic-editor-portal",className:"widgetic-editor-modal",zIndex:1e5,clickThrough:!1});const t=document.createElement("div");t.className="widgetic-editor-modal-backdrop",t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("div");return i.className="widgetic-editor-content",i.style.cssText="\n width: 90vw;\n height: 90vh;\n max-width: 1200px;\n max-height: 800px;\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n ",t.appendChild(i),e.mount(t),{container:t,portal:e}}openEditor(e){return i(this,void 0,void 0,(function*(){try{const t=this.sessions.get(e);if(!t)return void O.warn("No editor session found",{compositionId:e});if(t.isOpen)return void O.debug("Editor already open",{compositionId:e});O.info("Opening composition editor",{compositionId:e});const i=Yt(),n=yield i.initializeUISdk(),{container:s,portal:o}=this.createEditorContainer(),r=yield n.mountCompositionEditor(s.querySelector(".widgetic-editor-content"),e,{onSave:t=>this.handleEditorSave(e,t),onClose:()=>this.closeEditor(e),onPreview:t=>this.handleEditorPreview(e,t)}),a=Mt().createWidgetController(e);if(t.isOpen=!0,t.editorContainer=s,t.editorInstance=r,t.widgetController=a,t.portal=o,t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="none")}O.info("Composition editor opened successfully",{compositionId:e})}catch(t){O.error("Failed to open editor",{compositionId:e,error:t}),this.showError("Failed to open editor. Please try again.",e)}}))}handleEditorSave(e,t){return i(this,void 0,void 0,(function*(){try{O.info("Saving composition changes",{compositionId:e,data:t});const i=this.sessions.get(e);(null==i?void 0:i.widgetController)&&(yield i.widgetController.updateConfig(t),yield i.widgetController.refresh()),yield this.closeEditor(e),O.info("Composition saved successfully",{compositionId:e})}catch(t){O.error("Failed to save composition",{compositionId:e,error:t}),this.showError("Failed to save changes. Please try again.",e)}}))}handleEditorPreview(e,t){return i(this,void 0,void 0,(function*(){try{const i=this.sessions.get(e);(null==i?void 0:i.widgetController)&&(yield i.widgetController.callFunction("preview",t))}catch(t){O.warn("Preview update failed",{compositionId:e,error:t})}}))}closeEditor(e){return i(this,void 0,void 0,(function*(){const t=this.sessions.get(e);if(t&&t.isOpen)try{if(t.editorInstance&&t.editorContainer){const e=Yt().getInstance();e&&(yield e.unmountCompositionEditor(t.editorContainer))}if(t.portal&&t.portal.destroy(),t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="block")}t.isOpen=!1,t.editorContainer=void 0,t.editorInstance=void 0,t.portal=void 0,O.info("Editor closed",{compositionId:e})}catch(t){O.error("Error closing editor",{compositionId:e,error:t})}}))}showError(e,t){const i=document.createElement("div");i.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n background: #dc3545;\n color: white;\n padding: 12px 16px;\n border-radius: 4px;\n z-index: 100001;\n font-size: 14px;\n max-width: 300px;\n ",i.textContent=e,document.body.appendChild(i),setTimeout((()=>{i.parentNode&&i.parentNode.removeChild(i)}),5e3)}removeOverlay(e){const t=this.sessions.get(e);t&&(t.isOpen&&this.closeEditor(e),t.overlay&&t.overlay.parentNode&&t.overlay.parentNode.removeChild(t.overlay),t.portal&&t.portal.destroy(),this.sessions.delete(e),O.debug("Editor overlay removed",{compositionId:e}))}isEditorOpen(e){var t;return(null===(t=this.sessions.get(e))||void 0===t?void 0:t.isOpen)||!1}getActiveSessions(){return Array.from(this.sessions.keys())}cleanup(){for(const e of this.sessions.keys())this.removeOverlay(e);O.debug("Editor overlay cleanup complete")}}let Jt=null;function Xt(e){return Jt||(Jt=new Qt(e)),Jt}class Zt{constructor(e={}){this.options=e,this.instances=new Map,this.widgetElements=new Map,this.widgetConfigs=new Map,this.fullscreenListeners=new Map,this.keyboardListeners=new Map,this.options=Object.assign({enableFullscreen:!0,enableOverlay:!0,enablePopup:!0,defaultOverlayZIndex:5e4,defaultPopupFeatures:"width=800,height=600,scrollbars=yes,resizable=yes"},e),this.setupGlobalKeyHandlers()}initializeWidget(e,t,i){const n={mode:t.displayMode||"inline",isFullscreen:!1,isOverlay:!1,isPopup:!1};return this.instances.set(e,n),this.widgetElements.set(e,i),this.widgetConfigs.set(e,t),this.setupDisplayMode(e,t,i),n}setupDisplayMode(e,t,i){const{displayMode:n}=t;switch(n){case"fullscreen":this.setupFullscreenMode(e,t,i);break;case"overlay":case"modal":this.setupOverlayMode(e,t,i);break;case"popup":this.setupPopupMode(e,t,i)}}setupFullscreenMode(e,t,i){var n;if(!this.options.enableFullscreen||!(null===(n=t.fullscreen)||void 0===n?void 0:n.enabled))return;const s=t.fullscreen.trigger||"click";"manual"!==s&&this.addFullscreenTrigger(e,i,s),t.fullscreen.showControls&&this.addFullscreenControls(e,i)}setupOverlayMode(e,t,i){var n;if(!this.options.enableOverlay||!(null===(n=t.overlay)||void 0===n?void 0:n.enabled))return;const s=t.overlay.trigger||"click";"auto"===s?setTimeout((()=>this.showOverlay(e)),100):"manual"!==s&&this.addOverlayTrigger(e,i,s)}setupPopupMode(e,t,i){var n;if(!this.options.enablePopup||!(null===(n=t.popup)||void 0===n?void 0:n.enabled))return;const s=t.popup.trigger||"click";"manual"!==s&&this.addPopupTrigger(e,i,s)}enterFullscreen(e){return i(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&!t.isFullscreen)try{const i=this.getWidgetElement(e);if(!i)throw new Error(`Widget element not found: ${e}`);const n=Kt({target:"widgetic-fullscreen",zIndex:100001,className:"fullscreen-widget"}),s=document.createElement("div");s.className="widgetic-fullscreen-container",s.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #000;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 100001;\n ",t.originalStyle=i.style.cssText;const o=document.createComment(`widgetic-fullscreen-placeholder-${e}`);i.parentNode&&(i.parentNode.replaceChild(o,i),t.originalPlaceholder=o),i.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100vw;\n max-height: 100vh;\n border: none;\n ",s.appendChild(i);const r=this.createExitButton((()=>this.exitFullscreen(e)));if(s.appendChild(r),n.mount(s),t.isFullscreen=!0,t.overlayPortal=n,t.fullscreenElement=s,this.setupFullscreenKeyHandler(e),document.documentElement.requestFullscreen)try{yield document.documentElement.requestFullscreen()}catch(e){O.warn("Native fullscreen failed, using CSS fullscreen",{error:e})}O.info("Widget entered fullscreen mode",{widgetId:e})}catch(t){throw O.error("Failed to enter fullscreen",{widgetId:e,error:t}),t}}))}exitFullscreen(e){return i(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&t.isFullscreen)try{const i=this.getWidgetElement(e);i&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(i,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(i.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),document.fullscreenElement&&document.exitFullscreen&&(yield document.exitFullscreen()),t.isFullscreen=!1,t.overlayPortal=void 0,t.fullscreenElement=void 0,this.removeFullscreenKeyHandler(e),O.info("Widget exited fullscreen mode",{widgetId:e})}catch(t){throw O.error("Failed to exit fullscreen",{widgetId:e,error:t}),t}}))}showOverlay(e){return i(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&!t.isOverlay)try{const i=this.getWidgetConfig(e),n=null==i?void 0:i.overlay;if(!n)throw new Error(`No overlay configuration for widget: ${e}`);const s=Kt({target:"widgetic-overlay",zIndex:n.zIndex||this.options.defaultOverlayZIndex,className:"overlay-widget"}),o=this.createOverlayContainer(e,n),r=this.getWidgetElement(e);if(r){t.originalStyle=r.style.cssText;const i=document.createComment(`widgetic-overlay-placeholder-${e}`);r.parentNode&&(r.parentNode.replaceChild(i,r),t.originalPlaceholder=i),this.styleOverlayWidget(r,n);o.querySelector(".overlay-content").appendChild(r)}s.mount(o),t.isOverlay=!0,t.overlayPortal=s,this.setupOverlayCloseHandlers(e,o,n),O.info("Widget shown in overlay mode",{widgetId:e})}catch(t){throw O.error("Failed to show overlay",{widgetId:e,error:t}),t}}))}hideOverlay(e){return i(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(t&&t.isOverlay)try{const i=this.getWidgetElement(e);i&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(i,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(i.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),t.isOverlay=!1,t.overlayPortal=void 0,this.removeOverlayKeyHandler(e),O.info("Widget overlay hidden",{widgetId:e})}catch(t){throw O.error("Failed to hide overlay",{widgetId:e,error:t}),t}}))}openPopup(e){return i(this,void 0,void 0,(function*(){const t=this.instances.get(e);if(!t||t.isPopup)return(null==t?void 0:t.popupWindow)||null;try{const i=this.getWidgetConfig(e),n=null==i?void 0:i.popup;if(!n)throw new Error(`No popup configuration for widget: ${e}`);const s=this.buildPopupFeatures(n),o=this.generatePopupUrl(e),r=window.open(o,n.target||`widgetic_${e}`,s);if(!r)throw new Error("Popup blocked by browser");return t.isPopup=!0,t.popupWindow=r,this.monitorPopupClose(e,r),O.info("Widget opened in popup",{widgetId:e}),r}catch(t){throw O.error("Failed to open popup",{widgetId:e,error:t}),t}}))}closePopup(e){const t=this.instances.get(e);if(t&&t.isPopup&&t.popupWindow)try{t.popupWindow.close(),t.isPopup=!1,t.popupWindow=null,O.info("Widget popup closed",{widgetId:e})}catch(t){O.error("Failed to close popup",{widgetId:e,error:t})}}getDisplayState(e){return this.instances.get(e)||null}cleanup(e){const t=this.instances.get(e);t&&(t.isFullscreen&&this.exitFullscreen(e),t.isOverlay&&this.hideOverlay(e),t.isPopup&&this.closePopup(e),this.instances.delete(e),this.removeFullscreenKeyHandler(e),this.removeOverlayKeyHandler(e))}cleanupAll(){for(const e of this.instances.keys())this.cleanup(e)}getWidgetElement(e){return this.widgetElements.has(e)?this.widgetElements.get(e):document.querySelector(`[data-widget-id="${e}"]`)||document.querySelector(`[data-widgetic-id="${e}"]`)||document.querySelector(`[composition-id="${e}"]`)||null}getWidgetConfig(e){return this.widgetConfigs.get(e)||null}addFullscreenTrigger(e,t,i){const n=()=>this.enterFullscreen(e);switch(i){case"click":t.addEventListener("click",n);break;case"double-click":t.addEventListener("dblclick",n);break;case"hover":t.addEventListener("mouseenter",n)}}addOverlayTrigger(e,t,i){const n=()=>this.showOverlay(e);switch(i){case"click":t.addEventListener("click",n);break;case"hover":t.addEventListener("mouseenter",n)}}addPopupTrigger(e,t,i){const n=()=>this.openPopup(e);"click"===i&&t.addEventListener("click",n)}createExitButton(e){const t=document.createElement("button");return t.className="widgetic-exit-fullscreen",t.innerHTML="✕",t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",s=t.height||"100%";i&&(t.overlayWidth||t.overlayHeight)&&(n=t.overlayWidth||n,s=t.overlayHeight||s),e.style.cssText=`\n width: ${n};\n height: ${s};\n border: none;\n display: block;\n `,i&&t.overlayResize&&this.applyOverlayResizeMode(e,t.overlayResize)}applyOverlayResizeMode(e,t){if(e.parentElement)switch(t){case"fill-width":e.style.width="100%",e.style.height="auto",e.style.aspectRatio="auto";break;case"fill-height":e.style.height="100%",e.style.width="auto",e.style.aspectRatio="auto";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="100%";break;case"fixed-width":e.style.height="100%";break;case"allow-scale-down":e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.objectFit="contain";break;case"fill":e.style.width="100%",e.style.height="100%",e.style.objectFit="cover"}}buildPopupFeatures(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.centerScreen&&t.push("location=center"),e.allowResize&&t.push("resizable=yes"),e.showToolbar&&t.push("toolbar=yes"),t.length>0?t.join(","):this.options.defaultPopupFeatures||""}generatePopupUrl(e){return"about:blank"}setupGlobalKeyHandlers(){"undefined"!=typeof document&&document.addEventListener("keydown",(e=>{if("Escape"===e.key)for(const[e,t]of this.instances)t.isFullscreen?this.exitFullscreen(e):t.isOverlay&&this.hideOverlay(e)}))}setupFullscreenKeyHandler(e){const t=t=>{"Escape"===t.key&&this.exitFullscreen(e)};this.keyboardListeners.set(`${e}-fullscreen`,t),document.addEventListener("keydown",t)}removeFullscreenKeyHandler(e){const t=this.keyboardListeners.get(`${e}-fullscreen`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-fullscreen`))}setupOverlayCloseHandlers(e,t,i){if(i.closeOnBackdropClick&&t.addEventListener("click",(i=>{i.target===t&&this.hideOverlay(e)})),i.closeOnEscape){const t=t=>{"Escape"===t.key&&this.hideOverlay(e)};this.keyboardListeners.set(`${e}-overlay`,t),document.addEventListener("keydown",t)}}removeOverlayKeyHandler(e){const t=this.keyboardListeners.get(`${e}-overlay`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-overlay`))}monitorPopupClose(e,t){const i=()=>{if(t.closed){const t=this.instances.get(e);t&&(t.isPopup=!1,t.popupWindow=null)}else setTimeout(i,1e3)};setTimeout(i,1e3)}addFullscreenControls(e,t){const i=document.createElement("div");i.className="widgetic-fullscreen-controls",i.style.cssText="\n position: absolute;\n bottom: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.7);\n border-radius: 4px;\n padding: 5px;\n z-index: 1000;\n ";const n=document.createElement("button");n.innerHTML="⛶",n.style.cssText="\n background: none;\n border: none;\n color: white;\n cursor: pointer;\n font-size: 16px;\n ",n.addEventListener("click",(()=>this.enterFullscreen(e))),i.appendChild(n),t.style.position="relative",t.appendChild(i)}}let ei=null;const ti={mobile:480,tablet:768,desktop:1024},ii={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},ni={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class si{constructor(e={enabled:!0}){var t;this.isEnabled=!1,this.activeOverlay=null,this.exitIntentListener=null,this.scrollListener=null,this.engagementStartTime=null,this.timeoutId=null,this.config=Object.assign(Object.assign({exitIntentEnabled:!0,scrollTriggerEnabled:!0,timeTriggerEnabled:!0,engagementThresholdEnabled:!0,externalTriggerEnabled:!0},e),{enabled:null===(t=e.enabled)||void 0===t||t}),this.config.breakpoints||(this.config.breakpoints={useBreakpoints:!1,mobile:ti.mobile,tablet:ti.tablet,desktop:ti.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),O.debug("OverlayManager initialized",{config:this.config})}initializeEventListeners(){"undefined"!=typeof window&&(this.config.exitIntentEnabled&&this.initializeExitIntent(),this.config.scrollTriggerEnabled&&this.initializeScrollTrigger(),this.config.engagementThresholdEnabled&&this.startEngagementTracking())}initializeExitIntent(){"undefined"!=typeof document&&(this.exitIntentListener=e=>{e.clientY<=0&&e.movementY<0&&this.emitOverlayTrigger("exit-intent",{mousePosition:{x:e.clientX,y:e.clientY},movementY:e.movementY})},document.addEventListener("mouseleave",this.exitIntentListener))}initializeScrollTrigger(){"undefined"!=typeof window&&(this.scrollListener=()=>{const e=window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100;e>=25&&e<30?this.emitOverlayTrigger("scroll-25",{scrollPercentage:e}):e>=50&&e<55?this.emitOverlayTrigger("scroll-50",{scrollPercentage:e}):e>=75&&e<80&&this.emitOverlayTrigger("scroll-75",{scrollPercentage:e})},window.addEventListener("scroll",this.scrollListener,{passive:!0}))}startEngagementTracking(){this.engagementStartTime=Date.now();setInterval((()=>{if(!this.engagementStartTime)return;const e=Date.now()-this.engagementStartTime;e>=3e4?this.emitOverlayTrigger("engagement-30s",{engagementTimeMs:e}):e>=6e4?this.emitOverlayTrigger("engagement-1m",{engagementTimeMs:e}):e>=12e4&&this.emitOverlayTrigger("engagement-2m",{engagementTimeMs:e})}),1e4)}showOverlay(e){if(this.isEnabled){this.activeOverlay&&(O.debug("Overlay already active, closing previous"),this.hideOverlay());try{const t=this.validateOverlayConfig(e),i=this.createOverlayElement(t);document.body.appendChild(i),this.activeOverlay=i,setTimeout((()=>{i.classList.add("widgetic-overlay-visible")}),50),t.autoClose&&t.autoClose>0&&(this.timeoutId=window.setTimeout((()=>{this.hideOverlay()}),t.autoClose)),O.info("Overlay displayed",{displayMode:t.displayMode,animation:t.animation,autoClose:t.autoClose}),this.emitOverlayEvent("overlay-shown",t)}catch(t){O.error("Failed to show overlay",{error:t,config:e})}}else O.warn("Overlay manager is disabled")}validateOverlayConfig(e){const t=Object.assign({},e);return t.displayMode&&Object.values(ii).includes(t.displayMode)||(t.displayMode=ii.MANUAL),t.animation&&ni.SUPPORTED_ANIMATIONS.includes(t.animation)||(t.animation=ni.DEFAULT_ANIMATION,O.debug("Using default animation for overlay",{provided:e.animation,defaultUsed:ni.DEFAULT_ANIMATION})),t.delay||(t.delay=ni.DEFAULT_DELAY_MS),void 0===t.showBackdrop&&(t.showBackdrop=!0),t}hideOverlay(){if(!this.activeOverlay)return;this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.activeOverlay;e.classList.remove("widgetic-overlay-visible"),e.classList.add("widgetic-overlay-hiding"),setTimeout((()=>{e.parentNode&&e.parentNode.removeChild(e)}),300),this.activeOverlay=null,O.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||ni.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close" aria-label="Close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&i.addEventListener("click",(()=>this.hideOverlay())),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const n=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",n))};return document.addEventListener("keydown",n),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||ti.mobile;return`\n /* Mobile responsive styles */\n @media (max-width: ${t}px) {\n .widgetic-overlay-content {\n max-width: 95vw;\n margin: 10px;\n }\n \n .widgetic-overlay-body {\n padding: 15px;\n }\n }\n \n /* Tablet responsive styles */\n @media (min-width: ${t+1}px) and (max-width: ${e.tablet||ti.tablet}px) {\n .widgetic-overlay-content {\n max-width: 90vw;\n margin: 15px;\n }\n \n .widgetic-overlay-body {\n padding: 18px;\n }\n }\n `}addOverlayStyles(){const e="widgetic-overlay-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .widgetic-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n }\n \n .widgetic-overlay-backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n \n .widgetic-overlay-visible {\n opacity: 1;\n }\n \n .widgetic-overlay-hiding {\n opacity: 0;\n }\n \n .widgetic-overlay-content {\n position: relative;\n background: white;\n border-radius: 8px;\n max-width: 90vw;\n max-height: 90vh;\n overflow: auto;\n transition: all 0.3s ease;\n }\n \n .widgetic-overlay-close {\n position: absolute;\n top: 10px;\n right: 15px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n z-index: 1;\n color: #6b7280;\n line-height: 1;\n padding: 4px;\n }\n \n .widgetic-overlay-close:hover {\n color: #374151;\n }\n \n .widgetic-overlay-body {\n padding: 20px;\n }\n \n /* Fade animation (default) */\n .widgetic-overlay-fade .widgetic-overlay-content {\n transform: scale(0.95);\n opacity: 0;\n }\n \n .widgetic-overlay-fade.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Slide animations */\n .widgetic-overlay-slide-up .widgetic-overlay-content {\n transform: translateY(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-up.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-down .widgetic-overlay-content {\n transform: translateY(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-down.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-left .widgetic-overlay-content {\n transform: translateX(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-left.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-right .widgetic-overlay-content {\n transform: translateX(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-right.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n /* Zoom animation */\n .widgetic-overlay-zoom .widgetic-overlay-content {\n transform: scale(0.7);\n opacity: 0;\n }\n \n .widgetic-overlay-zoom.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Bounce animation */\n .widgetic-overlay-bounce .widgetic-overlay-content {\n transform: scale(0.3);\n opacity: 0;\n transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n \n .widgetic-overlay-bounce.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Mobile responsive */\n ${this.generateResponsiveCSS()}\n `,document.head.appendChild(t)}emitOverlayTrigger(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-trigger",{detail:{triggerType:e,data:t,timestamp:(new Date).toISOString()}}))}emitOverlayEvent(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-event",{detail:{eventType:e,data:t,timestamp:(new Date).toISOString()}}))}triggerOverlay(e,t={}){const i=Object.assign({displayMode:e,animation:ni.DEFAULT_ANIMATION,delay:ni.DEFAULT_DELAY_MS,content:"Default overlay content"},t);i.delay&&i.delay>0?setTimeout((()=>{this.showOverlay(i)}),i.delay):this.showOverlay(i)}isOverlayActive(){return null!==this.activeOverlay}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),this.isEnabled=this.config.enabled,O.debug("OverlayManager config updated",{config:this.config})}destroy(){this.activeOverlay&&this.hideOverlay(),this.exitIntentListener&&document.removeEventListener("mouseleave",this.exitIntentListener),this.scrollListener&&window.removeEventListener("scroll",this.scrollListener),this.timeoutId&&clearTimeout(this.timeoutId),O.debug("OverlayManager destroyed")}}let oi=null;class ri{constructor(e={}){this.metrics=[],this.webVitals={},this.widgetMetrics=new Map,this.isTracking=!1,this.config=Object.assign({enableTracking:te.ENABLE_PERFORMANCE_TRACKING,enableWebVitals:!0,enableWidgetMetrics:!0,enableResourceTracking:!0,enableBudgetMonitoring:!0,sampleRate:te.PERFORMANCE_SAMPLE_RATE,maxMetricsBuffer:te.MAX_METRICS_BUFFER,axiomApiEndpoint:te.AXIOM_API_ENDPOINT,statsigApiEndpoint:te.STATSIG_API_ENDPOINT,budgets:[{metric:"lcp",threshold:te.LCP_THRESHOLD,warningThreshold:te.LCP_WARNING_THRESHOLD,enabled:!0},{metric:"fid",threshold:te.FID_THRESHOLD,warningThreshold:te.FID_WARNING_THRESHOLD,enabled:!0},{metric:"cls",threshold:te.CLS_THRESHOLD,warningThreshold:te.CLS_WARNING_THRESHOLD,enabled:!0},{metric:"widget-load",threshold:te.WIDGET_LOAD_THRESHOLD,warningThreshold:te.WIDGET_LOAD_WARNING_THRESHOLD,enabled:!0},{metric:"bundle-size",threshold:te.BUNDLE_SIZE_THRESHOLD,warningThreshold:te.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 n=i.loadEndTime-i.loadStartTime;this.recordMetric("widget-load",n,{compositionId:e,success:t,isLazyLoaded:i.isLazyLoaded,bundleSize:i.bundleSize}),this.checkBudget("widget-load",n),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 n={name:e,value:t,timestamp:performance.now(),metadata:i};this.metrics.push(n),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,n){const s={type:"performance-budget-alert",metric:e,value:t,threshold:i,level:n,timestamp:Date.now(),url:window.location.href};window.dispatchEvent(new CustomEvent("widgetic:performance-alert",{detail:s})),this.recordMetric("budget-alert",t,s)}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 i(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(e){return i(this,void 0,void 0,(function*(){yield fetch(this.config.reportingEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}))}reportToAxiom(e){return i(this,void 0,void 0,(function*(){const t=this.config.axiomApiEndpoint||"https://api.axiom.co/v1";yield fetch(`${t}/datasets/${this.config.axiomDataset}/ingest`,{method:"POST",headers:{Authorization:`Bearer ${this.config.axiomApiKey}`,"Content-Type":"application/x-ndjson"},body:JSON.stringify(e)+"\n"})}))}reportToStatsig(e){return i(this,void 0,void 0,(function*(){const t=this.config.statsigApiEndpoint||"https://events.statsigapi.net/v1/custom";yield fetch(t,{method:"POST",headers:{"STATSIG-API-KEY":this.config.statsigKey,"Content-Type":"application/json"},body:JSON.stringify({events:[{eventName:"widget_performance",value:e,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 ai=null;function di(e){return ai||(ai=new ri(e)),ai}class ci{constructor(e={}){this.items=new Map,this.observer=null,this.preloadObserver=null,this.loadingQueue=[],this.activeLoads=0,this.performanceMonitor=di(),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"),n=(e?this.items.get(e):null)||(i?this.items.get(i):null);n&&(!t.isIntersecting||n.isLoaded||n.isLoading||(n.viewportEntryTime=performance.now(),this.performanceMonitor.recordLazyLoad(n.compositionId,n.viewportEntryTime),this.queueLoad(n)))}}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"),n=(e?this.items.get(e):null)||(i?this.items.get(i):null);!n||n.isPreloaded||n.isLoaded||t.isIntersecting&&this.preloadResources(n)}}register(e,t,i,n={}){const s=e.getAttribute("data-lazy-id")||`lazy_${t}_${Math.random().toString(36).substr(2,9)}`;e.setAttribute("data-lazy-id",s),e.setAttribute("data-composition-id",t);const o={element:e,compositionId:t,config:n.config||{},loadFunction:i,priority:n.priority||5,retryCount:0,isLoading:!1,isLoaded:!1,isPreloaded:!1,resourceUrls:n.resourceUrls};this.items.set(s,o),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&&o.resourceUrls&&this.addResourceHints(o.resourceUrls),this.observer||setTimeout((()=>this.loadItem(o)),100)}unregister(e){let t=e,i=this.items.get(e);if(!i)for(const[n,s]of this.items.entries())if(s.compositionId===e){t=n,i=s;break}if(!i)return;this.observer&&this.observer.unobserve(i.element),this.preloadObserver&&this.preloadObserver.unobserve(i.element);const n=this.retryTimeouts.get(t)||this.retryTimeouts.get(i.compositionId);n&&(clearTimeout(n),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 i(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(e){return i(this,void 0,void 0,(function*(){if(!e.isLoading&&!e.isLoaded){e.isLoading=!0,this.activeLoads++,this.performanceMonitor.startWidgetLoad(e.compositionId,{isLazyLoaded:!0,bundleSize:this.estimateBundleSize(e)});try{e.element.classList.add("widgetic-loading"),e.element.classList.remove("widgetic-lazy-loading"),yield e.loadFunction(),e.isLoaded=!0,e.element.classList.remove("widgetic-loading"),e.element.classList.add("widgetic-loaded"),e.element.removeAttribute("data-lazy"),this.observer&&this.observer.unobserve(e.element),this.preloadObserver&&this.preloadObserver.unobserve(e.element),this.performanceMonitor.endWidgetLoad(e.compositionId,!0)}catch(t){if(e.element.classList.add("widgetic-load-error"),this.performanceMonitor.recordWidgetError(e.compositionId,t instanceof Error?t.message:"Load failed"),this.performanceMonitor.endWidgetLoad(e.compositionId,!1),e.retryCount<this.config.retryAttempts){e.retryCount++,this.performanceMonitor.recordWidgetRetry(e.compositionId,`Attempt ${e.retryCount}`);const t=setTimeout((()=>{e.isLoading=!1,this.retryTimeouts.delete(e.compositionId),this.loadItem(e)}),this.config.retryDelay*e.retryCount);this.retryTimeouts.set(e.compositionId,t)}}finally{e.isLoading=!1,this.activeLoads--,this.config.enableProgressiveLoading&&setTimeout((()=>this.processLoadingQueue()),10)}}}))}preloadResources(e){return i(this,void 0,void 0,(function*(){if(e.resourceUrls&&!e.isPreloaded){e.isPreloaded=!0;try{const t=e.resourceUrls.map((e=>this.preloadResource(e)));yield Promise.allSettled(t)}catch(e){}}}))}preloadResource(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,i)=>{const n=document.createElement("link");n.rel="preload",n.href=e,e.endsWith(".js")?n.as="script":e.endsWith(".css")?n.as="style":e.match(/\.(png|jpg|jpeg|gif|webp|svg)$/)?n.as="image":(n.as="fetch",n.setAttribute("crossorigin","anonymous")),n.onload=()=>t(),n.onerror=()=>i(new Error(`Failed to preload ${e}`)),document.head.appendChild(n)}))}))}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(e){const t=this.items.get(e);return t?t.isLoaded?Promise.resolve():new Promise(((e,n)=>{const s=t.loadFunction;t.loadFunction=()=>i(this,void 0,void 0,(function*(){try{yield s(),e()}catch(e){n(e)}})),this.loadItem(t)})):Promise.reject(new Error(`Widget ${e} 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,n=window.innerWidth||document.documentElement.clientWidth;return t.top<i&&t.bottom>0&&t.left<n&&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)),n=this.performanceMonitor.getMetrics().filter((e=>"lazy-load"===e.name)).map((e=>e.value)),s=n.length>0?n.reduce(((e,t)=>e+t),0)/n.length:0,o=e.filter((e=>this.isElementVisible(e.element))),r=o.filter((e=>e.isLoaded)),a=o.length>0?r.length/o.length:0,d=e.filter((e=>e.isPreloaded)),c=e.length>0?d.length/e.length:0;return{totalItems:e.length,loadedItems:t.length,failedItems:i.length,averageLoadTime:s,viewportUtilization:a,preloadSuccess:c}}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 li=null;class ui{constructor(e={}){this.resources=new Map,this.loadQueue=[],this.activeRequests=0,this.performanceMonitor=di(),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 i(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 i(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 n={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,n),this.shouldPreload(n,i.preload)?this.preloadResource(n):this.shouldPrefetch(n,i.prefetch)&&setTimeout((()=>this.prefetchResource(n)),this.config.prefetchDelay),n}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(e){return i(this,void 0,void 0,(function*(){if(e.isPreloaded||e.isLoaded)return;const t=performance.now();try{const i=document.createElement("link");i.rel="preload",i.href=e.url,i.as="script"===e.type?"script":"style"===e.type?"style":"font"===e.type?"font":"image"===e.type?"image":"fetch","font"!==e.type&&"fetch"!==e.type||(i.crossOrigin="anonymous"),yield new Promise(((n,s)=>{i.onload=()=>{e.isPreloaded=!0,e.loadTime=performance.now()-t,this.performanceMonitor.recordMetric("preload",e.loadTime,{url:e.url,type:e.type,priority:e.priority}),n()},i.onerror=()=>s(new Error(`Failed to preload ${e.url}`)),document.head.appendChild(i)}))}catch(e){}}))}prefetchResource(e){return i(this,void 0,void 0,(function*(){if(!e.isPrefetched&&!e.isLoaded)try{const t=document.createElement("link");t.rel="prefetch",t.href=e.url,document.head.appendChild(t),e.isPrefetched=!0,this.performanceMonitor.recordMetric("prefetch",1,{url:e.url,type:e.type,priority:e.priority})}catch(e){}}))}loadResources(e){return i(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]})),n=[];for(let e=0;e<i.length;e+=this.config.maxConcurrentRequests){const t=i.slice(e,e+this.config.maxConcurrentRequests),s=yield Promise.all(t.map((e=>this.loadResource(e))));n.push(...s)}return n}))}loadResource(e){return i(this,void 0,void 0,(function*(){if(e.isLoaded)return e;const t=performance.now();try{const i=yield fetch(e.url);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);e.isLoaded=!0,e.loadTime=performance.now()-t,e.size=parseInt(i.headers.get("content-length")||"0"),this.performanceMonitor.recordMetric("resource-fetch",e.loadTime,{url:e.url,type:e.type,size:e.size,priority:e.priority})}catch(e){throw e}return e}))}loadBundleWithSplitting(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.enableBundleSplitting)return this.loadBundle(e,t);try{const i=e.replace(/\.js$/,"-core.js");yield this.loadResource(this.registerResource(i,"script",{priority:"critical",compositionId:t}));const n=e.replace(/\.js$/,"-widget.js");yield this.loadResource(this.registerResource(n,"script",{priority:"high",compositionId:t}));const s=e.replace(/\.js$/,"-features.js");this.prefetchResource(this.registerResource(s,"script",{priority:"medium",compositionId:t}))}catch(i){return this.loadBundle(e,t)}}))}loadBundle(e,t){return i(this,void 0,void 0,(function*(){yield this.loadResource(this.registerResource(e,"script",{priority:"high",compositionId:t}))}))}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)),n=e.filter((e=>e.isPrefetched)),s=e.filter((e=>e.cached)),o=t.filter((e=>e.size)).reduce(((e,t)=>e+(t.size||0)),0),r=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:n.length,cachedResources:s.length,totalSize:o,averageLoadTime:r,cacheHitRate:t.length>0?s.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 hi=null;function gi(e){return hi||(hi=new ui(e)),hi}class pi{constructor(e={}){this.rateLimitTracker=new Map,this.globalRateLimit={count:0,windowStart:Date.now(),violations:0},this.behaviorTracker=new Map,this.blockedInstances=new Set,this.suspiciousInstances=new Set,this.cleanupInterval=null,this.config=Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0,maxTextLength:1e5,maxUpdatesPerMinute:60,maxGlobalUpdatesPerMinute:1e3,suspiciousActivityThreshold:5},e),this.startCleanupTask(),O.info("[SecurityManager] Initialized with config:",this.config)}static getInstance(e){return pi.instance||(pi.instance=new pi(e)),pi.instance}validateTextFieldUpdate(e,t,i,n){const s=`${e}:${t}`;if(this.blockedInstances.has(e))return{allowed:!1,reason:"Instance blocked due to security violations",severity:"high"};if(i.length>this.config.maxTextLength)return this.recordViolation(e,"text_length_exceeded"),{allowed:!1,reason:`Text length exceeds maximum (${this.config.maxTextLength} characters)`,severity:"medium"};if(this.config.enableRateLimit){const t=this.checkRateLimit(s);if(!t.allowed)return this.recordViolation(e,"rate_limit_exceeded"),t}if(this.config.enableBotDetection){const t=this.analyzeBehavior(e,i);if(!t.allowed)return this.recordViolation(e,"suspicious_behavior"),t}let o=i;if(this.config.enableSanitization){const t=this.sanitizeInput(i);if(!t.allowed)return this.recordViolation(e,"malicious_content"),t;o=t.sanitizedText||i}const r=this.analyzeContentPatterns(i);return r.allowed?{allowed:!0,sanitizedText:o}:(this.recordViolation(e,"suspicious_pattern"),r)}sanitizeInput(e){try{const t=/javascript:/gi,i=/\bon\w+\s*=/gi,n=/data:text\/html/gi;if(/<script[^>]*>[\s\S]*?<\/script>/gi.test(e)||t.test(e)||i.test(e)||n.test(e))return{allowed:!1,reason:"Potentially malicious content detected",severity:"high"};let s=e.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/javascript:/gi,"").replace(/\bon\w+\s*=/gi,"").replace(/data:text\/html/gi,"data:text/plain");s=this.sanitizeLinks(s);const o=(s.match(/<[a-z][^>]*>/gi)||[]).length,r=s.replace(/<[^>]+>/g,"").length;if(o>0&&r>0){if(o/r>.1)return{allowed:!1,reason:"Excessive HTML content detected",severity:"medium"}}return{allowed:!0,sanitizedText:s}}catch(e){return O.warn("[SecurityManager] Sanitization error:",e),{allowed:!1,reason:"Input sanitization failed",severity:"medium"}}}sanitizeLinks(e){try{const t=/<a\b(?![^>]*\bhref\s*=)[^>]*>/gi,i=e.replace(/<a\b(?![^>]*\bhref\s*=)[^>]*>([\s\S]*?)<\/a>/gi,"$1").replace(t,""),n=/<a\s+([^>]*href\s*=\s*["'][^"']*["'][^>]*)>/gi;return i.replace(n,((e,t)=>{const i=t.match(/href\s*=\s*["']([^"']*)["']/i);if(!i)return"";const n=i[1],s=["javascript:","data:","vbscript:","file:","ftp:"];for(const e of s)if(n.toLowerCase().startsWith(e))return"";const o=this.isExternalLink(n);let r=t.replace(/\btarget\s*=\s*["'][^"']*["']/gi,"").replace(/\brel\s*=\s*["'][^"']*["']/gi,"").replace(/\bon\w+\s*=\s*["'][^"']*["']/gi,"").trim();return r+=o?' target="_blank" rel="nofollow noopener noreferrer"':' rel="noopener"',`<a ${r}>`}))}catch(t){return O.warn("[SecurityManager] Link sanitization error:",t),e}}isExternalLink(e){try{if(e.startsWith("//"))return!0;if(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("#")||e.startsWith("?"))return!1;if(e.includes("://")){const t=new URL(e),i="undefined"!=typeof window?window.location.hostname:"";return t.hostname!==i}return!1}catch(e){return!0}}checkRateLimit(e){const t=Date.now(),i=this.rateLimitTracker.get(e)||{count:0,windowStart:t,violations:0};return t-i.windowStart>=6e4&&(i.count=0,i.windowStart=t),i.count++,this.rateLimitTracker.set(e,i),i.count>this.config.maxUpdatesPerMinute?(i.violations++,{allowed:!1,reason:"Rate limit exceeded for this widget",severity:"medium"}):(t-this.globalRateLimit.windowStart>=6e4&&(this.globalRateLimit.count=0,this.globalRateLimit.windowStart=t),this.globalRateLimit.count++,this.globalRateLimit.count>this.config.maxGlobalUpdatesPerMinute?(this.globalRateLimit.violations++,{allowed:!1,reason:"Global rate limit exceeded",severity:"high"}):{allowed:!0})}analyzeBehavior(e,t){const i=Date.now(),n=this.behaviorTracker.get(e)||{updateCount:0,averageInterval:0,suspiciousPatterns:0,firstSeen:i,lastSeen:i,textLengthVariations:[],updateIntervals:[]},s=i-n.lastSeen;if(n.updateIntervals.push(s),n.textLengthVariations.push(t.length),n.updateIntervals.length>20&&(n.updateIntervals=n.updateIntervals.slice(-20),n.textLengthVariations=n.textLengthVariations.slice(-20)),n.updateCount++,n.lastSeen=i,n.updateIntervals.length>1){const e=n.updateIntervals.filter((e=>e>0));n.averageInterval=e.reduce(((e,t)=>e+t),0)/e.length}let o=0;if(n.updateIntervals.length>=5){const e=n.updateIntervals.slice(-5);this.calculateVariance(e)<100&&o++}if(n.updateIntervals.length>=3){n.updateIntervals.slice(-3).every((e=>e<100&&e>0))&&o++}if(n.textLengthVariations.length>=5){const e=n.textLengthVariations.slice(-5);1===new Set(e).size&&e[0]>10&&o++}const r=i-n.firstSeen;if(r>0&&n.updateCount>50){n.updateCount/(r/1e3)>2&&o++}if(n.suspiciousPatterns=o,this.behaviorTracker.set(e,n),o>=this.config.suspiciousActivityThreshold){this.suspiciousInstances.add(e);const t=this.rateLimitTracker.get(`${e}:suspicious`);return t&&t.violations>3?(this.blockedInstances.add(e),{allowed:!1,reason:"Instance blocked due to repeated suspicious behavior",severity:"high"}):{allowed:!1,reason:"Suspicious behavior pattern detected",severity:"medium"}}return{allowed:!0}}analyzeContentPatterns(e){if((e.match(/https?:\/\/[^\s]+/g)||[]).length>=5)return{allowed:!1,reason:"Spam-like content pattern detected",severity:"medium"};const t=[/(.)\1{50,}/g,/\b(buy|sale|discount|offer|free|winner|congratulations|urgent|click here)\b.*\b(buy|sale|discount|offer|free|winner|congratulations|urgent|click here)\b/gi,/\$[0-9]{3,}/g];for(const i of t)if(i.test(e))return{allowed:!1,reason:"Spam-like content pattern detected",severity:"medium"};const i=[/\bunion\s+select\b/gi,/\bdrop\s+table\b/gi,/\binsert\s+into\b/gi,/\bdelete\s+from\b/gi,/<iframe[^>]*src/gi,/<object[^>]*data/gi];for(const t of i)if(t.test(e))return{allowed:!1,reason:"Potential injection attempt detected",severity:"high"};return{allowed:!0}}recordViolation(e,t){O.warn(`[SecurityManager] Security violation: ${t}`,{instanceId:e});const i=`${e}:violations`,n=this.rateLimitTracker.get(i)||{count:0,windowStart:Date.now(),violations:0};n.violations++,this.rateLimitTracker.set(i,n),n.violations>=10&&(this.blockedInstances.add(e),O.warn(`[SecurityManager] Blocked instance due to repeated violations: ${e}`)),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-violation",{detail:{instanceId:e,violationType:t,timestamp:Date.now()}}))}calculateVariance(e){if(e.length<2)return 0;const t=e.reduce(((e,t)=>e+t))/e.length;return e.map((e=>Math.pow(e-t,2))).reduce(((e,t)=>e+t))/e.length}startCleanupTask(){this.cleanupInterval=setInterval((()=>{this.cleanup()}),3e5)}cleanup(){const e=Date.now(),t=18e5;for(const[i,n]of this.rateLimitTracker.entries())e-n.windowStart>t&&this.rateLimitTracker.delete(i);for(const[i,n]of this.behaviorTracker.entries())e-n.lastSeen>t&&this.behaviorTracker.delete(i);O.debug("[SecurityManager] Cleanup completed",{rateLimitEntries:this.rateLimitTracker.size,behaviorEntries:this.behaviorTracker.size,blockedInstances:this.blockedInstances.size})}isInstanceBlocked(e){return this.blockedInstances.has(e)}isInstanceSuspicious(e){return this.suspiciousInstances.has(e)}unblockInstance(e){this.blockedInstances.delete(e),this.suspiciousInstances.delete(e),this.behaviorTracker.delete(e);for(const t of this.rateLimitTracker.keys())t.startsWith(e)&&this.rateLimitTracker.delete(t);O.info(`[SecurityManager] Unblocked instance: ${e}`)}getSecurityStats(){return{blockedInstances:this.blockedInstances.size,suspiciousInstances:this.suspiciousInstances.size,rateLimitEntries:this.rateLimitTracker.size,behaviorEntries:this.behaviorTracker.size,globalRateLimit:this.globalRateLimit,config:this.config}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),O.info("[SecurityManager] Configuration updated:",e)}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.rateLimitTracker.clear(),this.behaviorTracker.clear(),this.blockedInstances.clear(),this.suspiciousInstances.clear(),O.info("[SecurityManager] Destroyed")}}function mi(e){return pi.getInstance(e)}var vi=Object.freeze({__proto__:null,SecurityManager:pi,getSecurityManager:mi});class fi{constructor(e){this.intersectionObserver=null,this.isInViewport=!0,this.hasBeenInViewport=!1,this.scrollListener=null,this.lastScrollY=0,this.scrollDistance=0,this.isTriggered=!1,this.debounceTimer=null,this.rafId=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,totalScrollDistance:0,viewportChanges:0},this.widgetId=e.widgetId,this.element=e.element,this.type=e.type,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,threshold:.1,distance:100,direction:"down",debounce:100}}initialize(){this.config.enabled&&(O.debug("Initializing ScrollTrigger",{widgetId:this.widgetId,type:this.type,config:this.config}),this.lastScrollY=window.scrollY,"viewport"===this.type?this.initializeViewportDetection():"distance"===this.type&&this.initializeScrollDistance())}initializeViewportDetection(){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:this.config.threshold||.1,rootMargin:"0px"}),this.intersectionObserver.observe(this.element),O.debug("Viewport detection initialized",{widgetId:this.widgetId,threshold:this.config.threshold})}initializeScrollDistance(){this.scrollListener=this.debounce(this.handleScrollDistance.bind(this),this.config.debounce||100),window.addEventListener("scroll",this.scrollListener,{passive:!0}),O.debug("Scroll distance tracking initialized",{widgetId:this.widgetId,distance:this.config.distance})}handleIntersection(e){if(this.isDestroyed)return;const t=e[e.length-1];if(!t)return;const i=this.isInViewport;if(this.isInViewport=t.isIntersecting,t.isIntersecting&&(this.hasBeenInViewport=!0),this.stats.viewportChanges++,O.debug("Viewport intersection changed",{widgetId:this.widgetId,isIntersecting:this.isInViewport,intersectionRatio:t.intersectionRatio}),i&&!this.isInViewport){if(!this.hasBeenInViewport)return;this.triggerActivated("scroll-out-of-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}else!i&&this.isInViewport&&this.triggerDeactivated("scroll-back-in-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}observeElement(e){!this.isDestroyed&&"viewport"===this.type&&this.intersectionObserver&&e!==this.element&&(this.intersectionObserver.unobserve(this.element),this.element=e,this.intersectionObserver.observe(e),O.debug("ScrollTrigger now watching another element",{widgetId:this.widgetId}))}handleScrollDistance(){this.isDestroyed||(this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame((()=>{const e=window.scrollY,t=e-this.lastScrollY;this.stats.totalScrollDistance+=Math.abs(t);const i=t>0,n=t<0;"down"===this.config.direction&&i?this.scrollDistance+=t:("up"===this.config.direction&&n||"any"===this.config.direction)&&(this.scrollDistance+=Math.abs(t));const s=this.config.distance||100;!this.isTriggered&&this.scrollDistance>=s&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{scrollDistance:this.scrollDistance,direction:i?"down":"up",scrollY:e})),this.lastScrollY=e,O.debug("Scroll distance updated",{widgetId:this.widgetId,scrollDistance:this.scrollDistance,requiredDistance:s,isTriggered:this.isTriggered})})))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),O.debug("Scroll trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}triggerDeactivated(e,t){const i=new CustomEvent("widgetic:trigger-deactivated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),O.debug("Scroll trigger deactivated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return i=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e()}),t)}}updateConfig(e){if(this.isDestroyed)return;const t=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0!==e.threshold&&"viewport"===this.type&&(this.destroy(),this.isDestroyed=!1,this.initializeViewportDetection()),void 0!==e.distance&&"distance"===this.type&&(this.scrollDistance=0,this.isTriggered=!1),O.debug("ScrollTrigger config updated",{widgetId:this.widgetId,oldConfig:t,newConfig:this.config})}reset(){this.isDestroyed||(this.scrollDistance=0,this.isTriggered=!1,this.lastScrollY=window.scrollY,O.debug("ScrollTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{type:this.type,isInViewport:this.isInViewport,scrollDistance:this.scrollDistance,isTriggered:this.isTriggered,currentScrollY:window.scrollY})}isActive(){return"viewport"===this.type?!this.isInViewport:"distance"===this.type&&this.isTriggered}forceActivate(){"viewport"===this.type?this.triggerActivated("scroll-out-of-view",{manual:!0}):"distance"===this.type&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{manual:!0}))}forceDeactivate(){"viewport"===this.type&&this.triggerDeactivated("scroll-back-in-view",{manual:!0})}destroy(){this.isDestroyed||(this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.scrollListener&&(window.removeEventListener("scroll",this.scrollListener),this.scrollListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.isDestroyed=!0,O.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class yi{constructor(e){this.mouseLeaveListener=null,this.lastMouseY=0,this.isTriggered=!1,this.scrollUpListener=null,this.visibilityChangeListener=null,this.backButtonListener=null,this.touchStartListener=null,this.touchEndListener=null,this.lastScrollY=0,this.scrollUpDistance=0,this.touchStartY=0,this.touchStartTime=0,this.isScrollingUp=!1,this.debounceTimer=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,desktopTriggers:0,mobileTriggers:0,backButtonTriggers:0,scrollUpTriggers:0,tabSwitchTriggers:0},this.widgetId=e.widgetId,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}}}initialize(){var e,t;this.config.enabled&&(O.debug("Initializing ExitIntentTrigger",{widgetId:this.widgetId,config:this.config}),this.lastScrollY=window.scrollY,(null===(e=this.config.desktop)||void 0===e?void 0:e.enabled)&&this.isDesktop()&&this.initializeDesktopTriggers(),(null===(t=this.config.mobile)||void 0===t?void 0:t.enabled)&&this.isMobile()&&this.initializeMobileTriggers())}isDesktop(){return!("ontouchstart"in window)&&!navigator.maxTouchPoints}isMobile(){return"ontouchstart"in window||navigator.maxTouchPoints>0}initializeDesktopTriggers(){var e,t;this.mouseLeaveListener=this.debounce(this.handleMouseLeave.bind(this),(null===(e=this.config.desktop)||void 0===e?void 0:e.delay)||100),this.mouseLeaveListener&&(document.addEventListener("mouseleave",this.mouseLeaveListener),document.addEventListener("mouseout",this.mouseLeaveListener)),O.debug("Desktop exit intent triggers initialized",{widgetId:this.widgetId,sensitivity:null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity})}initializeMobileTriggers(){const e=this.config.mobile;e.backButton&&(this.backButtonListener=this.handleBackButton.bind(this),window.addEventListener("popstate",this.backButtonListener),history.pushState({widgeticExitIntent:!0},"",window.location.href)),e.scrollUp&&(this.scrollUpListener=this.debounce(this.handleScrollUp.bind(this),50),this.scrollUpListener&&window.addEventListener("scroll",this.scrollUpListener,{passive:!0}),this.touchStartListener=this.handleTouchStart.bind(this),this.touchEndListener=this.handleTouchEnd.bind(this),document.addEventListener("touchstart",this.touchStartListener,{passive:!0}),document.addEventListener("touchend",this.touchEndListener,{passive:!0})),e.tabSwitch&&(this.visibilityChangeListener=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeListener)),O.debug("Mobile exit intent triggers initialized",{widgetId:this.widgetId,backButton:e.backButton,scrollUp:e.scrollUp,tabSwitch:e.tabSwitch})}handleMouseLeave(e){var t;if(this.isDestroyed||this.isTriggered)return;const i=(null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity)||10;e.clientY<=i&&null===e.relatedTarget&&(this.isTriggered=!0,this.stats.desktopTriggers++,this.triggerActivated("exit-intent",{source:"desktop",method:"mouse-leave",mouseY:e.clientY,sensitivity:i}))}handleBackButton(e){var t;this.isDestroyed||(null===(t=e.state)||void 0===t?void 0:t.widgeticExitIntent)&&(this.stats.backButtonTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"back-button"}),history.pushState({widgeticExitIntent:!0},"",window.location.href))}handleScrollUp(){var e;if(this.isDestroyed)return;const t=window.scrollY,i=t-this.lastScrollY;if(i<0){this.scrollUpDistance+=Math.abs(i),this.isScrollingUp=!0;const n=(null===(e=this.config.mobile)||void 0===e?void 0:e.sensitivity)||50;this.scrollUpDistance>=n&&t<=100&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"scroll-up",scrollUpDistance:this.scrollUpDistance,currentScrollY:t,sensitivity:n}),this.scrollUpDistance=0)}else this.scrollUpDistance=0,this.isScrollingUp=!1;this.lastScrollY=t}handleTouchStart(e){if(this.isDestroyed||1!==e.touches.length)return;const t=e.touches[0];this.touchStartY=t.clientY,this.touchStartTime=Date.now()}handleTouchEnd(e){if(this.isDestroyed||1!==e.changedTouches.length)return;const t=e.changedTouches[0].clientY,i=Date.now()-this.touchStartTime,n=t-this.touchStartY;n>100&&i<300&&window.scrollY<=50&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"swipe-up",swipeDistance:n,touchDuration:i,scrollY:window.scrollY}))}handleVisibilityChange(){this.isDestroyed||document.hidden&&(this.stats.tabSwitchTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"tab-switch",visibilityState:document.visibilityState}))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),O.debug("Exit intent trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return(...i)=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e.apply(this,i)}),t)}}updateConfig(e){var t,i;if(this.isDestroyed)return;const n=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0===e.enabled&&void 0===(null===(t=e.desktop)||void 0===t?void 0:t.enabled)&&void 0===(null===(i=e.mobile)||void 0===i?void 0:i.enabled)||(this.destroy(),this.isDestroyed=!1,this.initialize()),O.debug("ExitIntentTrigger config updated",{widgetId:this.widgetId,oldConfig:n,newConfig:this.config})}reset(){this.isDestroyed||(this.isTriggered=!1,this.scrollUpDistance=0,this.isScrollingUp=!1,this.lastScrollY=window.scrollY,O.debug("ExitIntentTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{isTriggered:this.isTriggered,scrollUpDistance:this.scrollUpDistance,isScrollingUp:this.isScrollingUp,currentScrollY:window.scrollY,isDesktop:this.isDesktop(),isMobile:this.isMobile()})}isActive(){return this.isTriggered}forceActivate(e="desktop"){this.triggerActivated("exit-intent",{source:e,method:"manual",manual:!0})}destroy(){this.isDestroyed||(this.mouseLeaveListener&&(document.removeEventListener("mouseleave",this.mouseLeaveListener),document.removeEventListener("mouseout",this.mouseLeaveListener),this.mouseLeaveListener=null),this.backButtonListener&&(window.removeEventListener("popstate",this.backButtonListener),this.backButtonListener=null),this.scrollUpListener&&(window.removeEventListener("scroll",this.scrollUpListener),this.scrollUpListener=null),this.visibilityChangeListener&&(document.removeEventListener("visibilitychange",this.visibilityChangeListener),this.visibilityChangeListener=null),this.touchStartListener&&(document.removeEventListener("touchstart",this.touchStartListener),this.touchStartListener=null),this.touchEndListener&&(document.removeEventListener("touchend",this.touchEndListener),this.touchEndListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.isDestroyed=!0,O.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const bi={"top-left":["top","left"],"top-center":["top","center"],"top-right":["top","right"],"center-left":["center","left"],center:["center","center"],"center-center":["center","center"],"center-right":["center","right"],"bottom-left":["bottom","left"],"bottom-center":["bottom","center"],"bottom-right":["bottom","right"]};class wi{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return wi.instance||(wi.instance=new wi),wi.instance}canShowOverlay(e,t){if(!(null==t?void 0:t.enabled))return!0;const i=this.getViewHistory(e,t),n=Date.now(),s=60*t.timePeriodHours*60*1e3,o=i.filter((e=>n-e.timestamp<=s)),r=o.length<t.maxViews;return O.debug(`[RecurrenceManager] Recurrence check for ${e}`,{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:o.length,canShow:r}),r}recordView(e,t){if(!(null==t?void 0:t.enabled))return;const i={timestamp:Date.now(),widgetId:e},n=this.getViewHistory(e,t);n.push(i);const s=60*t.timePeriodHours*60*1e3,o=Date.now(),r=n.filter((e=>o-e.timestamp<=s));this.saveViewHistory(e,t,r),O.debug(`[RecurrenceManager] Recorded view for ${e}`,{totalViews:r.length,timePeriodHours:t.timePeriodHours})}getViewHistory(e,t){if(!this.isLocalStorageAvailable())return[];try{const i=this.getStorageKey(e,t),n=localStorage.getItem(i);if(!n)return[];const s=JSON.parse(n);return s.version!==this.storageVersion?[]:Array.isArray(s.views)?s.views:[]}catch(t){return O.warn(`[RecurrenceManager] Failed to load view history for ${e}`,{error:t}),[]}}saveViewHistory(e,t,i){if(this.isLocalStorageAvailable())try{const n=this.getStorageKey(e,t),s={version:this.storageVersion,widgetId:e,views:i,lastUpdated:Date.now()};localStorage.setItem(n,JSON.stringify(s))}catch(t){O.warn(`[RecurrenceManager] Failed to save view history for ${e}`,{error:t})}}getStorageKey(e,t){const i=(null==t?void 0:t.storageKeySuffix)?`-${t.storageKeySuffix}`:"";return`${this.storageKey}-${e}${i}`}isLocalStorageAvailable(){try{const e="__localStorage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}getStats(e,t){if(!(null==t?void 0:t.enabled))return null;const i=this.getViewHistory(e,t),n=Date.now(),s=60*t.timePeriodHours*60*1e3,o=i.filter((e=>n-e.timestamp<=s));return{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:o.length,remainingViews:Math.max(0,t.maxViews-o.length),canShow:o.length<t.maxViews,lastView:o.length>0?o[o.length-1].timestamp:null,viewHistory:o.map((e=>e.timestamp))}}clearHistory(e,t){if(!(null==t?void 0:t.enabled)||!this.isLocalStorageAvailable())return;const i=this.getStorageKey(e,t);localStorage.removeItem(i),O.debug(`[RecurrenceManager] Cleared view history for ${e}`)}cleanup(){if(!this.isLocalStorageAvailable())return;const e=[];for(let t=0;t<localStorage.length;t++){const i=localStorage.key(t);if(null==i?void 0:i.startsWith(this.storageKey))try{const t=JSON.parse(localStorage.getItem(i)||"{}"),n=Date.now()-864e5;t.lastUpdated<n&&e.push(i)}catch(t){e.push(i)}}e.forEach((e=>localStorage.removeItem(e))),e.length>0&&O.debug(`[RecurrenceManager] Cleaned up ${e.length} old view records`)}}class Ii{constructor(e){var t;this.scrollTrigger=null,this.exitIntentTrigger=null,this.portal=null,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,this.placeholder=null,this.isInOverlay=!1,this.isDestroyed=!1,this.triggerInstances=new Map,this.keydownListener=null,this.recurrenceManager=wi.getInstance(),this.delayTimer=null,this.domReadyListener=null,this.fullWidthRestore=null,this.onTriggerActivated=e=>this.handleTriggerActivated(e),this.onTriggerDeactivated=e=>this.handleTriggerDeactivated(e),this.onOverlayClose=e=>this.handleOverlayClose(e),this.widgetId=e.widgetId,this.element=e.element,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.mode=this.config.mode||"site",this.displayWhenShown=null!==(t=e.displayWhenShown)&&void 0!==t?t:"",this.originalParent=this.element.parentElement,this.originalNextSibling=this.element.nextSibling,this.initialize()}getDefaultConfig(){return{mode:"site",scroll:{enabled:!0,threshold:.1,distance:100,direction:"down"},exitIntent:{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}},overlay:{position:"bottom-right",offset:{x:20,y:20},className:"",style:"",closeButton:!0,backdrop:!1,animation:"slide",background:{enabled:!0,color:"#000",opacity:.5}},recurrence:{enabled:!1,maxViews:1,timePeriodHours:24}}}initialize(){switch(O.debug("Initializing TriggerManager",{widgetId:this.widgetId,mode:this.mode,config:this.config}),this.mode){case"site":break;case"mixed":this.initializeScrollTrigger("viewport");break;case"overlay":this.hideWidget(),this.armOverlayEventTrigger()}this.bindEvents()}armOverlayEventTrigger(){switch(this.config.eventTrigger){case"pageLoad":this.showOnLoad();break;case"delay":this.showAfterDelay();break;case"scroll":this.initializeScrollTrigger("distance");break;default:this.initializeScrollTrigger("distance"),this.initializeExitIntentTrigger()}}whenDomReady(e){this.isDestroyed||("loading"===document.readyState?(this.domReadyListener=()=>{this.domReadyListener=null,this.isDestroyed||e()},document.addEventListener("DOMContentLoaded",this.domReadyListener,{once:!0})):e())}showOnLoad(){this.whenDomReady((()=>this.showOverlay()))}showAfterDelay(){var e,t;if(!1===(null===(e=this.config.delay)||void 0===e?void 0:e.enabled))return;const i=null===(t=this.config.delay)||void 0===t?void 0:t.delayMs,n="number"==typeof i&&Number.isFinite(i)&&i>=0?i:3e3;this.whenDomReady((()=>{null===this.delayTimer&&(this.delayTimer=setTimeout((()=>{this.delayTimer=null,this.showOverlay()}),n),O.debug("Delay trigger armed",{widgetId:this.widgetId,delayMs:n}))}))}initializeScrollTrigger(e){var t;(null===(t=this.config.scroll)||void 0===t?void 0:t.enabled)&&(this.scrollTrigger=new fi({widgetId:this.widgetId,element:this.element,type:e,config:this.config.scroll}),this.triggerInstances.set("scroll",this.scrollTrigger))}initializeExitIntentTrigger(){var e;(null===(e=this.config.exitIntent)||void 0===e?void 0:e.enabled)&&(this.exitIntentTrigger=new yi({widgetId:this.widgetId,config:this.config.exitIntent}),this.triggerInstances.set("exitIntent",this.exitIntentTrigger))}bindEvents(){document.addEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.addEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.addEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener=this.handleEscapeKey.bind(this),document.addEventListener("keydown",this.keydownListener)}handleTriggerActivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;O.debug("Trigger activated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-out-of-view"===i?this.showOverlay():"overlay"!==this.mode||"scroll-distance"!==i&&"exit-intent"!==i||this.showOverlay(),this.dispatchTriggerEvent("activated",i,n)}handleTriggerDeactivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;O.debug("Trigger deactivated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-back-in-view"===i&&this.hideOverlay(),this.dispatchTriggerEvent("deactivated",i,n)}handleOverlayClose(e){var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===this.widgetId&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}handleEscapeKey(e){"Escape"===e.key&&this.isInOverlay&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}showOverlay(){var e,t,i,n,s;if(!this.isInOverlay&&!this.isDestroyed){if("overlay"===this.mode&&(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)){if(!this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence))return O.debug("Overlay blocked by recurrence limits",{widgetId:this.widgetId,recurrenceConfig:this.config.recurrence}),void this.dispatchEvent("overlay-blocked",{reason:"recurrence-limit",recurrenceStats:this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)})}this.portal||(this.portal=Kt({target:"widgetic-trigger-portal",className:(null===(t=this.config.overlay)||void 0===t?void 0:t.className)||"",style:(null===(i=this.config.overlay)||void 0===i?void 0:i.style)||"",zIndex:this.getOverlayZIndex(),clickThrough:!this.hasOverlayBackground()})),this.overlayContainer=this.createOverlayContainer(),this.portal.mount(this.overlayContainer),this.leavePlaceholder(),this.overlayContainer.appendChild(this.element),this.element.style.display=this.displayWhenShown,this.applyFullWidthSizing(),this.isInOverlay=!0,"overlay"===this.mode&&(null===(n=this.config.recurrence)||void 0===n?void 0:n.enabled)&&this.recurrenceManager.recordView(this.widgetId,this.config.recurrence),O.debug("Widget moved to overlay",{widgetId:this.widgetId}),this.dispatchEvent("overlay-shown",{mode:this.mode,position:null===(s=this.config.overlay)||void 0===s?void 0:s.position})}}leavePlaceholder(){var e;if("mixed"!==this.mode||this.placeholder)return;const t=this.element.parentNode;if(!t)return;const{width:i,height:n}=this.element.getBoundingClientRect(),s=document.createElement("div");s.setAttribute("data-widgetic-placeholder",this.widgetId),s.setAttribute("aria-hidden","true"),s.style.cssText=`display:block;visibility:hidden;pointer-events:none;width:${i}px;height:${n}px;`,t.insertBefore(s,this.element),this.placeholder=s,null===(e=this.scrollTrigger)||void 0===e||e.observeElement(s)}returnToPlaceholder(){const e=this.placeholder;return!!e&&(this.placeholder=null,!!e.parentNode&&(e.parentNode.replaceChild(this.element,e),!0))}hideOverlay(){var e;this.isInOverlay&&!this.isDestroyed&&(this.restoreFullWidthSizing(),!this.returnToPlaceholder()&&this.originalParent&&(this.originalNextSibling?this.originalParent.insertBefore(this.element,this.originalNextSibling):this.originalParent.appendChild(this.element)),"mixed"===this.mode&&(null===(e=this.scrollTrigger)||void 0===e||e.observeElement(this.element)),this.portal&&this.portal.unmount(),this.overlayContainer=null,this.isInOverlay=!1,O.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,s;const o=document.createElement("div");o.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),c=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),l=this.getOverlayStyles(r,a,this.getOverlayZIndex(),c);if(o.style.cssText=l,d&&this.applyBackgroundStyling(o),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,c);o.appendChild(e)}return(null===(s=this.config.overlay)||void 0===s?void 0:s.animation)&&o.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(o),o}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,s=(null==n?void 0:n.color)||"#000000",o=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${s};\n opacity: ${o};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?99999999:Math.min(Math.floor(t),ne)}getOverlayStyles(e,t,i,n){const[s,o]=bi[e]||bi["bottom-right"];let r=`\n position: fixed;\n z-index: ${i};\n pointer-events: auto;\n max-height: 90vh;\n `;return n?r+="left: 0; right: 0; width: 100%; max-width: 100vw;":(r+="max-width: 90vw;",r+="left"===o?`left: ${t.x}px;`:"right"===o?`right: ${t.x}px;`:"left: 0; right: 0; margin-left: auto; margin-right: auto; width: -moz-fit-content; width: fit-content;"),r+="top"===s?`top: ${n?0:t.y}px;`:"bottom"===s?`bottom: ${n?0:t.y}px;`:"top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; height: -moz-fit-content; height: fit-content;",r}applyFullWidthSizing(){var e;if(!(null===(e=this.config.overlay)||void 0===e?void 0:e.fullWidth)||this.fullWidthRestore)return;const t=Array.from(this.element.querySelectorAll("iframe"));this.fullWidthRestore={elementWidth:this.element.style.width,iframes:t.map((e=>({iframe:e,width:e.style.width})))},this.element.style.width="100%",t.forEach((e=>{e.style.width="100%"}))}restoreFullWidthSizing(){this.fullWidthRestore&&(this.element.style.width=this.fullWidthRestore.elementWidth,this.fullWidthRestore.iframes.forEach((({iframe:e,width:t})=>{e.style.width=t})),this.fullWidthRestore=null)}createCloseButton(e,t=!1){const i=document.createElement("button");i.className="widgetic-trigger-overlay-close",i.setAttribute("aria-label","Close overlay"),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const s=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=s+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(e){this.isDestroyed||(this.config=Object.assign(Object.assign({},this.config),e),this.triggerInstances.forEach(((e,t)=>{"scroll"===t&&this.config.scroll?e.updateConfig(this.config.scroll):"exitIntent"===t&&this.config.exitIntent&&e.updateConfig(this.config.exitIntent)})),O.debug("TriggerManager config updated",{widgetId:this.widgetId,config:this.config}))}getStats(){var e;const t={widgetId:this.widgetId,mode:this.mode,isInOverlay:this.isInOverlay,isDestroyed:this.isDestroyed,triggerInstances:Array.from(this.triggerInstances.keys())};return this.triggerInstances.forEach(((e,i)=>{"function"==typeof e.getStats&&(t[`${i}Stats`]=e.getStats())})),(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(t.recurrenceStats=this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)),t}forceShowOverlay(){this.showOverlay()}forceHideOverlay(){this.hideOverlay()}getRecurrenceStats(){var e;return(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)?this.recurrenceManager.getStats(this.widgetId,this.config.recurrence):null}clearRecurrenceHistory(){var e;(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(this.recurrenceManager.clearHistory(this.widgetId,this.config.recurrence),O.debug("Recurrence history cleared",{widgetId:this.widgetId}))}canShowOverlay(){var e;return"overlay"!==this.mode||!(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)||this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence)}destroy(){this.isDestroyed||(null!==this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.domReadyListener&&(document.removeEventListener("DOMContentLoaded",this.domReadyListener),this.domReadyListener=null),this.isInOverlay&&this.hideOverlay(),this.placeholder&&(this.placeholder.remove(),this.placeholder=null),this.triggerInstances.forEach((e=>{"function"==typeof e.destroy&&e.destroy()})),this.triggerInstances.clear(),this.portal&&(this.portal.destroy(),this.portal=null),document.removeEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.removeEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.removeEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.recurrenceManager.cleanup(),this.isDestroyed=!0,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,O.debug("TriggerManager destroyed",{widgetId:this.widgetId}))}applyOverlayWidgetStyling(e){var t;if(!("mixed"===this.mode))return;if(!1!==(null===(t=this.config.overlay)||void 0===t?void 0:t.keepDimensions))return;const i=this.config.overlay;if(i){if(i.overlayWidth){const t="number"==typeof i.overlayWidth?`${i.overlayWidth}px`:i.overlayWidth;e.style.width=t,e.style.maxWidth=t}if(i.overlayHeight){const t="number"==typeof i.overlayHeight?`${i.overlayHeight}px`:i.overlayHeight;e.style.height=t,e.style.maxHeight=t}i.overlayResize&&this.applyOverlayResizeMode(e,i.overlayResize)}}applyOverlayResizeMode(e,t){switch(t){case"fill-width":e.style.width="90vw",e.style.height="auto",e.style.maxWidth="90vw";break;case"fill-height":e.style.height="90vh",e.style.width="auto",e.style.maxHeight="90vh";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="90vw",e.style.maxWidth="90vw";break;case"fixed-width":e.style.height="90vh",e.style.maxHeight="90vh";break;case"allow-scale-down":e.style.maxWidth="90vw",e.style.maxHeight="90vh";break;case"fill":e.style.width="90vw",e.style.height="90vh",e.style.maxWidth="90vw",e.style.maxHeight="90vh"}}}var Ei=Object.freeze({__proto__:null,TriggerManager:Ii});class Si{constructor(e={}){var t,i,n,s;this.cspDirectives=new Map,this.cspNonce="",this.encryptionKey=null,this.sensitiveDataCache=new Map,this.contentFilters=new Map,this.moderationQueue=new Map,this.auditEvents=[],this.auditBuffer=new Map,this.threatPatterns=new Map,this.threatScores=new Map,this.consentStatus=new Map,this.dataSubjects=new Map,this.config=Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0,maxTextLength:1e5,maxUpdatesPerMinute:60,maxGlobalUpdatesPerMinute:1e3,suspiciousActivityThreshold:5,auditLogging:!0,threatDetection:!0,csp:{level:"balanced",allowInlineStyles:!1,allowEval:!1,reportOnly:!1},secureData:{classification:"internal",encryptInTransit:!0,encryptAtRest:!1,anonymizeData:!1,dataRetentionDays:90},contentFilter:{enableProfanityFilter:!0,enableSpamDetection:!0,enableMalwareScanning:!0,autoModeration:!1},privacy:{enableGDPRCompliance:!0,enableCCPACompliance:!0,anonymizeUserData:!1,cookieConsent:!0,dataProcessingBasis:"legitimate_interest",dataSubjectRights:!0}},e),this.baseSecurityManager=pi.getInstance(this.config),this.initializeCSP(),this.initializeDataSecurity(),this.initializeContentFilters(),this.initializeThreatDetection(),this.initializePrivacyControls(),O.info("[AdvancedSecurityManager] Initialized with config:",{cspLevel:null===(t=this.config.csp)||void 0===t?void 0:t.level,dataClassification:null===(i=this.config.secureData)||void 0===i?void 0:i.classification,contentFiltering:null===(n=this.config.contentFilter)||void 0===n?void 0:n.enableProfanityFilter,privacy:null===(s=this.config.privacy)||void 0===s?void 0:s.enableGDPRCompliance})}static getInstance(e){return Si.instance||(Si.instance=new Si(e)),Si.instance}initializeCSP(){this.config.csp&&(this.cspNonce=this.generateNonce(),this.setupCSPDirectives(),this.applyCSP(),O.info("[AdvancedSecurityManager] CSP initialized with level:",this.config.csp.level))}generateNonce(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}setupCSPDirectives(){var e,t;const{level:i,allowedDomains:n=[],allowInlineStyles:s,allowEval:o}=this.config.csp,r=["'self'","https://widgetic.com","https://cdn.widgetic.com",...n];switch(i){case"strict":this.cspDirectives.set("default-src",["'self'"]),this.cspDirectives.set("script-src",["'self'",`'nonce-${this.cspNonce}'`]),this.cspDirectives.set("style-src",["'self'",`'nonce-${this.cspNonce}'`]),this.cspDirectives.set("img-src",["'self'","data:","https:"]),this.cspDirectives.set("connect-src",["'self'",...r]),this.cspDirectives.set("font-src",["'self'","https:"]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["'self'"]),this.cspDirectives.set("frame-ancestors",["'self'"]);break;case"balanced":this.cspDirectives.set("default-src",["'self'",...r]),this.cspDirectives.set("script-src",["'self'",`'nonce-${this.cspNonce}'`,...r,...o?["'unsafe-eval'"]:[]]),this.cspDirectives.set("style-src",["'self'",`'nonce-${this.cspNonce}'`,...r,...s?["'unsafe-inline'"]:[]]),this.cspDirectives.set("img-src",["'self'","data:","blob:","https:",...r]),this.cspDirectives.set("connect-src",["'self'",...r]),this.cspDirectives.set("font-src",["'self'","https:",...r]),this.cspDirectives.set("media-src",["'self'","blob:","https:",...r]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["'self'",...r]),this.cspDirectives.set("frame-ancestors",["'self'",...r]);break;case"permissive":this.cspDirectives.set("default-src",["'self'",...r,"https:"]),this.cspDirectives.set("script-src",["'self'","'unsafe-inline'","'unsafe-eval'",...r,"https:"]),this.cspDirectives.set("style-src",["'self'","'unsafe-inline'",...r,"https:"]),this.cspDirectives.set("img-src",["*","data:","blob:"]),this.cspDirectives.set("connect-src",["*"]),this.cspDirectives.set("font-src",["*"]),this.cspDirectives.set("media-src",["*"]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["*"])}(null===(e=this.config.csp)||void 0===e?void 0:e.customDirectives)&&Object.entries(this.config.csp.customDirectives).forEach((([e,t])=>{this.cspDirectives.set(e,t)})),(null===(t=this.config.csp)||void 0===t?void 0:t.reportUri)&&this.cspDirectives.set("report-uri",[this.config.csp.reportUri])}applyCSP(){var e;if("undefined"==typeof document)return;const t=this.buildCSPString();let i=document.querySelector('meta[http-equiv="Content-Security-Policy"]');i||(i=document.createElement("meta"),i.httpEquiv="Content-Security-Policy",document.head.appendChild(i)),(null===(e=this.config.csp)||void 0===e?void 0:e.reportOnly)&&(i.httpEquiv="Content-Security-Policy-Report-Only"),i.content=t,O.info("[AdvancedSecurityManager] CSP applied:",t)}buildCSPString(){const e=[];return this.cspDirectives.forEach(((t,i)=>{const n=i.replace(/([A-Z])/g,"-$1").toLowerCase();e.push(`${n} ${t.join(" ")}`)})),e.join("; ")}initializeDataSecurity(){return i(this,void 0,void 0,(function*(){var e;if(null===(e=this.config.secureData)||void 0===e?void 0:e.encryptAtRest)try{this.encryptionKey=yield crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),O.info("[AdvancedSecurityManager] Data encryption initialized")}catch(e){O.error("[AdvancedSecurityManager] Failed to initialize encryption:",e)}}))}initializeContentFilters(){this.config.contentFilter&&(this.addDefaultContentFilters(),this.config.contentFilter.customFilters&&this.config.contentFilter.customFilters.forEach((e=>{this.contentFilters.set(e.id,e)})),O.info("[AdvancedSecurityManager] Content filtering initialized with filters:",Array.from(this.contentFilters.keys())))}addDefaultContentFilters(){var e,t,n;(null===(e=this.config.contentFilter)||void 0===e?void 0:e.enableProfanityFilter)&&this.contentFilters.set("profanity",{id:"profanity",name:"Profanity Filter",description:"Filters inappropriate language",type:"keyword",keywords:["damn","hell","crap","stupid","idiot"],severity:"medium",action:"warn"}),(null===(t=this.config.contentFilter)||void 0===t?void 0:t.enableSpamDetection)&&(this.contentFilters.set("spam",{id:"spam",name:"Spam Detection",description:"Detects spam content patterns including links",type:"regex",pattern:/(click here|buy now|limited time|act now|free money|make money fast|visit.*site|check.*out|earn.*\$|guaranteed.*income|work.*from.*home|lose.*weight.*fast)/gi,severity:"high",action:"block"}),this.contentFilters.set("link_spam",{id:"link_spam",name:"Link Spam Detection",description:"Detects spam patterns in links and URLs",type:"custom",severity:"medium",action:"warn",customHandler:(e,t)=>i(this,void 0,void 0,(function*(){return this.detectLinkSpam(e)}))})),(null===(n=this.config.contentFilter)||void 0===n?void 0:n.enableMalwareScanning)&&this.contentFilters.set("malware",{id:"malware",name:"Malware Scanner",description:"Scans for malicious content patterns",type:"regex",pattern:/(javascript:|data:text\/html|<script|eval\(|document\.write)/gi,severity:"critical",action:"block"})}initializeThreatDetection(){this.config.threatDetection&&(this.addDefaultThreatPatterns(),this.config.customThreatPatterns&&this.config.customThreatPatterns.forEach((e=>{this.threatPatterns.set(e.id,e)})),O.info("[AdvancedSecurityManager] Threat detection initialized with patterns:",Array.from(this.threatPatterns.keys())))}addDefaultThreatPatterns(){this.threatPatterns.set("sql_injection",{id:"sql_injection",name:"SQL Injection Detection",description:"Detects SQL injection attempts",type:"injection",severity:"high",responseAction:"block",indicators:[{type:"pattern",condition:/(union|select|insert|update|delete|drop|create|alter)\s/gi,weight:8},{type:"pattern",condition:/('|")\s*(or|and)\s*('|")/gi,weight:9}]}),this.threatPatterns.set("xss",{id:"xss",name:"Cross-Site Scripting Detection",description:"Detects XSS attempts",type:"injection",severity:"high",responseAction:"block",indicators:[{type:"pattern",condition:/<script[^>]*>|javascript:|on\w+\s*=/gi,weight:9},{type:"content",condition:e=>e.includes("alert(")||e.includes("prompt("),weight:7}]}),this.threatPatterns.set("data_exfiltration",{id:"data_exfiltration",name:"Data Exfiltration Detection",description:"Detects potential data exfiltration attempts",type:"exfiltration",severity:"critical",responseAction:"quarantine",indicators:[{type:"behavior",condition:e=>e.dataVolumePerMinute>1e6,weight:8},{type:"frequency",condition:e=>e.requestsPerMinute>100,weight:6,timeWindow:6e4}]})}initializePrivacyControls(){this.config.privacy&&(this.config.privacy.cookieConsent&&this.initializeConsentManagement(),this.config.privacy.dataSubjectRights&&this.initializeDataSubjectRights(),O.info("[AdvancedSecurityManager] Privacy controls initialized"))}initializeConsentManagement(){if("undefined"!=typeof localStorage){const e=localStorage.getItem("widgetic_privacy_consent");if(e)try{const t=JSON.parse(e);this.consentStatus.set("general",t.general||!1),this.consentStatus.set("analytics",t.analytics||!1),this.consentStatus.set("marketing",t.marketing||!1)}catch(e){O.warn("[AdvancedSecurityManager] Failed to parse existing consent:",e)}}}initializeDataSubjectRights(){O.info("[AdvancedSecurityManager] Data subject rights initialized")}validateContent(e,t){return i(this,arguments,void 0,(function*(e,t,i={}){var n;const s=[];let o=t;try{const r=this.baseSecurityManager.validateTextFieldUpdate(e,i.fieldId||"content",t,i);if(!r.allowed)return s.push({filterId:"basic_security",filterName:"Basic Security",severity:r.severity||"medium",reason:r.reason||"Basic security validation failed"}),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation",outcome:"blocked",details:{reason:r.reason,contentLength:t.length},classification:"internal",severity:"medium",userId:i.userId,sessionId:i.sessionId}),{allowed:!1,violations:s};if(r.sanitizedText&&(o=r.sanitizedText),this.config.threatDetection){const t=yield this.detectThreats(e,o,i);if(t.violations.length>0){if(s.push(...t.violations),!t.allowed)return{allowed:!1,violations:s};t.filteredContent&&(o=t.filteredContent)}}if(this.config.contentFilter){const n=yield this.applyContentFilters(o,i);if(n.violations.length>0){if(s.push(...n.violations),!n.allowed)return yield this.logAuditEvent({type:"content_filtered",widgetId:e,action:"content_blocked",outcome:"blocked",details:{violations:n.violations,originalLength:t.length},classification:"internal",severity:"medium",userId:i.userId,sessionId:i.sessionId}),{allowed:!1,violations:s};n.filteredContent&&(o=n.filteredContent)}}return 0===s.length&&(yield this.logAuditEvent({type:"data_accessed",widgetId:e,action:"content_validated",outcome:"success",details:{contentLength:t.length,filtered:o!==t},classification:(null===(n=this.config.secureData)||void 0===n?void 0:n.classification)||"internal",severity:"low",userId:i.userId,sessionId:i.sessionId})),{allowed:!0,filteredContent:o!==t?o:void 0,violations:s}}catch(t){return O.error("[AdvancedSecurityManager] Content validation error:",t),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation_error",outcome:"failure",details:{error:t instanceof Error?t.message:"Unknown error"},classification:"internal",severity:"high",userId:i.userId,sessionId:i.sessionId}),s.push({filterId:"system_error",filterName:"System Error",severity:"critical",reason:"Content validation system error"}),{allowed:!1,violations:s}}}))}applyContentFilters(e,t){return i(this,void 0,void 0,(function*(){const i=[];let n=e,s=!1;for(const[e,o]of this.contentFilters)try{const r=yield this.applyFilter(o,n,t);if(r.violations&&i.push(...r.violations),!r.allowed){if("block"===o.action){s=!0;break}"moderate"===o.action&&this.moderationQueue.set(`${Date.now()}-${e}`,{content:n,filter:o,context:t,timestamp:Date.now()})}r.filteredContent&&(n=r.filteredContent)}catch(t){O.error(`[AdvancedSecurityManager] Filter ${e} error:`,t),i.push({filterId:e,filterName:o.name,severity:"medium",reason:"Filter processing error"})}return{allowed:!s,filteredContent:n!==e?n:void 0,violations:i}}))}applyFilter(e,t,n){return i(this,void 0,void 0,(function*(){switch(e.type){case"regex":return this.applyRegexFilter(e,t);case"keyword":return this.applyKeywordFilter(e,t);case"custom":return e.customHandler?yield e.customHandler(t,n):{allowed:!0};default:return{allowed:!0}}}))}applyRegexFilter(e,t){if(!e.pattern)return{allowed:!0};const i="string"==typeof e.pattern?new RegExp(e.pattern,"gi"):e.pattern,n=t.match(i);if(n&&n.length>0){const s=n.map((t=>({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Pattern matched: ${t}`}))),o=t.replace(i,"[FILTERED]");return{allowed:"block"!==e.action,filtered:!0,filteredContent:o,violations:s,confidence:.9}}return{allowed:!0}}applyKeywordFilter(e,t){if(!e.keywords||0===e.keywords.length)return{allowed:!0};const i=t.toLowerCase(),n=[];let s=t;for(const t of e.keywords){const o=t.toLowerCase();if(i.includes(o)){n.push({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Keyword detected: ${t}`});const i=new RegExp(t,"gi");s=s.replace(i,"[FILTERED]")}}return n.length>0?{allowed:"block"!==e.action,filtered:!0,filteredContent:s,violations:n,confidence:.8}:{allowed:!0}}detectLinkSpam(e){return i(this,void 0,void 0,(function*(){const t=[];let i=0;try{const n=/<a[^>]*href\s*=\s*["']([^"']*)["'][^>]*>([^<]*)<\/a>/gi,s=[];let o;for(;null!==(o=n.exec(e));)s.push({url:o[1],text:o[2],match:o[0]});s.length>5&&(i+=3,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Excessive number of links detected: ${s.length}`}));for(const e of s){["bit.ly","tinyurl","t.co","goo.gl","ow.ly","tiny.cc"].some((t=>e.url.includes(t)))&&(i+=2,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`URL shortener detected: ${e.url}`}));["click here","read more","visit now","buy now","order now","download now","get started","try free","join now","sign up"].some((t=>e.text.toLowerCase().includes(t.toLowerCase())))&&(i+=1,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"low",reason:`Suspicious link text: "${e.text}"`}));[".tk",".ml",".ga",".cf",".buzz",".click"].some((t=>e.url.includes(t)))&&(i+=2,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Suspicious domain: ${e.url}`})),e.text.includes("http")&&!e.url.includes(e.text.replace(/^https?:\/\//,""))&&(i+=3,t.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"high",reason:`Mismatched link text and URL: "${e.text}" -> ${e.url}`}))}const r=i>=5,a=Math.min(i/10,1);return{allowed:!r,filtered:t.length>0,violations:t,confidence:a,requiresModeration:i>=3&&i<5}}catch(e){return O.error("[AdvancedSecurityManager] Link spam detection error:",e),{allowed:!0,violations:[{filterId:"link_spam",filterName:"Link Spam Detection",severity:"low",reason:"Link spam detection failed"}]}}}))}detectThreats(e,t,n){return i(this,void 0,void 0,(function*(){const i=[];let s=0,o=!1;for(const[r,a]of this.threatPatterns){let d=0;for(const e of a.indicators){d+=this.evaluateIndicator(e,t,n)}const c=Math.min(10,d);s+=c,c>=7&&(i.push({filterId:r,filterName:a.name,severity:a.severity,reason:a.description}),"block"!==a.responseAction&&"quarantine"!==a.responseAction||(o=!0),yield this.logAuditEvent({type:"threat_detected",widgetId:e,action:"threat_pattern_matched",outcome:o?"blocked":"suspicious",details:{patternId:r,patternName:a.name,threatScore:c,indicators:a.indicators.length},classification:"confidential",severity:a.severity,userId:n.userId,sessionId:n.sessionId}))}const r=`${e}:${n.userId||"anonymous"}`;return this.threatScores.set(r,(this.threatScores.get(r)||0)+s),{allowed:!o,violations:i}}))}evaluateIndicator(e,t,i){try{switch(e.type){case"pattern":if("string"==typeof e.condition||e.condition instanceof RegExp){return("string"==typeof e.condition?new RegExp(e.condition,"gi"):e.condition).test(t)?e.weight:0}break;case"content":if("function"==typeof e.condition)return e.condition(t)?e.weight:0;break;case"behavior":case"frequency":if("function"==typeof e.condition)return e.condition(i)?e.weight:0}return 0}catch(e){return O.warn("[AdvancedSecurityManager] Indicator evaluation error:",e),0}}logAuditEvent(e){return i(this,void 0,void 0,(function*(){if(!this.config.auditLogging)return;const t=Object.assign({id:this.generateEventId(),timestamp:(new Date).toISOString(),ipAddress:this.getClientIP(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"Unknown",classification:"internal",severity:"low",correlationId:this.generateCorrelationId(),details:{}},e),i=t.widgetId;this.auditBuffer.has(i)||this.auditBuffer.set(i,[]),this.auditBuffer.get(i).push(t),this.auditEvents.push(t),this.auditEvents.length>1e3&&this.auditEvents.splice(0,this.auditEvents.length-1e3);const n=this.getLogLevel(t.severity);O[n](`[SecurityAudit] ${t.type}:`,{id:t.id,widgetId:t.widgetId,action:t.action,outcome:t.outcome,severity:t.severity,userId:t.userId}),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-audit",{detail:t}))}))}getCSPNonce(){return this.cspNonce}updateCSPConfig(e){this.config.csp||(this.config.csp={level:"balanced",allowInlineStyles:!1,allowEval:!1,reportOnly:!1}),this.config.csp=Object.assign(Object.assign({},this.config.csp),e),this.setupCSPDirectives(),this.applyCSP(),this.logAuditEvent({type:"configuration_changed",widgetId:"system",action:"csp_config_updated",outcome:"success",details:{newConfig:e},classification:"internal",severity:"medium"})}recordConsent(e,t,i,n={}){if(this.consentStatus.set(t,i),"undefined"!=typeof localStorage){const e=JSON.parse(localStorage.getItem("widgetic_privacy_consent")||"{}");e[t]=i,e.timestamp=Date.now(),localStorage.setItem("widgetic_privacy_consent",JSON.stringify(e))}this.logAuditEvent({type:"privacy_consent",widgetId:e,action:"consent_"+(i?"granted":"revoked"),outcome:"success",details:{consentType:t,granted:i},classification:"confidential",severity:"medium",userId:n.userId,sessionId:n.sessionId}),O.info(`[AdvancedSecurityManager] Privacy consent ${i?"granted":"revoked"}:`,{consentType:t,widgetId:e,userId:n.userId})}hasConsent(e){return this.consentStatus.get(e)||!1}getSecurityStats(){const e=this.auditEvents.filter((e=>"threat_detected"===e.type)).length,t=this.auditEvents.filter((e=>"content_filtered"===e.type)).length,i=this.baseSecurityManager.getSecurityStats().blockedInstances;return{auditEvents:this.auditEvents.length,threatDetections:e,contentFiltered:t,blockedInstances:i}}exportAuditLogs(e,t){var i;let n=this.auditEvents;return e&&(n=n.filter((t=>t.widgetId===e))),t&&(n=n.filter((e=>e.classification===t))),(null===(i=this.config.privacy)||void 0===i?void 0:i.anonymizeUserData)?n.map((e=>Object.assign(Object.assign({},e),{userId:e.userId?"anonymized":void 0,ipAddress:e.ipAddress?"anonymized":void 0,userAgent:"anonymized"}))):n}generateEventId(){return`audit_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateCorrelationId(){return`corr_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getClientIP(){return"client_ip"}getLogLevel(e){switch(e){case"low":case"medium":default:return"info";case"high":return"warn";case"critical":return"error"}}}class Ti{constructor(e,t){this._active=!0,this.id=`sub_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.compositionId=e,this.handler=t}isActive(){return this._active}unsubscribe(){this._active=!1}}class ki{constructor(e){this.pollTimer=null,this.lastPoll=0,this.interval=e.interval,this.endpoint=e.endpoint,this.subscriptions=e.subscriptions,this.realtimeManager=e.realtimeManager}start(){return i(this,void 0,void 0,(function*(){this.pollTimer||(O.info("[PollingFallback] Starting polling fallback",{interval:this.interval,subscriptions:this.subscriptions.size}),this.pollTimer=setInterval((()=>{this.pollForUpdates()}),this.interval),yield this.pollForUpdates())}))}stop(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),O.info("[PollingFallback] Polling fallback stopped")}pollForUpdates(){return i(this,void 0,void 0,(function*(){if(0!==this.subscriptions.size)try{const e=yield fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.realtimeManager.getApiKey()},body:JSON.stringify({compositionIds:Array.from(this.subscriptions),since:this.lastPoll})});if(!e.ok)throw new Error(`Polling failed: ${e.status}`);const t=yield e.json();for(const e of t.updates||[])yield this.realtimeManager.handlePolledUpdate(e);this.lastPoll=Date.now()}catch(e){O.error("[PollingFallback] Polling error:",e)}}))}}class Ci{constructor(e){this.socket=null,this.connectionState="disconnected",this.connectionId=null,this.subscriptions=new Map,this.allSubscriptions=new Map,this.reconnectAttempts=0,this.reconnectTimer=null,this.messageQueue=new Map,this.retryTimer=null,this.heartbeatTimer=null,this.lastHeartbeat=0,this.heartbeatTimeout=null,this.pollingFallback=null,this.connectionStartTime=0,this.messageStats={sent:0,received:0,errors:0};const t={enabled:!0,wsUrl:"wss://realtime.widgetic.com",authentication:{type:"apikey",credentials:""},features:{contentUpdates:!0,styleUpdates:!0,configUpdates:!1,dataUpdates:!0},security:{validateUpdates:!0,rateLimitPerMinute:30,allowedUpdateTypes:["content","style","data"]},reconnection:{enabled:!0,maxAttempts:5,baseDelay:1e3,maxDelay:3e4},fallback:{enabled:!0,pollInterval:5e3},heartbeat:{enabled:!0,interval:3e4,timeout:1e4}};this.config=Object.assign(Object.assign(Object.assign({},t),e),{authentication:Object.assign(Object.assign({},t.authentication),e.authentication),features:Object.assign(Object.assign({},t.features),e.features),security:Object.assign(Object.assign({},t.security),e.security),reconnection:Object.assign(Object.assign({},t.reconnection),e.reconnection),fallback:Object.assign(Object.assign({},t.fallback),e.fallback),heartbeat:Object.assign(Object.assign({},t.heartbeat),e.heartbeat)}),this.securityManager=function(e){return Si.getInstance(e)}(),this.performanceMonitor=di(),this.setupEventListeners()}static getInstance(e){return Ci.instance||(Ci.instance=new Ci(e||{})),Ci.instance}initialize(){return i(this,void 0,void 0,(function*(){this.config.enabled?"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(O.info("[RealtimeManager] Initializing real-time connection"),yield this.connect()):O.info("[RealtimeManager] Real-time updates disabled")}))}connect(){return i(this,void 0,void 0,(function*(){if("connected"!==this.connectionState&&"connecting"!==this.connectionState){this.connectionState="connecting",this.connectionStartTime=Date.now();try{const e=this.buildWebSocketUrl();O.info("[RealtimeManager] Connecting to WebSocket:",e),this.socket=new WebSocket(e),this.socket.onopen=this.handleConnect.bind(this),this.socket.onmessage=this.handleMessage.bind(this),this.socket.onclose=this.handleDisconnect.bind(this),this.socket.onerror=this.handleError.bind(this)}catch(e){throw this.connectionState="error",O.error("[RealtimeManager] Connection failed:",e),yield this.handleConnectionError(e),e}}}))}subscribe(e,t){const i=new Ti(e,t);return this.subscriptions.has(e)||this.subscriptions.set(e,new Set),this.subscriptions.get(e).add(i),this.allSubscriptions.set(i.id,i),"connected"===this.connectionState?this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}):this.queueMessage(e,{type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}),O.info("[RealtimeManager] Subscribed to composition:",{compositionId:e,subscriptionId:i.id,totalSubscriptions:this.allSubscriptions.size}),i}unsubscribe(e){e.unsubscribe();const t=this.subscriptions.get(e.compositionId);t&&(t.delete(e),0===t.size&&this.subscriptions.delete(e.compositionId)),this.allSubscriptions.delete(e.id),"connected"===this.connectionState&&this.sendMessage({type:"unsubscribe",compositionId:e.compositionId,subscriptionId:e.id,timestamp:Date.now()}),O.info("[RealtimeManager] Unsubscribed from composition:",{compositionId:e.compositionId,subscriptionId:e.id,remainingSubscriptions:this.allSubscriptions.size})}getActiveSubscriptions(){return new Set(this.subscriptions.keys())}getApiKey(){return this.config.authentication.credentials}handlePolledUpdate(e){return i(this,void 0,void 0,(function*(){try{const t={type:e.type,compositionId:e.compositionId,data:e.data,userId:e.userId,timestamp:e.timestamp,version:e.version,partial:e.partial};yield this.processUpdate(t,{fromPolling:!0})}catch(e){O.error("[RealtimeManager] Failed to process polled update:",e)}}))}buildWebSocketUrl(){const e=this.config.wsUrl,t=new URLSearchParams;switch(this.config.authentication.type){case"apikey":t.append("apikey",this.config.authentication.credentials);break;case"jwt":t.append("token",this.config.authentication.credentials);break;case"session":t.append("session",this.config.authentication.credentials)}return t.append("client","embed-sdk"),t.append("version","1.0.0"),`${e}?${t.toString()}`}handleConnect(){var e;this.connectionState="connected",this.reconnectAttempts=0;const t=Date.now()-this.connectionStartTime;O.info("[RealtimeManager] Connected to real-time service",{connectionTime:t,subscriptions:this.subscriptions.size}),null===(e=this.performanceMonitor)||void 0===e||e.recordCustomMetric("realtime_connection_time",t),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.startHeartbeat(),this.processMessageQueue(),this.reestablishSubscriptions(),this.emitEvent("connected",{connectionTime:t})}handleMessage(e){return i(this,void 0,void 0,(function*(){this.messageStats.received++;try{const t=JSON.parse(e.data);switch(t.type){case"widget_update":yield this.handleWidgetUpdate(t);break;case"subscription_confirmed":this.handleSubscriptionConfirmed(t);break;case"heartbeat":this.handleHeartbeat(t);break;case"error":this.handleServerError(t);break;case"authentication":this.handleAuthentication(t);break;default:O.warn("[RealtimeManager] Unknown message type:",t.type)}}catch(e){this.messageStats.errors++,O.error("[RealtimeManager] Message parsing failed:",e)}}))}handleWidgetUpdate(e){return i(this,void 0,void 0,(function*(){const{compositionId:t,updateType:i,data:n,userId:s,timestamp:o,version:r,partial:a}=e;if(!this.config.features[`${i}Updates`])return void O.warn("[RealtimeManager] Update type disabled:",i);if(!this.config.security.allowedUpdateTypes.includes(i))return void O.warn("[RealtimeManager] Update type not allowed:",i);const d=this.subscriptions.get(t);if(!d||0===d.size)return void O.debug("[RealtimeManager] No subscriptions for composition:",t);const c={type:i,compositionId:t,data:n,userId:s,timestamp:o,version:r,partial:a};yield this.processUpdate(c,{fromWebSocket:!0})}))}processUpdate(e){return i(this,arguments,void 0,(function*(e,t={}){var i;try{if(this.config.security.validateUpdates){const t=yield this.securityManager.validateContent(e.compositionId,JSON.stringify(e.data),{userId:e.userId});if(!t.allowed)return O.warn("[RealtimeManager] Update blocked by security:",{compositionId:e.compositionId,violations:t.violations}),void this.emitEvent("security_violation",{compositionId:e.compositionId,violations:t.violations,update:e});if(t.filteredContent)try{e.data=JSON.parse(t.filteredContent)}catch(e){O.warn("[RealtimeManager] Failed to parse filtered content, using original")}}const n=this.subscriptions.get(e.compositionId);if(!n)return;const s=[];for(const t of n)t.isActive()&&s.push(t.handler(e).catch((i=>{O.error("[RealtimeManager] Handler execution failed:",{subscriptionId:t.id,compositionId:e.compositionId,error:i})})));yield Promise.allSettled(s),O.debug("[RealtimeManager] Update applied:",{compositionId:e.compositionId,type:e.type,handlerCount:s.length,source:t.fromWebSocket?"websocket":"polling"}),null===(i=this.performanceMonitor)||void 0===i||i.recordCustomMetric("realtime_updates_processed",1),this.emitEvent("update_applied",{compositionId:e.compositionId,type:e.type,handlerCount:s.length})}catch(t){O.error("[RealtimeManager] Update processing failed:",t),this.emitEvent("update_error",{compositionId:e.compositionId,error:t instanceof Error?t.message:"Unknown error",update:e})}}))}handleSubscriptionConfirmed(e){O.info("[RealtimeManager] Subscription confirmed:",{compositionId:e.compositionId,subscriptionId:e.subscriptionId})}handleHeartbeat(e){this.lastHeartbeat=Date.now(),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null),this.sendMessage({type:"heartbeat_response",timestamp:Date.now()})}handleServerError(e){O.error("[RealtimeManager] Server error:",e.data),this.emitEvent("server_error",{error:e.data})}handleAuthentication(e){var t,i,n;(null===(t=e.data)||void 0===t?void 0:t.success)?(this.connectionId=e.data.connectionId,O.info("[RealtimeManager] Authentication successful:",{connectionId:this.connectionId})):(O.error("[RealtimeManager] Authentication failed:",null===(i=e.data)||void 0===i?void 0:i.error),null===(n=this.socket)||void 0===n||n.close())}handleDisconnect(e){this.connectionState="disconnected",this.connectionId=null,O.warn("[RealtimeManager] Disconnected from real-time service:",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.stopHeartbeat(),this.config.reconnection.enabled&&!e.wasClean&&this.scheduleReconnection(),this.config.fallback.enabled&&this.subscriptions.size>0&&this.enablePollingFallback(),this.emitEvent("disconnected",{code:e.code,reason:e.reason,wasClean:e.wasClean})}handleError(e){var t;this.messageStats.errors++,O.error("[RealtimeManager] WebSocket error:",e),null===(t=this.performanceMonitor)||void 0===t||t.recordCustomMetric("realtime_errors",1),this.emitEvent("error",{event:e})}handleConnectionError(e){return i(this,void 0,void 0,(function*(){O.error("[RealtimeManager] Connection error:",e),this.config.reconnection.enabled?yield this.scheduleReconnection():this.config.fallback.enabled&&this.enablePollingFallback()}))}scheduleReconnection(){return i(this,void 0,void 0,(function*(){if(this.reconnectAttempts>=this.config.reconnection.maxAttempts)return O.error("[RealtimeManager] Max reconnection attempts reached"),this.config.fallback.enabled&&this.enablePollingFallback(),void this.emitEvent("max_reconnect_attempts",{attempts:this.reconnectAttempts});this.connectionState="reconnecting",this.reconnectAttempts++;const e=Math.min(this.config.reconnection.baseDelay*Math.pow(2,this.reconnectAttempts-1),this.config.reconnection.maxDelay);O.info("[RealtimeManager] Scheduling reconnection:",{attempt:this.reconnectAttempts,delay:e,maxAttempts:this.config.reconnection.maxAttempts}),this.reconnectTimer=setTimeout((()=>i(this,void 0,void 0,(function*(){try{yield this.connect()}catch(e){O.error("[RealtimeManager] Reconnection failed:",e),yield this.scheduleReconnection()}}))),e)}))}enablePollingFallback(){!this.pollingFallback&&this.config.fallback.enabled&&(O.info("[RealtimeManager] Enabling polling fallback"),this.pollingFallback=new ki({interval:this.config.fallback.pollInterval||5e3,endpoint:"/api/widgets/updates",subscriptions:this.getActiveSubscriptions(),realtimeManager:this}),this.pollingFallback.start(),this.emitEvent("fallback_enabled",{interval:this.config.fallback.pollInterval}))}sendMessage(e){if("connected"===this.connectionState&&this.socket)try{this.socket.send(JSON.stringify(e)),this.messageStats.sent++}catch(t){this.messageStats.errors++,O.error("[RealtimeManager] Failed to send message:",t),this.queueMessage(e.compositionId||"global",e)}else this.queueMessage(e.compositionId||"global",e)}queueMessage(e,t){this.messageQueue.has(e)||this.messageQueue.set(e,[]);this.messageQueue.get(e).push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now(),nextRetry:Date.now()+1e3}),this.retryTimer||(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processRetryQueue(){const e=Date.now();let t=!1;for(const[i,n]of this.messageQueue){const s=[];for(const i of n)e>=i.nextRetry?i.retryCount<i.maxRetries?(i.retryCount++,i.nextRetry=e+1e3*Math.pow(2,i.retryCount),this.sendMessage(i.message),i.retryCount<i.maxRetries&&s.push(i)):O.warn("[RealtimeManager] Message retry limit exceeded:",i.message):(s.push(i),t=!0);s.length>0?this.messageQueue.set(i,s):this.messageQueue.delete(i)}this.retryTimer=null,t&&(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processMessageQueue(){if("connected"===this.connectionState){O.info("[RealtimeManager] Processing queued messages:",{queueSize:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)});for(const[e,t]of this.messageQueue)for(const e of t)this.sendMessage(e.message);this.messageQueue.clear(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}}reestablishSubscriptions(){if(0!==this.subscriptions.size){O.info("[RealtimeManager] Re-establishing subscriptions:",{count:this.subscriptions.size});for(const[e,t]of this.subscriptions)for(const i of t)i.isActive()&&this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()})}}startHeartbeat(){this.config.heartbeat.enabled&&(this.stopHeartbeat(),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&(this.sendMessage({type:"heartbeat",timestamp:Date.now()}),this.heartbeatTimeout=setTimeout((()=>{var e;O.warn("[RealtimeManager] Heartbeat timeout"),null===(e=this.socket)||void 0===e||e.close()}),this.config.heartbeat.timeout))}).bind(this),2*this.config.heartbeat.interval),this.lastHeartbeat=Date.now())}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null)}setupEventListeners(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden?this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&this.sendMessage({type:"heartbeat",timestamp:Date.now()})}).bind(this),2*this.config.heartbeat.interval)):this.startHeartbeat()})),"undefined"!=typeof navigator&&"onLine"in navigator&&(window.addEventListener("online",(()=>{O.info("[RealtimeManager] Network back online"),"disconnected"===this.connectionState&&this.connect()})),window.addEventListener("offline",(()=>{O.warn("[RealtimeManager] Network offline"),this.pollingFallback&&this.pollingFallback.stop()})))}emitEvent(e,t){"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent(`widgetic:realtime:${e}`,{detail:Object.assign({manager:this,timestamp:Date.now()},t)}))}getConnectionState(){return this.connectionState}getStats(){return{connectionState:this.connectionState,subscriptions:this.allSubscriptions.size,messageStats:Object.assign({},this.messageStats),reconnectAttempts:this.reconnectAttempts,lastHeartbeat:this.lastHeartbeat,queuedMessages:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)}}disconnect(){O.info("[RealtimeManager] Disconnecting"),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.stopHeartbeat(),this.socket&&(this.socket.close(),this.socket=null),this.connectionState="disconnected",this.subscriptions.clear(),this.allSubscriptions.clear(),this.messageQueue.clear(),this.emitEvent("manual_disconnect",{})}}Ci.instance=null;class xi{constructor(e={}){var i,n,s,o;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionSubscriptions=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},e),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},e.security)}),this.apiConfig=new t.Configuration(Object.assign(Object.assign({basePath:this.config.apiBaseUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:3000")},this.config.apiKey&&{apiKey:this.config.apiKey}),this.config.accessToken&&{accessToken:this.config.accessToken})),this.widgetsApi=new t.WidgetsApi(this.apiConfig),this.compositionsApi=new t.CompositionsApi(this.apiConfig),this.securityManager=pi.getInstance(this.config.security||{}),this.displayManager=new Zt,this.performanceMonitor=di(),(null===(i=e.realtime)||void 0===i?void 0:i.enabled)&&(this.realtimeManager=function(e){return Ci.getInstance(e)}(e.realtime)),this.setupResponsiveTracking(),this.setupEventListeners(),O.info("[WidgetManager] Initialized with config:",{realtimeEnabled:!!(null===(n=e.realtime)||void 0===n?void 0:n.enabled),securityEnabled:!!(null===(s=e.security)||void 0===s?void 0:s.enableSanitization),performanceEnabled:!!(null===(o=e.performance)||void 0===o?void 0:o.enabled)})}static getInstance(e){return xi.instance||(xi.instance=new xi(e)),xi.instance}initialize(){return i(this,void 0,void 0,(function*(){if(this.isInitialized)O.warn("[WidgetManager] Already initialized");else try{this.realtimeManager&&(yield this.realtimeManager.initialize(),O.info("[WidgetManager] Real-time manager initialized")),this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),O.info("[WidgetManager] Successfully initialized")}catch(e){throw O.error("[WidgetManager] Initialization failed:",e),this.emitError({code:"INIT_FAILED",message:"Widget manager initialization failed",widgetId:"system",timestamp:Date.now(),details:{error:e instanceof Error?e.message:"Unknown error"}}),e}}))}registerWidget(e,t,n){return i(this,void 0,void 0,(function*(){try{const i=yield this.validateWidgetConfig(t);if(!i.allowed)throw new Error(`Widget validation failed: ${i.reason}`);const s={id:e,config:t,element:n,state:{ready:!1,error:null,width:t.width,height:t.height},displayState:{mode:t.displayMode,isFullscreen:!1,isOverlay:!1,isPopup:!1},updateHandlers:new Map,lastUpdate:Date.now()},o=this.displayManager.initializeWidget(e,t,n);if(s.displayState=o,t.triggers)try{const i=new Ii({widgetId:e,element:n,config:t.triggers});this.triggerManagers.set(e,i),O.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:e,triggers:t.triggers})}catch(t){O.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}return this.realtimeManager&&t.compositionId&&(yield this.setupRealtimeUpdates(s)),this.widgets.set(e,s),this.widgetConfigs.set(e,t),s.state.ready=!0,O.info("[WidgetManager] Widget registered:",{widgetId:e,compositionId:t.compositionId,realtimeEnabled:!!s.realtimeSubscription}),this.emitEvent({type:"widget_registered",widgetId:e,data:{config:t},timestamp:Date.now()}),s}catch(t){throw O.error("[WidgetManager] Widget registration failed:",t),this.emitError({code:"REGISTRATION_FAILED",message:"Widget registration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}}),t}}))}setupRealtimeUpdates(e){return i(this,void 0,void 0,(function*(){if(this.realtimeManager&&e.config.compositionId)try{const t=e.config.compositionId;if(this.compositionWidgets.has(t)||this.compositionWidgets.set(t,new Set),this.compositionWidgets.get(t).add(e.id),this.compositionSubscriptions.has(t))O.info("[WidgetManager] Using existing real-time subscription for composition:",{compositionId:t,widgetCount:this.compositionWidgets.get(t).size});else{const e=e=>i(this,void 0,void 0,(function*(){yield this.handleCompositionUpdate(t,e)})),n=this.realtimeManager.subscribe(t,e);this.compositionSubscriptions.set(t,n),O.info("[WidgetManager] Real-time subscription created for composition:",{compositionId:t,subscriptionId:n.id,widgetCount:this.compositionWidgets.get(t).size})}e.realtimeSubscription=this.compositionSubscriptions.get(t)}catch(e){throw O.error("[WidgetManager] Failed to setup real-time updates:",e),e}}))}handleCompositionUpdate(e,t){return i(this,void 0,void 0,(function*(){var i,n;try{O.debug("[WidgetManager] Processing composition update:",{compositionId:e,updateType:t.type,timestamp:t.timestamp,affectedWidgets:(null===(i=this.compositionWidgets.get(e))||void 0===i?void 0:i.size)||0});const s=this.compositionWidgets.get(e);if(!s||0===s.size)return void O.warn("[WidgetManager] No widgets found for composition:",e);const o=[];for(const e of s){const i=this.widgets.get(e);i&&o.push(this.handleWidgetUpdate(i,t))}if(yield Promise.allSettled(o),"content"===t.type||"data"===t.type){const i=this.compositionData.get(e),n={id:e,widgetId:e,content:"content"===t.type?t.data:(null==i?void 0:i.content)||{},theme:(null==i?void 0:i.theme)||{},version:t.version||"1.0.0"};"data"===t.type&&(null==i?void 0:i.content)&&(n.content=Object.assign(Object.assign({},i.content),t.data)),this.compositionData.set(e,n)}this.emitEvent({type:"composition_updated",widgetId:e,data:{compositionId:e,updateType:t.type,updateData:t.data,timestamp:t.timestamp,affectedWidgets:Array.from(s)},timestamp:Date.now()}),null===(n=this.performanceMonitor)||void 0===n||n.recordCustomMetric("composition_updates_applied",1)}catch(i){O.error("[WidgetManager] Composition update failed:",i),this.emitError({code:"COMPOSITION_UPDATE_FAILED",message:"Composition update processing failed",widgetId:e,timestamp:Date.now(),details:{compositionId:e,updateType:t.type,error:i instanceof Error?i.message:"Unknown error"}})}}))}handleWidgetUpdate(e,t){return i(this,void 0,void 0,(function*(){try{switch(e.lastUpdate=Date.now(),t.type){case"content":yield this.handleContentUpdate(e,t);break;case"style":yield this.handleStyleUpdate(e,t);break;case"config":yield this.handleConfigUpdate(e,t);break;case"data":yield this.handleDataUpdate(e,t);break;default:O.warn("[WidgetManager] Unknown update type:",t.type)}this.emitEvent({type:"widget_updated",widgetId:e.id,data:{compositionId:e.config.compositionId,updateType:t.type,updateData:t.data,timestamp:t.timestamp},timestamp:Date.now()})}catch(i){O.error("[WidgetManager] Widget update failed:",i),this.emitError({code:"WIDGET_UPDATE_FAILED",message:"Widget update processing failed",widgetId:e.id,timestamp:Date.now(),details:{compositionId:e.config.compositionId,updateType:t.type,error:i instanceof Error?i.message:"Unknown error"}})}}))}handleContentUpdate(e,t){return i(this,void 0,void 0,(function*(){var i;if(e.config.compositionId){const i=this.compositionData.get(e.config.compositionId),n={id:e.config.compositionId,widgetId:e.config.compositionId,content:t.data,theme:(null==i?void 0:i.theme)||{},version:t.version||(null==i?void 0:i.version)||"1.0.0"};this.compositionData.set(e.config.compositionId,n)}yield this.applyContentToWidget(e,t.data);const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("content");n&&(yield n(t.data))}))}handleStyleUpdate(e,t){return i(this,void 0,void 0,(function*(){var i;yield this.applyStylesToWidget(e,t.data);const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("style");n&&(yield n(t.data))}))}handleConfigUpdate(e,t){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},e.config),t.data),s=yield this.validateWidgetConfig(n);if(!s.allowed)throw new Error(`Config update validation failed: ${s.reason}`);if(e.config=n,this.widgetConfigs.set(e.id,n),t.data.displayMode||t.data.resize||t.data.width||t.data.height)try{this.displayManager.cleanup(e.id);const t=this.displayManager.initializeWidget(e.id,n,e.element);e.displayState=t,O.debug("[WidgetManager] Display management updated:",{widgetId:e.id,displayMode:n.displayMode})}catch(t){O.warn("[WidgetManager] Failed to update display management:",{widgetId:e.id,error:t instanceof Error?t.message:"Unknown error"})}const o=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("config");o&&(yield o(t.data))}))}handleDataUpdate(e,t){return i(this,void 0,void 0,(function*(){var i;const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("data");n?yield n(t.data):yield this.applyContentToWidget(e,t.data)}))}applyContentToWidget(e,t){return i(this,void 0,void 0,(function*(){try{if("string"==typeof t)if("iframe"===e.element.tagName.toLowerCase()){const i=e.element;i.contentWindow&&i.contentWindow.postMessage({type:"widgetic_content_update",content:t},j.CLIENT_URL||"*")}else{const i=yield this.sanitizeContent(t,e.id);e.element.innerHTML=i}else if("object"==typeof t)if("iframe"===e.element.tagName.toLowerCase()){const i=e.element;i.contentWindow&&i.contentWindow.postMessage({type:"widgetic_data_update",data:t},j.CLIENT_URL||"*")}else e.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:t}));O.debug("[WidgetManager] Content applied to widget:",{widgetId:e.id,contentType:typeof t})}catch(e){throw O.error("[WidgetManager] Failed to apply content:",e),e}}))}applyStylesToWidget(e,t){return i(this,void 0,void 0,(function*(){try{"object"==typeof t?Object.entries(t).forEach((([t,i])=>{"string"!=typeof i&&"number"!=typeof i||(e.element.style[t]=i)})):"string"==typeof t&&(e.element.style.cssText+=t),O.debug("[WidgetManager] Styles applied to widget:",{widgetId:e.id,stylesType:typeof t})}catch(e){throw O.error("[WidgetManager] Failed to apply styles:",e),e}}))}sanitizeContent(e,t){return i(this,void 0,void 0,(function*(){const i=this.securityManager.validateTextFieldUpdate(t,"content",e);if(!i.allowed)throw new Error(`Content blocked by security: ${i.reason}`);return i.sanitizedText||e}))}validateWidgetConfig(e){return i(this,void 0,void 0,(function*(){var t;if(!e.compositionId)return{allowed:!1,reason:"Missing composition ID",severity:"high"};if(null===(t=this.config.security)||void 0===t?void 0:t.enableSanitization){const t=JSON.stringify(e),i=this.securityManager.validateTextFieldUpdate(e.compositionId,"config",t);if(!i.allowed)return{allowed:!1,reason:i.reason,severity:i.severity||"medium"}}return{allowed:!0}}))}setContent(e,t){return i(this,arguments,void 0,(function*(e,t,n={}){var s;try{O.debug("[WidgetManager] Setting dynamic content:",{compositionId:e,contentType:typeof t,options:n});const o={content:t};void 0!==n.validate&&(o.validate=n.validate),void 0!==n.partial&&(o.partial=n.partial),void 0!==n.version&&(o.version=n.version),void 0!==n.source&&(o.source=n.source);const r=yield this.compositionsApi.setDynamicContent({id:e,setDynamicContentRequest:Ut(o)}),a=this.getWidgetsByComposition(e),d=this.compositionData.get(e);let c=t;n.partial&&(null==d?void 0:d.content)&&(c=this.mergeContent(d.content,t));const l={id:e,widgetId:e,content:c,theme:(null==d?void 0:d.theme)||{},version:n.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(e,l);const u=a.map((t=>i(this,void 0,void 0,(function*(){var i;try{yield this.applyContentToWidget(t,c);const s=null===(i=t.updateHandlers)||void 0===i?void 0:i.get("content");s&&(yield s(c)),t.lastUpdate=Date.now(),O.debug("[WidgetManager] Content applied to widget:",{widgetId:t.id,compositionId:e,source:n.source})}catch(e){throw O.error("[WidgetManager] Failed to update widget content:",{widgetId:t.id,error:e instanceof Error?e.message:"Unknown error"}),e}}))));return yield Promise.all(u),this.emitEvent({type:"content_updated",widgetId:e,data:{content:c,source:n.source,version:n.version,partial:n.partial},timestamp:Date.now()}),O.info("[WidgetManager] Content updated successfully via API:",{compositionId:e,widgetCount:a.length,source:n.source,realtimeUpdateSent:r.realtimeUpdateSent}),{success:null!==(s=r.success)&&void 0!==s&&s,validationResult:r.validationResult}}catch(t){const i=t instanceof Error?t.message:"Unknown error";return this.emitError({code:"CONTENT_UPDATE_FAILED",message:`Failed to set content: ${i}`,widgetId:e,timestamp:Date.now(),details:{error:i,options:n}}),{success:!1,error:i}}}))}getContentSchema(e){return i(this,void 0,void 0,(function*(){try{O.debug("[WidgetManager] Getting widget content schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetContentSchema({id:e});return O.debug("[WidgetManager] Content schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw O.error("[WidgetManager] Failed to get content schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get content schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}getDesignSchema(e){return i(this,void 0,void 0,(function*(){try{O.debug("[WidgetManager] Getting widget design schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetDesignSchema({id:e});return O.debug("[WidgetManager] Design schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw O.error("[WidgetManager] Failed to get design schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get design schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}validateContent(e,t){return i(this,void 0,void 0,(function*(){var i,n;try{O.debug("[WidgetManager] Validating content:",{compositionId:e});const s=yield this.compositionsApi.validateCompositionContent({id:e,body:Ut(t)});return O.debug("[WidgetManager] Content validation completed:",{compositionId:e,valid:null!==(i=s.valid)&&void 0!==i&&i}),{valid:null!==(n=s.valid)&&void 0!==n&&n,errors:s.errors,warnings:s.warnings,sanitizedContent:s.sanitizedContent}}catch(e){throw O.error("[WidgetManager] Content validation failed:",e),e}}))}getContent(e){const t=this.compositionData.get(e);return(null==t?void 0:t.content)||null}mergeContent(e,t){if(!e||"object"!=typeof e)return t;if(!t||"object"!=typeof t)return e;const i=Object.assign({},e);for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&!Array.isArray(n)?i[e]=this.mergeContent(i[e],n):i[e]=n;return i}registerUpdateHandler(e,t,i){const n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);n.updateHandlers||(n.updateHandlers=new Map),n.updateHandlers.set(t,i),O.info("[WidgetManager] Update handler registered:",{widgetId:e,updateType:t})}unregisterWidget(e){return i(this,void 0,void 0,(function*(){var t,i;const n=this.widgets.get(e);if(n)try{const s=n.config.compositionId;if(s&&this.compositionWidgets.has(s)&&(this.compositionWidgets.get(s).delete(e),0===this.compositionWidgets.get(s).size)){const e=this.compositionSubscriptions.get(s);e&&(null===(t=this.realtimeManager)||void 0===t||t.unsubscribe(e),this.compositionSubscriptions.delete(s),this.compositionWidgets.delete(s),O.info("[WidgetManager] Cleaned up composition subscription:",{compositionId:s,subscriptionId:e.id}))}try{this.displayManager.cleanup(e),O.debug("[WidgetManager] Display management cleaned up:",{widgetId:e})}catch(t){O.warn("[WidgetManager] Failed to cleanup display management:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}const o=this.triggerManagers.get(e);if(o)try{o.destroy(),this.triggerManagers.delete(e),O.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:e})}catch(t){O.warn("[WidgetManager] Failed to cleanup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.widgets.delete(e),this.widgetConfigs.delete(e),O.info("[WidgetManager] Widget unregistered:",{widgetId:e,compositionId:s,remainingWidgetsForComposition:(null===(i=this.compositionWidgets.get(s||""))||void 0===i?void 0:i.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:e,data:{compositionId:s},timestamp:Date.now()})}catch(t){O.error("[WidgetManager] Widget unregistration failed:",t),this.emitError({code:"UNREGISTRATION_FAILED",message:"Widget unregistration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}})}else O.warn("[WidgetManager] Widget not found for unregistration:",e)}))}getWidget(e){return this.widgets.get(e)}getAllWidgets(){return Array.from(this.widgets.values())}getWidgetsByComposition(e){const t=this.compositionWidgets.get(e);return t?Array.from(t).map((e=>this.widgets.get(e))).filter((e=>void 0!==e)):[]}setupResponsiveTracking(){if("undefined"==typeof window)return;const e=()=>{const e={mode:"mobile"===Be().getDeviceType()?"mobile":"desktop",breakpoint:768,width:window.innerWidth,timestamp:Date.now()};this.responsiveState&&this.responsiveState.mode===e.mode||(this.responsiveState=e,this.emitEvent({type:"responsive_change",widgetId:"system",data:e,timestamp:Date.now()}),this.handleResponsiveChange(e))};let t;e(),window.addEventListener("resize",(()=>{clearTimeout(t),t=setTimeout(e,250)}))}handleResponsiveChange(e){for(const t of this.widgets.values())try{const i=this.widgetConfigs.get(t.id);if(i&&t.displayState){this.displayManager.cleanup(t.id);const n=this.displayManager.initializeWidget(t.id,i,t.element);t.displayState=n,O.debug("[WidgetManager] Responsive update applied:",{widgetId:t.id,mode:e.mode,width:e.width})}this.emitEvent({type:"widget_responsive_change",widgetId:t.id,data:e,timestamp:Date.now()})}catch(e){O.error("[WidgetManager] Responsive change handling failed for widget:",{widgetId:t.id,error:e})}}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}addErrorHandler(e){this.errorHandlers.add(e)}removeErrorHandler(e){this.errorHandlers.delete(e)}emitEvent(e){const t=this.eventListeners.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){O.error("[WidgetManager] Event handler failed:",e)}}))}emitError(e){this.errorHandlers.forEach((t=>{try{t(e)}catch(e){O.error("[WidgetManager] Error handler failed:",e)}}))}setupEventListeners(){"undefined"!=typeof window&&(this.realtimeManager&&(document.addEventListener("widgetic:realtime:connected",(()=>{this.emitEvent({type:"realtime_connected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:disconnected",(()=>{this.emitEvent({type:"realtime_disconnected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:error",(e=>{this.emitError({code:"REALTIME_ERROR",message:"Real-time connection error",widgetId:"system",timestamp:Date.now(),details:e.detail})}))),document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})})))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,compositionSubscriptions:this.compositionSubscriptions.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return i(this,void 0,void 0,(function*(){O.info("[WidgetManager] Destroying widget manager");const e=Array.from(this.widgets.keys());yield Promise.allSettled(e.map((e=>this.unregisterWidget(e))));for(const[e,t]of this.triggerManagers)try{t.destroy(),O.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:e})}catch(t){O.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),O.debug("[WidgetManager] Display manager cleaned up")}catch(e){O.warn("[WidgetManager] Failed to cleanup display manager:",{error:e instanceof Error?e.message:"Unknown error"})}this.realtimeManager&&this.realtimeManager.disconnect(),this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionSubscriptions.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,xi.instance=null,O.info("[WidgetManager] Widget manager destroyed")}))}getActiveCompositions(){return Array.from(this.compositionWidgets.keys()).filter((e=>this.compositionWidgets.get(e).size>0))}getCompositionData(e){return this.compositionData.get(e)}}function Ai(e){return xi.getInstance(e)}xi.instance=null;var Mi=Object.freeze({__proto__:null,WidgetManager:xi,getWidgetManager:Ai});let Li=!1;class Di{constructor(e={}){var t,i,n,s,o,r,a,d,c,l,u,h,g,p,m,v,f,y,b,w,I,E;this.version=$,this.instances=new Map,this.isInitialized=!1,this.renderer=Ft(),this.widgetControllers=new Map,this.authDetector=Bt(),this.editorOverlay=Xt(),this.displayManager=(ei||(ei=new Zt(E)),ei),this.resizeHandler=function(e){return Dt||(Dt=new Lt(e)),Dt}(),this.authenticationStatus=null,this.overlayManager=null,this.hostObserverStarted=!1,this.config=Object.assign({renderMode:"auto",performance:{enabled:!1,config:{}},lazyLoading:{enabled:!0,config:{}}},e),this.browserCapabilities=it(),this.messenger=Mt(this.config.messagingOptions);const S=this.config.logLevel||(this.config.debug?"debug":"info");if(O.setLevel(S),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(t=this.config.performance)||void 0===t?void 0:t.enabled)){!function(e={}){ai=new ri(e)}(Object.assign({enableTracking:te.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:te.AXIOM_API_KEY,axiomDataset:te.AXIOM_DATASET,axiomApiEndpoint:te.AXIOM_API_ENDPOINT,statsigKey:te.STATSIG_API_KEY,statsigApiEndpoint:te.STATSIG_API_ENDPOINT},null===(i=this.config.performance)||void 0===i?void 0:i.config))}!1!==(null===(n=this.config.lazyLoading)||void 0===n?void 0:n.enabled)&&function(e={}){li=new ci(e)}((null===(s=this.config.lazyLoading)||void 0===s?void 0:s.config)||{}),void 0!==this.config.debug&&(D.setDebug(this.config.debug),this.config.debug&&D.setLevel("debug")),!1!==(null===(o=this.config.resourceOptimization)||void 0===o?void 0:o.enabled)&&function(e={}){hi=new ui(e)}((null===(r=this.config.resourceOptimization)||void 0===r?void 0:r.config)||{}),this.config.editorOptions&&(this.editorOverlay=Xt(this.config.editorOptions)),!1!==(null===(a=this.config.overlayConfig)||void 0===a?void 0:a.enabled)&&(this.overlayManager=function(e){return oi||(oi=new si(e)),oi}({enabled:!0,defaultMode:null===(d=this.config.overlayConfig)||void 0===d?void 0:d.defaultMode,exitIntentEnabled:null===(c=this.config.overlayConfig)||void 0===c?void 0:c.exitIntentEnabled,scrollTriggerEnabled:null===(l=this.config.overlayConfig)||void 0===l?void 0:l.scrollTriggerEnabled,timeTriggerEnabled:null===(u=this.config.overlayConfig)||void 0===u?void 0:u.timeTriggerEnabled,engagementThresholdEnabled:null===(h=this.config.overlayConfig)||void 0===h?void 0:h.engagementThresholdEnabled,externalTriggerEnabled:null===(g=this.config.overlayConfig)||void 0===g?void 0:g.externalTriggerEnabled,breakpoints:{useBreakpoints:(null===(m=null===(p=this.config.overlayConfig)||void 0===p?void 0:p.breakpoints)||void 0===m?void 0:m.useBreakpoints)||!1,mobile:(null===(f=null===(v=this.config.overlayConfig)||void 0===v?void 0:v.breakpoints)||void 0===f?void 0:f.mobile)||480,tablet:(null===(b=null===(y=this.config.overlayConfig)||void 0===y?void 0:y.breakpoints)||void 0===b?void 0:b.tablet)||768,desktop:(null===(I=null===(w=this.config.overlayConfig)||void 0===w?void 0:w.breakpoints)||void 0===I?void 0:I.desktop)||1024}})),O.info("Widgetic Embed SDK v1.0 initialized",{version:$,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&O.info("EmbedSDK initialized in debug mode",{config:this.config})}init(){return i(this,void 0,void 0,(function*(){var e,t;if(this.watchPublishedHosts(),yield this.scanPage(),this.isInitialized)O.warn("SDK already initialized");else if(Li||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)O.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,Li=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((e=>{O.warn("Background authentication check failed",{error:e})})),this.config.preloadUISDK&&(null===(e=this.authenticationStatus)||void 0===e?void 0:e.isAuthenticated))try{const e=Yt();yield e.preload(),O.info("UI SDK preloaded successfully")}catch(e){O.warn("Failed to preload UI SDK",{error:e})}yield this.scanPage(),O.info("Widgetic Embed SDK initialized successfully",{version:$,capabilities:this.browserCapabilities,authenticationStatus:null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated}),yield this.scanPage()}catch(e){throw O.error("SDK initialization failed",{error:e}),e}}))}checkAuthentication(){return i(this,void 0,void 0,(function*(){var e;try{this.authenticationStatus=yield this.authDetector.checkAuthentication(),this.authenticationStatus.isAuthenticated?O.info("User authenticated for editing",{userId:null===(e=this.authenticationStatus.user)||void 0===e?void 0:e.id}):O.debug("User not authenticated for editing")}catch(e){O.debug("Authentication check failed",{error:e}),this.authenticationStatus={isAuthenticated:!1,canEdit:!1}}}))}enhance(){return i(this,void 0,void 0,(function*(){yield this.scanPage()}))}refresh(){return i(this,void 0,void 0,(function*(){O.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){tt(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{tt()})).observe(document.documentElement,{childList:!0,subtree:!0}))}scanPage(){return i(this,void 0,void 0,(function*(){var e,t,i,n;const s=document.querySelectorAll("widgetic");if(O.debug("Found widgetic host elements",{count:s.length}),0===s.length)return void O.info("No widgets found on page");const o=[];for(const r of Array.from(s))if(ke(r)&&r instanceof HTMLElement){if(et(r))continue;try{const s=se(r),a=null===(t=null===(e=s.device)||void 0===e?void 0:e.mobileEnabled)||void 0===t||t;if(!Ve(a,null===(n=null===(i=s.device)||void 0===i?void 0:i.desktopEnabled)||void 0===n||n)){O.debug("Widget skipped due to device restrictions",{compositionId:s.compositionId,deviceRestrictions:s.device,element:r.outerHTML.substring(0,100)+"..."}),r.style.display="none",r.setAttribute("data-device-restricted","true");continue}o.push({element:r,config:s})}catch(e){O.error("Failed to parse widget configuration",{element:r.outerHTML,error:e})}}0!==o.length?yield this.renderWidgetsBatch(o):O.warn("No valid widget configurations found")}))}renderWidgetsBatch(e){return i(this,void 0,void 0,(function*(){try{const t=[],i=e.map((({element:e,config:i})=>{let n=e;if(e.parentNode){const t=document.createElement("div");t.className=`widgetic-host ${e.className}`.trim(),e.getAttribute("style")&&(t.style.cssText=e.getAttribute("style")||""),e.parentNode.replaceChild(t,e),n=t}return t.push(n),{compositionId:i.compositionId,renderMode:rt(i.renderMode,this.browserCapabilities),width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:n}})),n=yield this.renderer.renderWidgets(i);for(let i=0;i<n.length;i++){const s=n[i],{config:o}=e[i],r=t[i],a=Te(o.compositionId),d=this.displayManager.initializeWidget(a,o,s.element);s.element instanceof HTMLElement&&r instanceof HTMLElement&&this.resizeHandler.registerWidget(a,s.element,r.parentElement||r,o);const c={id:a,config:o,element:s.element,displayState:d,state:{ready:!0,error:null,width:"number"==typeof o.width?o.width:parseInt(String(o.width)),height:"number"==typeof o.height?o.height:parseInt(String(o.height))},enterFullscreen:()=>this.displayManager.enterFullscreen(a),exitFullscreen:()=>this.displayManager.exitFullscreen(a),showOverlay:()=>this.displayManager.showOverlay(a),hideOverlay:()=>this.displayManager.hideOverlay(a),openPopup:()=>this.displayManager.openPopup(a),closePopup:()=>this.displayManager.closePopup(a)};this.instances.set(c.id,c),yield this.maybeAddEditorOverlay(s.element,o.compositionId),O.debug("Widget rendered successfully",{instanceId:c.id,compositionId:o.compositionId,renderMode:s.renderMode,displayMode:o.displayMode})}O.info("Batch widget rendering complete",{rendered:n.length,total:e.length})}catch(t){O.error("Batch widget rendering failed",{error:t});for(const{element:t,config:i}of e)try{yield this.renderSingleWidget(t,i)}catch(e){O.error("Individual widget rendering failed",{compositionId:i.compositionId,error:e})}}}))}renderSingleWidget(e,t){return i(this,void 0,void 0,(function*(){try{performance.now(),di(),gi();const n=function(e){return li||(li=new ci(e)),li}();if(this.shouldUseLazyLoading(e,t))return void n.register(e,t.compositionId,(()=>i(this,void 0,void 0,(function*(){yield this.performActualWidgetRender(e,t)}))),{config:t,priority:this.getWidgetPriority(t),resourceUrls:this.getWidgetResourceUrls(t)});yield this.performActualWidgetRender(e,t)}catch(e){const i=di(),n=e instanceof Error?e.message:"Render failed";throw i.recordWidgetError(t.compositionId,n),i.endWidgetLoad(t.compositionId,!1),O.error("Widget rendering failed",{error:e,config:t}),e}}))}performActualWidgetRender(e,t){return i(this,void 0,void 0,(function*(){const i=performance.now(),n=di(),s=gi();try{const o=this.getWidgetResourceUrls(t);if(o.length>0&&(yield s.loadResources(o,{type:"script",priority:"high",compositionId:t.compositionId})),!("render"in this.renderer)||"function"!=typeof this.renderer.render)throw new Error("Widget renderer does not support render method");{const{widgetElement:s,instance:o}=yield this.renderer.render(e,t);if(!s)throw new Error("Widget element not created");const r=performance.now()-i;n.recordWidgetRender(t.compositionId,r),n.endWidgetLoad(t.compositionId,!0),this.instances.set(o.id,o)}}catch(e){const i=di(),n=e instanceof Error?e.message:"Render failed";throw i.recordWidgetError(t.compositionId,n),i.endWidgetLoad(t.compositionId,!1),O.error("Widget rendering failed",{error:e,config:t}),e}}))}shouldUseLazyLoading(e,t){var i;if(!1===(null===(i=this.config.lazyLoading)||void 0===i?void 0:i.enabled))return!1;if("critical"===t.priority||!0===t.preload)return!1;const n=e.getBoundingClientRect();return!(n.top<window.innerHeight&&n.bottom>0)}getWidgetPriority(e){switch(e.priority){case"critical":return 10;case"high":return 7;case"medium":default:return 5;case"low":return 2}}getWidgetResourceUrls(e){const t=[];return e.scriptUrl&&t.push(e.scriptUrl),e.styleUrl&&t.push(e.styleUrl),e.resourceUrls&&Array.isArray(e.resourceUrls)&&t.push(...e.resourceUrls),t}maybeAddEditorOverlay(e,t){return i(this,void 0,void 0,(function*(){if(!1!==this.config.enableEditing)try{yield this.editorOverlay.addOverlay(e,t)}catch(e){O.debug("Failed to add editor overlay",{compositionId:t,error:e})}}))}getInstances(){return Array.from(this.instances.values())}getInstance(e){return this.instances.get(e)||null}getInstancesByComposition(e){return this.getInstances().filter((t=>t.config.compositionId===e))}getStats(){const e=this.renderer.getStats();return{version:$,widgetsRendered:this.instances.size,renderMode:"auto",cacheStats:e.batchCache,messagingActive:this.messenger.isActive(),customEventSubscriptions:this.messenger.getCustomEventSubscriptions(),functionHandlers:this.messenger.getFunctionHandlers(),authenticationStatus:this.authenticationStatus||void 0,editingSessions:this.editorOverlay.getActiveSessions().length}}createWidgetController(e){const t=Array.from(this.instances.values()).find((t=>t.config.compositionId===e));if(!t)return O.warn("Widget instance not found for controller creation",{compositionId:e}),null;const i=this.messenger.createWidgetController(t.id,e);return this.widgetControllers.set(e,i),O.info("Widget controller created",{compositionId:e,instanceId:t.id}),i}getWidgetController(e){return this.widgetControllers.get(e)||null}subscribeToWidget(e,t,i){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.subscribe(t,i)}callWidgetFunction(e,t,...n){return i(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.callFunction(t,...n)}))}updateWidgetConfig(e,t){return i(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.updateConfig(t)}))}getWidgetState(e,t){return i(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.getState(t)}))}setWidgetState(e,t,n){return i(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.setState(t,n)}))}emitToWidget(e,t,i,n){let s=this.getWidgetController(e);s||(s=this.createWidgetController(e),s)?s.emit(t,i,n):O.warn(`Cannot create controller for widget: ${e}`)}canEditComposition(e){return i(this,void 0,void 0,(function*(){return this.authDetector.canEditComposition(e)}))}getAuthenticationStatus(){return this.authenticationStatus}refreshAuthentication(){return i(this,void 0,void 0,(function*(){return yield this.checkAuthentication(),this.authenticationStatus}))}openEditor(e){return i(this,void 0,void 0,(function*(){if(!(yield this.canEditComposition(e)))throw new Error(`User cannot edit composition: ${e}`);yield this.editorOverlay.openEditor(e)}))}isEditorOpen(e){return this.editorOverlay.isEditorOpen(e)}closeEditor(e){return i(this,void 0,void 0,(function*(){yield this.editorOverlay.closeEditor(e)}))}setEditingEnabled(e){this.config.enableEditing=e,O.info("Editing mode changed",{enabled:e})}setContent(e,t){return i(this,arguments,void 0,(function*(e,t,i={}){try{const{getWidgetManager:n}=yield Promise.resolve().then((function(){return Mi})),s=n();return yield s.setContent(e,t,i)}catch(e){return O.error("[EmbedSDK] Failed to set content:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}))}getContentSchema(e){return i(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Mi})),n=i();return yield n.getContentSchema(t.config.compositionId)}catch(e){throw O.error("[EmbedSDK] Failed to get content schema:",e),e}}))}getDesignSchema(e){return i(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Mi})),n=i();return yield n.getDesignSchema(t.config.compositionId)}catch(e){throw O.error("[EmbedSDK] Failed to get design schema:",e),e}}))}validateContent(e,t){return i(this,void 0,void 0,(function*(){try{const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Mi})),n=i();return yield n.validateContent(e,t)}catch(e){throw O.error("[EmbedSDK] Failed to validate content:",e),e}}))}getContent(e){try{return Ai().getContent(e)}catch(e){return O.error("[EmbedSDK] Failed to get content:",e),null}}onContentUpdate(e,t){return this.subscribeToWidget(e,"content_updated",t)}scan(){return i(this,void 0,void 0,(function*(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{const e=document.querySelectorAll("[data-widgetic]"),t=Array.from(e).map((e=>{const t=e.getAttribute("data-widgetic"),i=e.getAttribute("data-id");return t&&i?{id:t,dataId:i,element:e}:null})).filter(Boolean);return yield this.loadWidgets(t),{success:!0,widgets:t,errors:[]}}catch(e){return{success:!1,widgets:[],errors:[e instanceof Error?e.message:"Unknown error"]}}}))}loadWidgets(e){return i(this,void 0,void 0,(function*(){for(const t of e)try{yield this.loadWidget(t)}catch(e){}}))}loadWidget(e){return i(this,void 0,void 0,(function*(){yield new Promise((e=>setTimeout(e,100*Math.random())));const t=this.determineRenderMode();"iframe"===t?this.renderIframe(e):"custom-element"===t&&this.renderCustomElement(e)}))}determineRenderMode(){return"iframe"===this.config.renderMode?"iframe":"custom-element"===this.config.renderMode||"undefined"!=typeof customElements?"custom-element":"iframe"}renderIframe(e){const t=document.createElement("iframe");t.src=`https://widgetic.com/widget/${e.dataId}`,t.style.width=e.element.style.width||"400px",t.style.height=e.element.style.height||"300px",t.style.border="none",e.element.appendChild(t)}renderCustomElement(e){if("undefined"!=typeof customElements){customElements.get("widgetic-widget")||customElements.define("widgetic-widget",class extends HTMLElement{connectedCallback(){this.innerHTML=`<div>Widgetic Widget: ${this.getAttribute("data-widget-id")}</div>`}});const t=document.createElement("widgetic-widget");t.setAttribute("data-widget-id",e.dataId),e.element.appendChild(t)}}getConfig(){return Object.assign({},this.config)}showOverlay(e){this.overlayManager?this.overlayManager.showOverlay(e):O.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():O.warn("Overlay manager not initialized")}triggerOverlay(e,t={}){this.overlayManager?this.overlayManager.triggerOverlay(e,t):O.warn("Overlay manager not initialized")}isOverlayActive(){var e;return(null===(e=this.overlayManager)||void 0===e?void 0:e.isOverlayActive())||!1}destroy(){document.querySelectorAll("iframe").forEach((e=>e.remove()));document.querySelectorAll("widgetic-widget").forEach((e=>e.remove())),this.overlayManager&&(this.overlayManager.destroy(),this.overlayManager=null),this.isInitialized=!1}}let Oi=null;function Wi(e){return Oi||(Oi=new Di(e)),Oi}"undefined"!=typeof document&&(tt(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{tt()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{Wi().init().catch((e=>{O.error("Auto-initialization failed",{error:e})}))})):setTimeout((()=>{Wi().init().catch((e=>{O.error("Auto-initialization failed",{error:e})}))}),0));class Ri{constructor(){this.debugMode=!1,this.trackedElements=new WeakSet}static getInstance(){return Ri.instance||(Ri.instance=new Ri),Ri.instance}enableDebugMode(){this.debugMode=!0,this.addDebugStyles(),O.info("CSS debugging mode enabled")}disableDebugMode(){this.debugMode=!1,this.removeDebugStyles(),O.info("CSS debugging mode disabled")}analyzeWidget(e){const t=e.getAttribute("data-widgetic-instance")||"unknown",i=[],n=[];this.detectCSSConflicts(e,i),this.checkStyleIsolation(e,n);const s={widgetId:t,conflicts:i,isolationScore:this.calculateIsolationScore(e,i),recommendations:n};return this.debugMode&&this.displayDebugReport(s),s}detectCSSConflicts(e,t){const i=window.getComputedStyle(e);["font-family","font-size","color","background-color","margin","padding","border","box-sizing"].forEach((n=>{const s=i.getPropertyValue(n);i.getPropertyPriority(n),this.isExternalStyle(e,n,s)&&t.push({property:n,widgetValue:this.getWidgetStyleValue(e,n),externalValue:s,specificity:this.calculateSpecificity(e,n),source:this.getStyleSource(e,n)})}))}checkStyleIsolation(e,t){e.getAttribute("data-widgetic-instance")||t.push("Add data-widgetic-instance attribute for proper namespace isolation");const i=window.getComputedStyle(e);Array.from(i).some((e=>e.startsWith("--widgetic-")))||t.push("Use CSS custom properties (--widgetic-*) for better theme isolation");const n=i.getPropertyValue("contain");n.includes("layout")&&n.includes("style")||t.push("Apply CSS containment (contain: layout style paint) for better isolation");"auto"===i.getPropertyValue("z-index")&&this.hasStackingContext(e)&&t.push("Consider explicit z-index management to prevent stacking conflicts")}calculateIsolationScore(e,t){let i=100;i-=10*t.length;const n=window.getComputedStyle(e),s=n.getPropertyValue("contain");s.includes("layout")||(i-=15),s.includes("style")||(i-=15),s.includes("paint")||(i-=10);"isolate"!==n.getPropertyValue("isolation")&&(i-=10);e.getAttribute("data-widgetic-instance")||(i-=15);return"border-box"!==n.getPropertyValue("box-sizing")&&(i-=5),Math.max(0,i)}isExternalStyle(e,t,i){const n=document.createElement(e.tagName.toLowerCase());n.style.cssText=e.getAttribute("style")||"",document.body.appendChild(n);const s=window.getComputedStyle(n).getPropertyValue(t);return document.body.removeChild(n),i!==s&&!this.isWidgetStyle(e,t)}isWidgetStyle(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return!1;return this.getMatchingCSSRules(e).some((e=>{var n;return(null===(n=e.selectorText)||void 0===n?void 0:n.includes(`[data-widgetic-instance="${i}"]`))&&e.style.getPropertyValue(t)}))}getWidgetStyleValue(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return"";const n=this.getMatchingCSSRules(e).find((e=>{var t;return null===(t=e.selectorText)||void 0===t?void 0:t.includes(`[data-widgetic-instance="${i}"]`)}));return(null==n?void 0:n.style.getPropertyValue(t))||""}calculateSpecificity(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return 0;const n=i.selectorText||"";let s=0;return s+=100*(n.match(/#/g)||[]).length,s+=10*(n.match(/[\.\[]/g)||[]).length,s+=(n.match(/[a-zA-Z]/g)||[]).length,s}getStyleSource(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return"unknown";if(i.parentStyleSheet){const e=i.parentStyleSheet;if(e.href)return e.href;if(e.ownerNode)return"inline styles"}return"unknown"}getMatchingCSSRules(e){const t=[];try{for(let i=0;i<document.styleSheets.length;i++){const n=document.styleSheets[i];try{const i=n.cssRules||n.rules;for(let n=0;n<i.length;n++){const s=i[n];s.selectorText&&e.matches(s.selectorText)&&t.push(s)}}catch(e){continue}}}catch(e){O.warn("Failed to analyze CSS rules",{error:e})}return t}hasStackingContext(e){const t=window.getComputedStyle(e),i=t.getPropertyValue("position"),n=t.getPropertyValue("z-index"),s=t.getPropertyValue("transform"),o=t.getPropertyValue("opacity");return"static"!==i&&"auto"!==n||"none"!==s||parseFloat(o)<1}addDebugStyles(){const e="widgetic-css-debug-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n /* CSS Debug Mode Styles */\n widgetic-widget[data-widgetic-instance] {\n outline: 2px dashed #007bff !important;\n outline-offset: 2px !important;\n position: relative !important;\n }\n\n widgetic-widget[data-widgetic-instance]::before {\n content: "Widget: " attr(data-widgetic-instance) !important;\n position: absolute !important;\n top: -20px !important;\n left: 0 !important;\n background: #007bff !important;\n color: white !important;\n padding: 2px 6px !important;\n font-size: 10px !important;\n font-family: monospace !important;\n z-index: 10000 !important;\n pointer-events: none !important;\n }\n\n widgetic-widget[data-error="true"] {\n outline-color: #dc3545 !important;\n }\n\n widgetic-widget[data-loading="true"] {\n outline-color: #ffc107 !important;\n }\n\n widgetic-widget[data-ready="true"] {\n outline-color: #28a745 !important;\n }\n ',document.head.appendChild(t)}removeDebugStyles(){const e=document.getElementById("widgetic-css-debug-styles");e&&e.remove()}displayDebugReport(e){}monitorWidget(e){if(this.trackedElements.has(e))return;this.trackedElements.add(e);new MutationObserver((e=>{e.forEach((e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.debugMode}))})).observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:["style","class"]})}}Ri.instance=null;const Pi=Ri.getInstance();function zi(){Pi.enableDebugMode()}function _i(){Pi.disableDebugMode()}class Fi{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){const i=this.listeners.get(e);return i&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}emit(e,...t){const i=this.listeners.get(e);return!(!i||0===i.size)&&(i.forEach((e=>{try{e(...t)}catch(e){}})),!0)}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}}class $i extends Fi{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set;const e=new t.Configuration({basePath:X()});this.abTestingApi=new t.ABTestingApi(e),this.compositionsApi=new t.CompositionsApi(e),this.widgetManager=xi.getInstance(),this.messenger=new xt,this.setupEventListeners()}static getInstance(){return $i.instance||($i.instance=new $i),$i.instance}setupEventListeners(){this.widgetManager.addEventListener("widget_ready",(e=>{this.setupWidgetConversionTracking(e.widgetId)})),this.widgetManager.addEventListener("custom_event",(e=>{this.handleWidgetCustomEvent(e)})),this.widgetManager.addEventListener("media_play",(e=>{this.handleMediaEvent("plays",e)})),this.widgetManager.addEventListener("form_submit",(e=>{this.handleFormEvent("submissions",e)})),this.widgetManager.addEventListener("widget_click",(e=>{this.handleClickEvent(e)}))}getTestConfig(e){return i(this,void 0,void 0,(function*(){var t;try{const n=yield this.abTestingApi.getABTestConfig({id:e});if(!n)return D.warn("A/B test not found",{experimentId:e}),null;const s=(yield Promise.all((n.variants||[]).map((e=>i(this,void 0,void 0,(function*(){try{const t=e.composition_id||e.compositionId||"";return{id:e.id||"",compositionId:t,embedCode:this.generateEmbedCode(t),trafficPercentage:e.traffic_percentage||e.trafficPercentage||0}}catch(t){return D.error("Failed to fetch composition for variant",{variantId:e.id,compositionId:e.compositionId,error:t}),null}})))))).filter((e=>null!==e));if(0===s.length)return D.warn("No valid variants found for A/B test",{experimentId:e}),null;const o={experimentId:n.test_id||e,isActive:"running"===n.status,winningVariant:void 0,variants:s,successMetrics:n.success_metrics||["impressions"],primaryMetric:(null===(t=n.success_metrics)||void 0===t?void 0:t[0])||"impressions"};return D.info("A/B test config loaded",{experimentId:e,config:o}),o}catch(t){return t&&"object"==typeof t&&"status"in t&&404===t.status?(D.warn("A/B test not found",{experimentId:e}),null):(D.error("Failed to load A/B test config",{experimentId:e,error:t}),null)}}))}getVariantAssignment(e,t){return i(this,void 0,void 0,(function*(){try{const i=yield this.getTestConfig(e);if(!i)return null;if(i.winningVariant){const t=i.variants.find((e=>e.id===i.winningVariant));if(t){const i={variantId:t.id,compositionId:t.compositionId,embedCode:t.embedCode};return localStorage.setItem(`ab_test_${e}`,JSON.stringify(i)),this.assignments.set(e,i),t}}const n=this.selectVariant(i.variants,t);if(!n)return null;const s={variantId:n.id,compositionId:n.compositionId,embedCode:n.embedCode};return localStorage.setItem(`ab_test_${e}`,JSON.stringify(s)),this.assignments.set(e,s),yield this.setupConversionTracking(e,i,s),n}catch(t){return D.error("Failed to get variant assignment",{experimentId:e,error:t}),null}}))}setupConversionTracking(e,t,n){return i(this,void 0,void 0,(function*(){try{const i=yield this.findTrackingTargets(n.compositionId,t.successMetrics),s={experimentId:e,variantId:n.variantId,metrics:t.successMetrics,trackingTargets:i};this.conversionSetups.set(e,s),D.debug("Conversion tracking setup complete",{experimentId:e,trackingTargets:i})}catch(t){D.error("Failed to setup conversion tracking",{experimentId:e,error:t})}}))}findTrackingTargets(e,t){return i(this,void 0,void 0,(function*(){try{const e={},i={clicks:["button","a","[data-click-track]","[onclick]"],conversions:["form",'button[type="submit"]',"[data-conversion]"],plays:["video","audio","[data-play]",".play-button"],submissions:["form","[data-form]"],downloads:["a[download]","[data-download]"],signups:["form","[data-signup]",".signup-form"]};for(const n of t){const t=i[n]||[];e[n]=t}return e}catch(t){return D.error("Failed to find tracking targets",{compositionId:e,error:t}),{}}}))}selectorExistsInContent(e,t){const i=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")){const e=t.slice(1,-1);return i.includes(e)}if(t.startsWith(".")){const e=t.slice(1);return i.includes(`class="${e}"`)||i.includes(`class='${e}'`)}return i.includes(`<${t}`)}setupWidgetConversionTracking(e){return i(this,void 0,void 0,(function*(){for(const[t,i]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(e))continue;const n=this.messenger.createWidgetController(e);i.metrics.includes("clicks")&&(yield this.setupClickTracking(n,t,i.variantId)),(i.metrics.includes("submissions")||i.metrics.includes("conversions"))&&(yield this.setupFormTracking(n,t,i.variantId)),i.metrics.includes("plays")&&(yield this.setupMediaTracking(n,t,i.variantId)),D.debug("Widget conversion tracking setup",{widgetId:e,experimentId:t})}catch(i){D.error("Failed to setup widget conversion tracking",{widgetId:e,experimentId:t,error:i})}}))}setupClickTracking(e,t,n){return i(this,void 0,void 0,(function*(){e.subscribe("click",(e=>i(this,void 0,void 0,(function*(){yield this.trackConversion(t,n,"clicks",{element:e.element,timestamp:e.timestamp})})))),yield e.callFunction("setupEventListener","click",(e=>{var i;this.trackConversion(t,n,"clicks",{target:null===(i=e.target)||void 0===i?void 0:i.tagName,timestamp:Date.now()})}))}))}setupFormTracking(e,t,n){return i(this,void 0,void 0,(function*(){e.subscribe("form-submit",(e=>i(this,void 0,void 0,(function*(){yield this.trackConversion(t,n,"submissions",{formData:e.formData,timestamp:e.timestamp})})))),e.subscribe("conversion",(e=>i(this,void 0,void 0,(function*(){yield this.trackConversion(t,n,"conversions",{conversionType:e.type,value:e.value,timestamp:e.timestamp})}))))}))}setupMediaTracking(e,t,n){return i(this,void 0,void 0,(function*(){e.subscribe("media-play",(e=>i(this,void 0,void 0,(function*(){yield this.trackConversion(t,n,"plays",{mediaType:e.mediaType,duration:e.duration,timestamp:e.timestamp})}))))}))}handleWidgetCustomEvent(e){return i(this,void 0,void 0,(function*(){var t;for(const[i,n]of Array.from(this.conversionSetups.entries()))if((null===(t=e.data)||void 0===t?void 0:t.experimentId)===i){const t=e.data.conversionType||"custom";yield this.trackConversion(i,n.variantId,t,e.data)}}))}handleMediaEvent(e,t){return i(this,void 0,void 0,(function*(){for(const[i,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(e)&&(yield this.trackConversion(i,n.variantId,e,t.data))}))}handleFormEvent(e,t){return i(this,void 0,void 0,(function*(){for(const[i,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(e)&&(yield this.trackConversion(i,n.variantId,e,t.data))}))}handleClickEvent(e){return i(this,void 0,void 0,(function*(){for(const[t,i]of Array.from(this.conversionSetups.entries()))i.metrics.includes("clicks")&&(yield this.trackConversion(t,i.variantId,"clicks",e.data))}))}trackConversion(e,t,n,s,o){return i(this,void 0,void 0,(function*(){try{const i=`${e}_${t}_${(null==o?void 0:o.userId)||(null==o?void 0:o.sessionId)||"anonymous"}`;if(this.trackedConversions.has(i))return void D.debug("Conversion already tracked for this user",{experimentId:e,variantId:t,conversionType:n});const r={event_type:"conversion",data:Ut({experimentId:e,variantId:t,userId:null==o?void 0:o.userId,sessionId:(null==o?void 0:o.sessionId)||this.getSessionId(),conversionType:n,timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:r}),this.trackedConversions.add(i),this.emit("conversion",{experimentId:e,variantId:t,conversionType:n,data:s}),D.info("Conversion tracked",{experimentId:e,variantId:t,conversionType:n,data:s})}catch(i){D.error("Failed to track conversion",{experimentId:e,variantId:t,conversionType:n,error:i})}}))}trackImpression(e,t,n){return i(this,void 0,void 0,(function*(){try{const i={event_type:"impression",data:Ut({experimentId:e,variantId:t,userId:null==n?void 0:n.userId,sessionId:(null==n?void 0:n.sessionId)||this.getSessionId(),timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:i}),D.debug("Impression tracked",{experimentId:e,variantId:t})}catch(i){D.error("Failed to track impression",{experimentId:e,variantId:t,error:i})}}))}validateGoalTracking(e,t){return i(this,void 0,void 0,(function*(){const i=[],n=[];try{for(const n of e){const e=yield this.validateVariantCapabilities(n,t);i.push(...e)}if(i.length>0){const e=Array.from(new Set(i.map((e=>e.metric))));n.push(`Consider adding trackable elements to your compositions for: ${e.join(", ")}`),e.includes("clicks")&&n.push("Add clickable elements like buttons, links, or interactive components"),e.includes("submissions")&&n.push("Add form elements to track form submissions"),e.includes("plays")&&n.push("Add media elements (audio/video) to track media plays"),e.includes("conversions")&&n.push("Implement custom conversion tracking using widgetic:conversion events")}const s=0===i.length;return D.info("Goal tracking validation completed",{variants:e.length,successMetrics:t,issues:i.length,isValid:s}),{isValid:s,issues:i,recommendations:n}}catch(e){return D.error("Goal tracking validation failed",{error:e}),{isValid:!1,issues:[{variant:"all",metric:"system",reason:"Validation system error"}],recommendations:["Please try again or contact support"]}}}))}validateVariantCapabilities(e,t){return i(this,void 0,void 0,(function*(){const i=[];try{const n=document.createElement("div");n.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(n);try{const s={compositionId:e.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},o=`validation_${e.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(o,s,n)){const n=this.messenger.getWidgetController(o);let s=null;if(n)try{s=yield n.callFunction("getCapabilities",[])}catch(t){D.warn("Widget does not expose getCapabilities method",{compositionId:e.composition_id})}for(const n of t){const t=this.checkMetricSupport(e,n,s);t&&i.push(t)}yield this.widgetManager.unregisterWidget(o)}else for(const n of t)i.push({variant:e.name,metric:n,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(n)}}catch(n){D.error("Failed to validate variant capabilities",{variant:e.name,error:n});for(const n of t)i.push({variant:e.name,metric:n,reason:"Validation error occurred"})}return i}))}checkMetricSupport(e,t,i){var n;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(n=i.textCapabilities.fields)||void 0===n?void 0:n.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,n,s;if(["interactive","form","media","gallery"].includes(e.type))return!0;if(null===(t=e.mediaCapabilities)||void 0===t?void 0:t.supportsPlay)return!0;if(null===(i=e.contentCapabilities)||void 0===i?void 0:i.supportsNavigation)return!0;if(null===(s=null===(n=e.textCapabilities)||void 0===n?void 0:n.fields)||void 0===s?void 0:s.length)return!0;const o=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&o.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t){if(!e||0===e.length)return null;const i=t.userId||t.sessionId||"anonymous",n=this.createDeterministicHash(i),s=Math.abs(n)%100;let o=0;for(const t of e)if(o+=t.trafficPercentage,s<o)return t;return e[e.length-1]}createDeterministicHash(e){let t=0;for(let i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return t}createAssignment(e,t,n){return i(this,void 0,void 0,(function*(){try{const i=this.detectDeviceType(n.userAgent),s=Ut({experimentId:e,variantId:t.variantId,userId:n.userId,sessionId:n.sessionId||this.getSessionId(),userAgent:n.userAgent||navigator.userAgent,ipAddress:n.ipAddress,deviceType:i});yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:s}),D.debug("Assignment created in backend",{experimentId:e,variantId:t.variantId})}catch(t){D.error("Failed to create assignment in backend",{experimentId:e,error:t})}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){let e=localStorage.getItem("widgetic_session_id");return e||(e="session_"+Math.random().toString(36).substr(2,9)+"_"+Date.now(),localStorage.setItem("widgetic_session_id",e)),e}detectDeviceType(e){if(!e)return"desktop";const t=e.toLowerCase();return/tablet|ipad|playbook|silk/.test(t)?"tablet":/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(t)?"mobile":"desktop"}}$i.instance=null;class Ni{constructor(e){this.deviceDetector=Be(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},e),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),O.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Ni.instance&&e&&(Ni.instance=new Ni(e)),!Ni.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Ni.instance}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){O.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){O.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(O.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),O.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):O.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return i(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),O.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){O.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return i(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void O.warn("[AnalyticsTracker] No API endpoint configured");const n=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),s=yield G(),o=new t.Configuration({basePath:this.config.apiEndpoint,accessToken:()=>i(this,void 0,void 0,(function*(){return s})),headers:{"X-SDK-Version":`embed-sdk/${$}`}}),r=new t.AnalyticsApi(o);yield r.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:n}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){O.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],O.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){O.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),O.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),O.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),Ni.instance=null,O.debug("[AnalyticsTracker] Destroyed")}}const Ui="undefined"!=typeof HTMLElement?HTMLElement:class{};class Hi extends Ui{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=$i.getInstance(),this.widgetManager=xi.getInstance(),this.analyticsTracker=Ni.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return i(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return D.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};if(this.renderLoading(),this.assignment=yield this.manager.getVariantAssignment(this.experimentId,e),!this.assignment)return D.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),D.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){D.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){t!==i&&"experiment-id"===e&&this.connectedCallback()}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return i(this,void 0,void 0,(function*(){var e,t,i;if(this.assignment&&this.shadowRoot)try{const i=document.createElement("div");i.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",i.setAttribute("data-ab-experiment",this.experimentId||""),i.setAttribute("data-ab-variant",this.assignment.variantId);const n=this.createEmbedElement(this.assignment.embedCode);if(n){i.appendChild(n);const s={compositionId:this.assignment.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${this.assignment.variantId}_${Date.now()}`,s,n),this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",this.assignment.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(i),this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId},bubbles:!0}))}catch(e){D.error("Failed to render variant",{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}createEmbedElement(e){var t;try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return D.warn("No element found in embed code",{embedCode:e}),null;const s=n.cloneNode(!0);return s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",(null===(t=this.assignment)||void 0===t?void 0:t.variantId)||""),s}catch(t){return D.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),D.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){D.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target;this.isClickableElement(i)&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",{element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||"",timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target;"FORM"===t.tagName&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",{formId:t.id||"unknown",timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",{mediaType:t.tagName.toLowerCase(),duration:t.duration||0,timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return i(this,void 0,void 0,(function*(){if(!this.impressionTracked&&this.experimentId&&this.assignment)try{const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};yield this.manager.trackImpression(this.experimentId,this.assignment.variantId,e),this.impressionTracked=!0,this.analyticsTracker.trackCompositionView({experiment_id:this.experimentId,variant_id:this.assignment.variantId,composition_id:this.assignment.compositionId}),D.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){D.error("Failed to track impression",{experimentId:this.experimentId,error:e})}}))}handleConversionEvent(e){this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),this.analyticsTracker.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;D.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;D.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}cleanup(){if(this.conversionListeners.forEach((e=>e())),this.conversionListeners.clear(),this.widgetInstance)try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){D.warn("Failed to cleanup widget instance",{error:e})}this.impressionTracked=!1,this.assignment=null,this.widgetInstance=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",Hi))}}Hi.register();const ji="undefined"!=typeof HTMLElement?HTMLElement:class{};class Bi extends ji{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.widgetManager=Ai(),O.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)O.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return O.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");O.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){O.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return i(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(O.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),O.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),O.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){O.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return i(this,void 0,void 0,(function*(){try{const i=X(),n=new t.Configuration({basePath:i,headers:{"X-SDK-Version":"embed-sdk/translations"}}),s=new t.TranslationsApi(n),o=yield s.getTranslationConfig({id:e});return(null==o?void 0:o.data)||null}catch(e){throw O.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";O.debug("[TranslationElement] Available languages:",i),O.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return O.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return O.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{O.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}O.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{O.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return i(this,void 0,void 0,(function*(){const t=Te(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{O.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){O.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return i(this,void 0,void 0,(function*(){try{const i=X(),n=new t.Configuration({basePath:i,headers:{"X-SDK-Version":"embed-sdk/translations"}}),s=new t.TranslationsApi(n);yield s.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){O.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,n){return i(this,void 0,void 0,(function*(){try{const i={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:n,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(i),O.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:n})}catch(e){O.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return i(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,O.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){O.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",Bi),O.info("[TranslationElement] Custom element registered")))}catch(e){O.error("[TranslationElement] Failed to register custom element:",e)}}}Bi.register();const Vi={WidgeticWidget:ft,registerWidgeticWidget:yt,getSDK:Wi,setApiKey:q,setTokenProvider:B,StaticApiKeyProvider:W,EndpointTokenProvider:R,FunctionTokenProvider:P,getConfiguration:ie},Ki={WidgetRenderer:zt,getWidgetRenderer:Ft,CustomElementRenderer:Ct,IframeRenderer:Pt,AuthManager:F,detectBrowserCapabilities:it,determineBestRenderMode:rt,parseWidgetConfig:se,generateInstanceId:Te,isValidWidgetElement:ke},qi={BatchApiClient:ct,getBatchClient:ut,ModuleLoader:gt,getModuleLoader:mt,WidgeticMessenger:xt,getMessenger:Mt,config:j,getApiUrl:Q,getCdnUrl:J,getTokenProvider:V,getAuthToken:G,DefaultTokenProvider:z,CSSDebugger:Ri,cssDebugger:Pi,enableCSSDebug:zi,disableCSSDebug:_i,log:O},Gi=Wi();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(yt(),Hi.register(),Bi.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=Gi,window.Widgetic={SDK:Gi,getSDK:Wi,EmbedSDK:Di,config:{API_URL:j.API_URL,API_VERSION:j.API_VERSION,CLIENT_URL:j.CLIENT_URL,PRODUCTION_URL:j.PRODUCTION_URL,NODE_ENV:j.NODE_ENV},log:O,WidgeticWidget:ft,registerWidgeticWidget:yt,cssDebugger:Pi,enableCSSDebug:()=>Pi.enableDebugMode(),disableCSSDebug:()=>Pi.disableDebugMode(),analyzeWidget:e=>Pi.analyzeWidget(e),ABTestManager:$i,ABTestElement:Hi,TranslationElement:Bi});class Yi{constructor(){this.textStates=new Map,this.debounceTimers=new Map,this.storageKey="widgetic-text-fields",this.storageVersion="1.0",this.maxStorageAge=6048e5,this.autoRestoreEnabled=!0,this.initialized=!1,this.securityManager=mi(),this.initialize()}static getInstance(){return Yi.instance||(Yi.instance=new Yi),Yi.instance}initialize(){this.initialized||(at()?(this.loadStoredState(),this.cleanupOldEntries(),this.initialized=!0,O.info("[TextFieldManager] Initialized successfully")):O.warn("[TextFieldManager] localStorage not available, text persistence disabled"))}registerTextField(e,t,i={}){const n=this.generateStateKey(e,t);O.debug(`[TextFieldManager] Registering text field: ${e}.${t}`,{config:i});const s=this.textStates.get(n);return s&&i.autoRestore&&this.shouldAutoRestore(s,i)&&O.debug(`[TextFieldManager] Auto-restoring text for ${n}`,{textLength:s.text.length,lastModified:new Date(s.lastModified)}),n}updateTextField(e,t,i,n={},s){const o=this.securityManager.validateTextFieldUpdate(e,t,i,s);if(!o.allowed)return O.warn(`[TextFieldManager] Security validation failed for ${e}.${t}`,{reason:o.reason,severity:o.severity}),void("undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e,fieldId:t,reason:o.reason,severity:o.severity,originalTextLength:i.length,timestamp:Date.now()}})));const r=o.sanitizedText||i,a=this.generateStateKey(e,t);let d=r;n.maxLength&&r.length>n.maxLength&&(O.warn(`[TextFieldManager] Text exceeds maxLength (${n.maxLength}), truncating`),d=r.substring(0,n.maxLength));const c={instanceId:e,fieldId:t,text:d,lastModified:Date.now(),textType:n.textType||"custom",metadata:Object.assign(Object.assign({},s),{characterCount:d.length,wordCount:this.countWords(d),sanitized:r!==i})};this.textStates.set(a,c),n.autoPersist&&n.persistState&&this.debouncePersist(a,n.debounceDelay||1e3),O.debug(`[TextFieldManager] Updated text field: ${a}`,{textLength:d.length,textType:c.textType,sanitized:r!==i})}getTextField(e,t){const i=this.generateStateKey(e,t);return this.textStates.get(i)||null}getWidgetTextFields(e){const t=[];for(const[i,n]of this.textStates)n.instanceId===e&&t.push(n);return t}clearTextField(e,t){const i=this.generateStateKey(e,t);this.textStates.delete(i),this.clearDebounceTimer(i),this.persistState(),O.debug(`[TextFieldManager] Cleared text field: ${i}`)}clearWidgetTextFields(e){const t=[];for(const[i,n]of this.textStates)n.instanceId===e&&t.push(i);t.forEach((e=>{this.textStates.delete(e),this.clearDebounceTimer(e)})),this.persistState(),O.debug(`[TextFieldManager] Cleared ${t.length} text fields for widget: ${e}`)}persistTextFields(){this.persistState()}shouldAutoRestore(e,t){if(!this.autoRestoreEnabled||!t.autoRestore)return!1;const i=t.autoRestoreTimeout||864e5;return Date.now()-e.lastModified<=i&&e.text.trim().length>0}generateStateKey(e,t){return`${e}:${t}`}debouncePersist(e,t){this.clearDebounceTimer(e);const i=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(e)}),t);this.debounceTimers.set(e,i)}clearDebounceTimer(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e))}loadStoredState(){try{const e=localStorage.getItem(this.storageKey);if(!e)return;const t=JSON.parse(e);if(t.version!==this.storageVersion)return O.info("[TextFieldManager] Storage version mismatch, clearing stored data"),void localStorage.removeItem(this.storageKey);t.textStates&&(this.textStates=new Map(Object.entries(t.textStates)),O.debug(`[TextFieldManager] Loaded ${this.textStates.size} text field states from storage`)),"boolean"==typeof t.autoRestoreEnabled&&(this.autoRestoreEnabled=t.autoRestoreEnabled)}catch(e){O.warn("[TextFieldManager] Failed to load stored state:",e),localStorage.removeItem(this.storageKey)}}persistState(){if(at())try{const e={version:this.storageVersion,textStates:Object.fromEntries(this.textStates),timestamp:Date.now(),autoRestoreEnabled:this.autoRestoreEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e)),O.debug(`[TextFieldManager] Persisted state for ${this.textStates.size} text fields`)}catch(e){O.warn("[TextFieldManager] Failed to persist state:",e)}}cleanupOldEntries(){const e=Date.now()-this.maxStorageAge,t=[];for(const[i,n]of this.textStates)n.lastModified<e&&t.push(i);t.length>0&&(t.forEach((e=>this.textStates.delete(e))),this.persistState(),O.debug(`[TextFieldManager] Cleaned up ${t.length} old text field entries`))}countWords(e){return e.trim().split(/\s+/).filter((e=>e.length>0)).length}setAutoRestoreEnabled(e){this.autoRestoreEnabled=e,this.persistState(),O.debug("[TextFieldManager] Auto-restore "+(e?"enabled":"disabled"))}getStats(){const e=Array.from(this.textStates.values()),t=e.reduce(((e,t)=>e+t.text.length),0),i=e.map((e=>e.lastModified));return{totalFields:e.length,totalCharacters:t,avgCharactersPerField:e.length>0?Math.round(t/e.length):0,oldestEntry:i.length>0?Math.min(...i):null,newestEntry:i.length>0?Math.max(...i):null}}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.textStates.clear(),at()&&localStorage.removeItem(this.storageKey),O.debug("[TextFieldManager] Cleaned up all data")}configureSecurity(e){this.securityManager.updateConfig(e),O.debug("[TextFieldManager] Security configuration updated")}isInstanceBlocked(e){return this.securityManager.isInstanceBlocked(e)}isInstanceSuspicious(e){return this.securityManager.isInstanceSuspicious(e)}unblockInstance(e){this.securityManager.unblockInstance(e),O.info(`[TextFieldManager] Unblocked instance: ${e}`)}getSecurityStats(){return this.securityManager.getSecurityStats()}validateText(e,t,i,n){return this.securityManager.validateTextFieldUpdate(e,t,i,n)}}function Qi(){return Yi.getInstance()}var Ji=Object.freeze({__proto__:null,TextFieldManager:Yi,getTextField:function(e,t){return Qi().getTextField(e,t)},getTextFieldManager:Qi,registerTextField:function(e,t,i){return Qi().registerTextField(e,t,i)},updateTextField:function(e,t,i,n,s){Qi().updateTextField(e,t,i,n,s)}});e.ABTestElement=Hi,e.ABTestManager=$i,e.AuthError=_,e.AuthManager=F,e.BatchApiClient=ct,e.CSSDebugger=Ri,e.CustomElementRenderer=Ct,e.DefaultTokenProvider=z,e.EmbedSDK=Di,e.EndpointTokenProvider=R,e.FunctionTokenProvider=P,e.HighLevelAPI=Vi,e.IframeRenderer=Pt,e.LowLevelAPI=qi,e.MidLevelAPI=Ki,e.ModuleLoader=gt,e.StaticApiKeyProvider=W,e.TranslationElement=Bi,e.WidgetRenderer=zt,e.WidgeticEmbedSDK=Di,e.WidgeticMessenger=xt,e.WidgeticWidget=ft,e.analyzeWidgetCSS=function(e){return Pi.analyzeWidget(e)},e.config=j,e.cssDebugger=Pi,e.default=Gi,e.detectBrowserCapabilities=it,e.determineBestRenderMode=rt,e.disableCSSDebug=_i,e.enableCSSDebug=zi,e.generateInstanceId=Te,e.getApiUrl=Q,e.getAuthManager=K,e.getAuthToken=G,e.getBatchClient=ut,e.getCdnUrl=J,e.getConfiguration=ie,e.getMessenger=Mt,e.getModuleLoader=mt,e.getSDK=Wi,e.getTokenProvider=V,e.getWidgetRenderer=Ft,e.isValidWidgetElement=ke,e.log=O,e.monitorWidgetCSS=function(e){Pi.monitorWidget(e)},e.parseWidgetConfig=se,e.registerWidgeticWidget=yt,e.resetBatchClient=function(){lt=null},e.resetMessenger=function(){At&&(At.cleanup(),At=null)},e.resetModuleLoader=function(){pt=null},e.resetWidgetRenderer=function(){_t&&_t.cleanupAll(),_t=null},e.setApiKey=q,e.setTokenProvider=B,e.toCamel=Nt,e.toSnake=Ut,Object.defineProperty(e,"__esModule",{value:!0})}));
|